import os import json import argparse from glob import glob from collections import defaultdict from shapely.geometry import box from shapely.ops import unary_union import numpy as np import matplotlib matplotlib.use("Agg") # safe for headless / servers import matplotlib.pyplot as plt # ====================== COCO -> Super mapping ====================== COCO_TO_SUPER = { 'person': 'person', 'bicycle': 'vehicle', 'car': 'vehicle', 'motorcycle': 'vehicle', 'airplane': 'vehicle', 'bus': 'vehicle', 'train': 'vehicle', 'truck': 'vehicle', 'boat': 'vehicle', 'traffic light': 'outdoor', 'fire hydrant': 'outdoor', 'stop sign': 'outdoor', 'parking meter': 'outdoor', 'bench': 'outdoor', 'bird': 'animal', 'cat': 'animal', 'dog': 'animal', 'horse': 'animal', 'sheep': 'animal', 'cow': 'animal', 'elephant': 'animal', 'bear': 'animal', 'zebra': 'animal', 'giraffe': 'animal', 'backpack': 'accessory', 'umbrella': 'accessory', 'handbag': 'accessory', 'tie': 'accessory', 'suitcase': 'accessory', 'frisbee': 'sports', 'skis': 'sports', 'snowboard': 'sports', 'sports ball': 'sports', 'kite': 'sports', 'baseball bat': 'sports', 'baseball glove': 'sports', 'skateboard': 'sports', 'surfboard': 'sports', 'tennis racket': 'sports', 'bottle': 'kitchen', 'wine glass': 'kitchen', 'cup': 'kitchen', 'fork': 'kitchen', 'knife': 'kitchen', 'spoon': 'kitchen', 'bowl': 'kitchen', 'banana': 'food', 'apple': 'food', 'sandwich': 'food', 'orange': 'food', 'broccoli': 'food', 'carrot': 'food', 'hot dog': 'food', 'pizza': 'food', 'donut': 'food', 'cake': 'food', 'chair': 'furniture', 'couch': 'furniture', 'potted plant': 'furniture', 'bed': 'furniture', 'dining table': 'furniture', 'toilet': 'furniture', 'tv': 'electronic', 'laptop': 'electronic', 'mouse': 'electronic', 'remote': 'electronic', 'keyboard': 'electronic', 'cell phone': 'electronic', 'microwave': 'appliance', 'oven': 'appliance', 'toaster': 'appliance', 'sink': 'appliance', 'refrigerator': 'appliance', 'book': 'indoor', 'clock': 'indoor', 'vase': 'indoor', 'scissors': 'indoor', 'teddy bear': 'indoor', 'hair drier': 'indoor', 'toothbrush': 'indoor' } # ====================== Aggregation / Sorting ====================== def _aggregate_label_stats(results: dict): """ Aggregate GT totals and matches across all techniques for the current label space (label = class or super, depending on prior regrouping). """ totals = defaultdict(int) matches = defaultdict(int) for tech_metrics in results.values(): for label, stats in tech_metrics.get("per_class", {}).items(): totals[label] += int(stats.get("gt_objects", 0)) matches[label] += int(stats.get("matched", 0)) return totals, matches def _class_order(results: dict, mode: str = "accuracy", min_instances: int = 10, face_overlap_stats: dict | None = None): """ Returns a list of label names ordered by: - "accuracy": overall matched/gt desc (NaN last), then alpha - "prevalence": overall gt desc, then alpha - "alpha": alphabetical - "face_iou": average IoU with face (desc), then alpha - "face_cover": average coverage by faces (desc), then alpha Only labels with totals >= min_instances are included. NOTE: 'results' should already be in the desired label space (class or super). """ totals, matches = _aggregate_label_stats(results) labels = [c for c in totals.keys() if totals[c] >= min_instances] if mode == "prevalence": labels.sort(key=lambda c: (-totals[c], c)) return labels if mode == "alpha": labels.sort() return labels if mode in ("face_iou", "face_cover"): def metric(c): if not face_overlap_stats or c not in face_overlap_stats: return float("nan") key = "avg_iou" if mode == "face_iou" else "avg_coverage" return face_overlap_stats[c].get(key, float("nan")) labels.sort( key=lambda c: (np.isnan(metric(c)), -(metric(c) if not np.isnan(metric(c)) else -1.0), c) ) return labels # default: accuracy acc = { c: (matches[c] / totals[c]) if totals[c] > 0 else float("nan") for c in labels } labels.sort( key=lambda c: ( np.isnan(acc[c]), # NaNs last -(acc[c] if not np.isnan(acc[c]) else -1.0), # desc acc c # tie-break alpha ) ) return labels # ====================== Regrouping helpers (class -> super) ====================== def _to_group(label: str, group_by: str) -> str: if group_by == "super": return COCO_TO_SUPER.get(label, label) # fallback to label if missing return label def _regroup_results_to(results: dict, group_by: str) -> dict: """ Convert technique->{'overall', 'per_class'} to desired label space: - if group_by == 'class', return results as is. - if group_by == 'super', aggregate per_class into super-categories. """ if group_by != "super": return results regrouped = {} for tech, metrics in results.items(): agg = defaultdict(lambda: {"gt_objects": 0, "matched": 0, "detection_accuracy": 0.0}) for cls, stats in metrics.get("per_class", {}).items(): g = _to_group(cls, "super") agg[g]["gt_objects"] += int(stats.get("gt_objects", 0)) agg[g]["matched"] += int(stats.get("matched", 0)) # recompute acc for g, s in agg.items(): tot = s["gt_objects"]; mat = s["matched"] s["detection_accuracy"] = (mat / tot) if tot > 0 else 0.0 regrouped[tech] = { "overall": dict(metrics.get("overall", {})), # unchanged "per_class": dict(agg) } return regrouped def _regroup_face_stats_to(face_stats: dict, group_by: str) -> dict: """ Convert {class: {count,sum_iou,avg_iou,sum_coverage,avg_coverage}} to desired label space. If group_by == 'super', sum counts & sums by super and recompute avgs. """ if group_by != "super": return face_stats counts = defaultdict(int) sums_iou = defaultdict(float) sums_cov = defaultdict(float) for cls, d in face_stats.items(): g = _to_group(cls, "super") counts[g] += int(d.get("count", 0)) sums_iou[g] += float(d.get("sum_iou", 0.0)) sums_cov[g] += float(d.get("sum_coverage", 0.0)) out = {} for g in counts.keys(): n = counts[g] si = sums_iou[g] sc = sums_cov[g] out[g] = { "count": n, "sum_iou": si, "avg_iou": (si / n) if n > 0 else float("nan"), "sum_coverage": sc, "avg_coverage": (sc / n) if n > 0 else float("nan"), } return out # ====================== Visualization helpers ====================== def _face_filter_label(face_mode: str) -> str: return { "overlap": "overlap", "nonoverlap": "nonoverlap", "any": "any", "delta": "Δ(overlap−nonoverlap)", }.get(face_mode, face_mode) # ====================== Base (non-delta) plots ====================== def save_confusion_style_matrix(results: dict, out_path: str, title: str = "Technique × Label (matched/GT; %)", class_sort: str = "accuracy", min_instances: int = 10, face_overlap_stats: dict | None = None, face_mode: str = "overlap", x_label_name: str = "Class"): """ Builds a Technique x Label matrix from results['per_class'] (label = class or super). """ techniques = sorted(results.keys()) labels = _class_order(results, class_sort, min_instances, face_overlap_stats) if not techniques or not labels: raise ValueError("No techniques or labels found to plot (check filters).") n_t, n_c = len(techniques), len(labels) matched = np.zeros((n_t, n_c), dtype=int) total = np.zeros((n_t, n_c), dtype=int) for i, tech in enumerate(techniques): per = results[tech].get("per_class", {}) for j, lab in enumerate(labels): d = per.get(lab) if d: matched[i, j] = int(d.get("matched", 0)) total[i, j] = int(d.get("gt_objects", 0)) with np.errstate(divide="ignore", invalid="ignore"): acc = np.where(total > 0, (matched / total) * 100.0, np.nan) # Marginals (Σ) row_m_matched = matched.sum(axis=1) row_m_total = total.sum(axis=1) col_m_matched = matched.sum(axis=0) col_m_total = total.sum(axis=0) all_matched = matched.sum() all_total = total.sum() # Extend with Σ row/col matched_ext = np.zeros((n_t + 1, n_c + 1), dtype=int) total_ext = np.zeros((n_t + 1, n_c + 1), dtype=int) acc_ext = np.full((n_t + 1, n_c + 1), np.nan, dtype=float) matched_ext[:n_t, :n_c] = matched total_ext[:n_t, :n_c] = total acc_ext[:n_t, :n_c] = acc matched_ext[:n_t, n_c] = row_m_matched total_ext[:n_t, n_c] = row_m_total acc_ext[:n_t, n_c] = np.where(row_m_total > 0, row_m_matched / row_m_total * 100.0, np.nan) matched_ext[n_t, :n_c] = col_m_matched total_ext[n_t, :n_c] = col_m_total acc_ext[n_t, :n_c] = np.where(col_m_total > 0, col_m_matched / col_m_total * 100.0, np.nan) matched_ext[n_t, n_c] = all_matched total_ext[n_t, n_c] = all_total acc_ext[n_t, n_c] = (all_matched / all_total * 100.0) if all_total > 0 else np.nan labels_ext = labels + ["Σ labels"] techniques_ext = techniques + ["Σ techniques"] # Plot fig_w = max(10, 0.6 * len(labels_ext) + 2) fig_h = max(5, 0.6 * len(techniques_ext) + 1) fig, ax = plt.subplots(figsize=(fig_w, fig_h)) cmap = plt.cm.Blues.copy() cmap.set_bad("#eeeeee") im = ax.imshow(np.ma.masked_invalid(acc_ext), cmap=cmap, vmin=0, vmax=100, aspect="auto") ax.set_xticks(np.arange(len(labels_ext))) ax.set_yticks(np.arange(len(techniques_ext))) # Append μ IoU/μ cov to labels if requested if face_overlap_stats and class_sort in ("face_iou", "face_cover"): def label_with_stat(c): info = face_overlap_stats.get(c, {}) if class_sort == "face_iou": avg = info.get("avg_iou", float("nan")) return f"{c}\n(μ IoU={avg:.2f})" if not np.isnan(avg) else c else: avg = info.get("avg_coverage", float("nan")) return f"{c}\n(μ cov={avg:.2f})" if not np.isnan(avg) else c core_labels = [label_with_stat(c) for c in labels] else: core_labels = labels ax.set_xticklabels(core_labels + ["Σ labels"], rotation=45, ha="right") ax.set_yticklabels(techniques_ext) ax.set_xlabel(f"MSCOCO {x_label_name} ({_face_filter_label(face_mode)}, ≥{min_instances} GT)") ax.set_ylabel("Technique") ax.set_title(title, pad=12) # Annotate: "matched/GT\nXX.X%" for i in range(acc_ext.shape[0]): for j in range(acc_ext.shape[1]): if not np.isnan(acc_ext[i, j]): ax.text(j, i, f"{matched_ext[i,j]}/{total_ext[i,j]}\n{acc_ext[i,j]:.1f}%", ha="center", va="center", fontsize=8) cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) cbar.set_label("Detection accuracy (%)", rotation=90, labelpad=10) fig.tight_layout() os.makedirs(os.path.dirname(out_path), exist_ok=True) fig.savefig(out_path, dpi=200, bbox_inches="tight") plt.close(fig) def save_heatmap(results: dict, out_path: str, title: str = "Detection accuracy by technique and label", class_sort: str = "accuracy", min_instances: int = 10, face_overlap_stats: dict | None = None, face_mode: str = "overlap", x_label_name: str = "Class"): """ Technique x Label heatmap from `results['per_class']` (label = class or super). """ techniques = sorted(results.keys()) labels = _class_order(results, class_sort, min_instances, face_overlap_stats) if not techniques or not labels: raise ValueError("No techniques or labels found to plot (check filters).") M = np.full((len(techniques), len(labels)), np.nan, dtype=float) for i, tech in enumerate(techniques): per = results[tech].get("per_class", {}) for j, lab in enumerate(labels): acc = per.get(lab, {}).get("detection_accuracy", None) if acc is not None: M[i, j] = acc * 100.0 M_masked = np.ma.masked_invalid(M) fig_w = max(10, 0.6 * len(labels) + 2) fig_h = 3 # compact row height fig, ax = plt.subplots(figsize=(fig_w, fig_h)) cmap = plt.cm.viridis.copy() cmap.set_bad("#eeeeee") im = ax.imshow(M_masked, cmap=cmap, aspect="auto", vmin=0, vmax=100) ax.set_xticks(np.arange(len(labels))) if face_overlap_stats and class_sort in ("face_iou", "face_cover"): def label_with_stat(c): info = face_overlap_stats.get(c, {}) if class_sort == "face_iou": avg = info.get("avg_iou", float("nan")) return f"{c}\n(μ IoU={avg:.2f})" if not np.isnan(avg) else c else: avg = info.get("avg_coverage", float("nan")) return f"{c}\n(μ cov={avg:.2f})" if not np.isnan(avg) else c xticklabels = [label_with_stat(c) for c in labels] else: xticklabels = labels ax.set_xticklabels(xticklabels, rotation=45, ha="right", fontsize=12) ax.set_yticks(np.arange(len(techniques))) ax.set_yticklabels(techniques, fontsize=12) # Annotate % for i in range(M.shape[0]): for j in range(M.shape[1]): val = M[i, j] if not np.isnan(val): ax.text(j, i, f"{val:.1f}%", ha="center", va="center", fontsize=12) cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.03) fig.tight_layout() os.makedirs(os.path.dirname(out_path), exist_ok=True) fig.savefig(out_path, dpi=200, bbox_inches="tight") plt.close(fig) # ====================== Δ (delta) plots ====================== def _merge_results_across_subsets(res_a: dict, res_b: dict) -> dict: """ Merge two results dicts (same shape as usual technique->metrics) by SUMMING counts. Useful in delta mode to build filtering/ordering totals from both overlap and nonoverlap. """ merged = {} for res in (res_a, res_b): for tech, metrics in res.items(): tgt = merged.setdefault(tech, {"overall": {"gt_objects": 0, "matched": 0, "detection_accuracy": 0.0}, "per_class": {}}) tgt["overall"]["gt_objects"] += int(metrics["overall"].get("gt_objects", 0)) tgt["overall"]["matched"] += int(metrics["overall"].get("matched", 0)) for lbl, stats in metrics.get("per_class", {}).items(): pc = tgt["per_class"].setdefault(lbl, {"gt_objects": 0, "matched": 0, "detection_accuracy": 0.0}) pc["gt_objects"] += int(stats.get("gt_objects", 0)) pc["matched"] += int(stats.get("matched", 0)) # recompute acc for tech, metrics in merged.items(): tot = metrics["overall"]["gt_objects"] mat = metrics["overall"]["matched"] metrics["overall"]["detection_accuracy"] = (mat / tot) if tot > 0 else 0.0 for lbl, stats in metrics["per_class"].items(): ct = stats["gt_objects"]; cm = stats["matched"] stats["detection_accuracy"] = (cm / ct) if ct > 0 else 0.0 return merged def _delta_matrix(overlap_results: dict, nonoverlap_results: dict, techniques: list[str], labels: list[str]) -> np.ndarray: """ Build a (tech x label) matrix of Δ accuracy (pp) = (overlap - nonoverlap)*100. Missing cells become NaN. """ D = np.full((len(techniques), len(labels)), np.nan, dtype=float) for i, tech in enumerate(techniques): per_o = overlap_results.get(tech, {}).get("per_class", {}) per_n = nonoverlap_results.get(tech, {}).get("per_class", {}) for j, lab in enumerate(labels): ao = per_o.get(lab, {}).get("detection_accuracy", None) an = per_n.get(lab, {}).get("detection_accuracy", None) if ao is None or an is None: D[i, j] = np.nan else: D[i, j] = (ao - an) * 100.0 return D def save_heatmap_delta(overlap_results: dict, nonoverlap_results: dict, out_path: str, title: str = "Δ accuracy (overlap − nonoverlap) by technique and label", class_sort: str = "accuracy", min_instances: int = 10, face_overlap_stats: dict | None = None, # use overlap stats for sorting/labels x_label_name: str = "Class"): """ Diverging heatmap showing Δ accuracy in percentage points. """ # Build ordering/filter totals from combined results combined_for_order = _merge_results_across_subsets(overlap_results, nonoverlap_results) techniques = sorted(set(overlap_results.keys()) | set(nonoverlap_results.keys())) labels = _class_order(combined_for_order, class_sort, min_instances, face_overlap_stats) if not techniques or not labels: raise ValueError("No techniques or labels found to plot (check filters).") D = _delta_matrix(overlap_results, nonoverlap_results, techniques, labels) D_masked = np.ma.masked_invalid(D) vmax = np.nanmax(np.abs(D)) if np.isfinite(np.nanmax(np.abs(D))) else 1.0 if vmax == 0: vmax = 1.0 fig_w = max(10, 0.6 * len(labels) + 2) fig_h = max(5, 0.6 * len(techniques) + 1) fig, ax = plt.subplots(figsize=(fig_w, fig_h)) cmap = plt.cm.RdBu_r cmap = cmap.copy() cmap.set_bad("#eeeeee") im = ax.imshow(D_masked, cmap=cmap, aspect="auto", vmin=-vmax, vmax=+vmax) ax.set_xticks(np.arange(len(labels))) ax.set_yticks(np.arange(len(techniques))) # If sorting by face metrics, append μ IoU / μ cov from overlap stats if face_overlap_stats and class_sort in ("face_iou", "face_cover"): def label_with_stat(c): info = face_overlap_stats.get(c, {}) if class_sort == "face_iou": avg = info.get("avg_iou", float("nan")) return f"{c}\n(μ IoU={avg:.2f})" if not np.isnan(avg) else c else: avg = info.get("avg_coverage", float("nan")) return f"{c}\n(μ cov={avg:.2f})" if not np.isnan(avg) else c xticklabels = [label_with_stat(c) for c in labels] else: xticklabels = labels ax.set_xticklabels(xticklabels, rotation=45, ha="right") ax.set_yticklabels(techniques) ax.set_xlabel(f"MSCOCO {x_label_name} (Δ overlap−nonoverlap; ≥{min_instances} GT total)") ax.set_ylabel("Technique") ax.set_title(title, pad=12) # Annotate Δ pp for i in range(D.shape[0]): for j in range(D.shape[1]): val = D[i, j] if not np.isnan(val): ax.text(j, i, f"{val:+.1f}pp", ha="center", va="center", fontsize=8) cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) cbar.set_label("Δ accuracy (percentage points)", rotation=90, labelpad=10) fig.tight_layout() os.makedirs(os.path.dirname(out_path), exist_ok=True) fig.savefig(out_path, dpi=200, bbox_inches="tight") plt.close(fig) def save_confusion_style_matrix_delta(overlap_results: dict, nonoverlap_results: dict, out_path: str, title: str = "Technique × Label (Δ accuracy, pp)", class_sort: str = "accuracy", min_instances: int = 10, face_overlap_stats: dict | None = None, x_label_name: str = "Class"): """ Confusion-style grid but shows Δ accuracy (pp); no Σ row/col (not well-defined for deltas). """ combined_for_order = _merge_results_across_subsets(overlap_results, nonoverlap_results) techniques = sorted(set(overlap_results.keys()) | set(nonoverlap_results.keys())) labels = _class_order(combined_for_order, class_sort, min_instances, face_overlap_stats) if not techniques or not labels: raise ValueError("No techniques or labels found to plot (check filters).") D = _delta_matrix(overlap_results, nonoverlap_results, techniques, labels) D_masked = np.ma.masked_invalid(D) vmax = np.nanmax(np.abs(D)) if np.isfinite(np.nanmax(np.abs(D))) else 1.0 if vmax == 0: vmax = 1.0 fig_w = max(10, 0.6 * len(labels) + 2) fig_h = max(5, 0.6 * len(techniques) + 1) fig, ax = plt.subplots(figsize=(fig_w, fig_h)) cmap = plt.cm.RdBu_r cmap = cmap.copy() cmap.set_bad("#eeeeee") im = ax.imshow(D_masked, cmap=cmap, vmin=-vmax, vmax=+vmax, aspect="auto") ax.set_xticks(np.arange(len(labels))) ax.set_yticks(np.arange(len(techniques))) if face_overlap_stats and class_sort in ("face_iou", "face_cover"): def label_with_stat(c): info = face_overlap_stats.get(c, {}) if class_sort == "face_iou": avg = info.get("avg_iou", float("nan")) return f"{c}\n(μ IoU={avg:.2f})" if not np.isnan(avg) else c else: avg = info.get("avg_coverage", float("nan")) return f"{c}\n(μ cov={avg:.2f})" if not np.isnan(avg) else c xticklabels = [label_with_stat(c) for c in labels] else: xticklabels = labels ax.set_xticklabels(xticklabels, rotation=45, ha="right") ax.set_yticklabels(techniques) ax.set_xlabel(f"MSCOCO {x_label_name} (Δ overlap−nonoverlap; ≥{min_instances} GT total)") ax.set_ylabel("Technique") ax.set_title(title, pad=12) # Annotate Δ for i in range(D.shape[0]): for j in range(D.shape[1]): val = D[i, j] if not np.isnan(val): ax.text(j, i, f"{val:+.1f}pp", ha="center", va="center", fontsize=8) cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) cbar.set_label("Δ accuracy (percentage points)", rotation=90, labelpad=10) fig.tight_layout() os.makedirs(os.path.dirname(out_path), exist_ok=True) fig.savefig(out_path, dpi=200, bbox_inches="tight") plt.close(fig) # ====================== IoU, coverage & matching ====================== def _bbox_iou(a, b) -> float: pa = box(*a) # (minx, miny, maxx, maxy) pb = box(*b) iou = 0.0 try: inter = pa.intersection(pb).area union = pa.union(pb).area iou = inter / union except Exception as e: print("Exception during bbox_iou", e) iou = 0.0 return iou def _coverage_with_faces(bbox, face_bboxes) -> float: """ Coverage = area( (union of face boxes) ∩ object_bbox ) / area(object_bbox). Returns a value in [0, 1]. If there are no faces, returns 0.0. """ if not face_bboxes: return 0.0 try: obj = box(*bbox) obj_area = obj.area if obj_area <= 0: return 0.0 faces = [box(*fb) for fb in face_bboxes] faces_union = unary_union(faces) if len(faces) > 1 else faces[0] inter_area = obj.intersection(faces_union).area cov = inter_area / obj_area # Clamp to [0,1] in case of tiny numeric noise return max(0.0, min(1.0, cov)) except Exception as e: print("Exception during coverage calc:", e) return 0.0 def _find_best_matching_object(obj, other_objects, min_iou): ref_label = obj["label"] best = None best_bbox_iou = -1.0 for other in other_objects: if other["label"] != ref_label: continue bbox_iou = _bbox_iou(obj["bbox"], other["bbox"]) if bbox_iou < min_iou: continue if bbox_iou > best_bbox_iou: best = [other, bbox_iou] best_bbox_iou = bbox_iou if not best: return None best[1] *= 100.0 # BBox-IoU % return best def _max_iou_with_faces(bbox, face_bboxes) -> float: if not face_bboxes: return 0.0 m = 0.0 for fb in face_bboxes: try: iou = _bbox_iou(bbox, fb) if iou > m: m = iou except Exception: continue return m # ====================== Data IO ====================== def get_objects_and_faces(path_to_folder): objects_by_file = {} faces_by_file = {} for fp in glob(os.path.join(path_to_folder, "*.json")): stem = os.path.splitext(os.path.basename(fp))[0] objects = [] faces = [] try: with open(fp, "r", encoding="utf-8") as f: data = json.load(f) except Exception as e: print(f"Failed to load {fp}: {e}") continue for o in data.get("objects", []): label = o.get("label") bbox = o.get("bbox") if label is None or bbox is None or not isinstance(bbox, (list, tuple)) or len(bbox) != 4: continue objects.append({"label": str(label), "bbox": list(bbox)}) for p in data.get("persons", []): fb = p.get("face_bbox") if fb is None or not isinstance(fb, (list, tuple)) or len(fb) != 4: continue faces.append(list(fb)) objects_by_file[stem] = objects faces_by_file[stem] = faces return objects_by_file, faces_by_file def get_objects(path_to_folder): out = {} for fp in glob(os.path.join(path_to_folder, "*.json")): try: with open(fp, "r", encoding="utf-8") as f: data = json.load(f) except Exception as e: print(f"Failed to load {fp}: {e}") continue objs = [] for o in data.get("objects", []): label = o.get("label") bbox = o.get("bbox") if label is None or bbox is None or not isinstance(bbox, (list, tuple)) or len(bbox) != 4: continue objs.append({"label": str(label), "bbox": list(bbox)}) key = os.path.splitext(os.path.basename(fp))[0] out[key] = objs return out def get_after_paths(path_to_folder): paths = [] for name in os.listdir(path_to_folder): if name.startswith(".") or name == "NO_OP": continue p = os.path.join(path_to_folder, name) if os.path.isdir(p): paths.append(p) return sorted(paths) # ====================== Metrics (per-class, with face filter) ====================== def _object_passes_face_filter(max_iou: float, has_faces: bool, face_filter: str) -> bool: """ Decide if an object is considered, based on face_filter mode: - "overlap": require has_faces and max_iou > 0 - "nonoverlap": require has_faces and max_iou == 0 - "any": include regardless (faces may or may not exist) """ if face_filter == "overlap": return has_faces and (max_iou > 0.0) if face_filter == "nonoverlap": return has_faces and (max_iou == 0.0) return True # "any" def _compute_metrics_per_technique_face_filtered(before_by_file, faces_by_file, after_by_file, iou_thresh=0.5, face_filter: str = "overlap"): """ Consider GT objects according to `face_filter` and compute per-class detection accuracy. Returns technique metrics with 'per_class' keyed by CLASS label. """ total_gt = 0 matched_gt = 0 per_class_total = defaultdict(int) per_class_matched = defaultdict(int) for fname, gt_objs in before_by_file.items(): det_objs = [dict(o) for o in after_by_file.get(fname, [])] # copy so we can mark _matched face_bboxes = faces_by_file.get(fname, []) or [] has_faces = len(face_bboxes) > 0 for gt in gt_objs: max_iou_face = _max_iou_with_faces(gt["bbox"], face_bboxes) if not _object_passes_face_filter(max_iou_face, has_faces, face_filter): continue total_gt += 1 label = gt.get("label", "") match = _find_best_matching_object(gt, det_objs, min_iou=iou_thresh) if match is not None: det, _bbox_iou_pct = match det["_matched"] = True matched_gt += 1 per_class_total[label] += 1 per_class_matched[label] += 1 else: per_class_total[label] += 1 overall_acc = (matched_gt / total_gt) if total_gt > 0 else 0.0 per_class = {} for cls in sorted(per_class_total.keys()): tot = per_class_total[cls] mat = per_class_matched[cls] per_class[cls] = { "gt_objects": tot, "matched": mat, "detection_accuracy": (mat / tot) if tot > 0 else 0.0 } return { "overall": { "gt_objects": total_gt, "matched": matched_gt, "detection_accuracy": overall_acc }, "per_class": per_class } def _compute_face_overlap_stats(before_by_file, faces_by_file, face_filter: str = "overlap"): """ Compute per-class average IoU (max IoU with any face) and average COVERAGE = area((union faces) ∩ object) / area(object). Objects are included according to `face_filter`. Returns: { cls: {"count": n, "sum_iou": s_iou, "avg_iou": s_iou/n, "sum_coverage": s_cov, "avg_coverage": s_cov/n} } """ sums_iou = defaultdict(float) sums_cov = defaultdict(float) counts = defaultdict(int) for fname, gt_objs in before_by_file.items(): face_bboxes = faces_by_file.get(fname, []) or [] has_faces = len(face_bboxes) > 0 for gt in gt_objs: max_iou = _max_iou_with_faces(gt["bbox"], face_bboxes) if not _object_passes_face_filter(max_iou, has_faces, face_filter): continue cover = _coverage_with_faces(gt["bbox"], face_bboxes) cls = gt.get("label", "") counts[cls] += 1 sums_iou[cls] += max_iou sums_cov[cls] += cover stats = {} for cls in counts.keys(): n = counts[cls] si = sums_iou[cls] sc = sums_cov[cls] stats[cls] = { "count": n, "sum_iou": si, "avg_iou": (si / n) if n > 0 else float("nan"), "sum_coverage": sc, "avg_coverage": (sc / n) if n > 0 else float("nan"), } return stats # ====================== Multi-dataset support ====================== def _compute_results_for_dataset(before_path: str, after_base_path: str, iou_thresh: float, face_filter: str): """ Compute results per technique for a single dataset (before/after pair), and compute per-class face IoU & coverage stats (dataset-level) under the same filter. """ before_objects_by_file, faces_by_file = get_objects_and_faces(before_path) technique_after_paths = get_after_paths(after_base_path) ds_results = {} for technique_after_path in technique_after_paths: technique_name = os.path.basename(os.path.normpath(technique_after_path)) after_objects_by_file = get_objects(technique_after_path) metrics = _compute_metrics_per_technique_face_filtered( before_by_file=before_objects_by_file, faces_by_file=faces_by_file, after_by_file=after_objects_by_file, iou_thresh=iou_thresh, face_filter=face_filter ) ds_results[technique_name] = metrics # Dataset-level face stats (IoU & coverage) face_stats = _compute_face_overlap_stats(before_objects_by_file, faces_by_file, face_filter) return ds_results, face_stats def _merge_results_across_datasets(results_list): """ Merge multiple results dicts (each: technique -> metrics) into a single global results dict. Sums counts and recomputes detection_accuracy. """ merged = {} for res in results_list: for tech, metrics in res.items(): tgt = merged.setdefault(tech, {"overall": {"gt_objects": 0, "matched": 0, "detection_accuracy": 0.0}, "per_class": {}}) # overall tgt["overall"]["gt_objects"] += int(metrics["overall"].get("gt_objects", 0)) tgt["overall"]["matched"] += int(metrics["overall"].get("matched", 0)) # per label (currently class) for lbl, stats in metrics.get("per_class", {}).items(): pc = tgt["per_class"].setdefault(lbl, {"gt_objects": 0, "matched": 0, "detection_accuracy": 0.0}) pc["gt_objects"] += int(stats.get("gt_objects", 0)) pc["matched"] += int(stats.get("matched", 0)) # recompute accuracies for tech, metrics in merged.items(): tot = metrics["overall"]["gt_objects"] mat = metrics["overall"]["matched"] metrics["overall"]["detection_accuracy"] = (mat / tot) if tot > 0 else 0.0 for lbl, stats in metrics["per_class"].items(): ct = stats["gt_objects"] cm = stats["matched"] stats["detection_accuracy"] = (cm / ct) if ct > 0 else 0.0 return merged def _merge_face_stats_across_datasets(face_stats_list): """ Merge per-dataset face-overlap stats: Input: list of {label: {"count": n, "sum_iou": si, "avg_iou": ..., "sum_coverage": sc, "avg_coverage": ...}} Output: {label: {"count": N, "sum_iou": SI, "avg_iou": SI/N, "sum_coverage": SC, "avg_coverage": SC/N}} """ merged_counts = defaultdict(int) merged_sum_iou = defaultdict(float) merged_sum_cov = defaultdict(float) for stats in face_stats_list: for lbl, d in stats.items(): merged_counts[lbl] += int(d.get("count", 0)) merged_sum_iou[lbl] += float(d.get("sum_iou", 0.0)) merged_sum_cov[lbl] += float(d.get("sum_coverage", 0.0)) merged = {} for lbl in merged_counts.keys(): n = merged_counts[lbl] si = merged_sum_iou[lbl] sc = merged_sum_cov[lbl] merged[lbl] = { "count": n, "sum_iou": si, "avg_iou": (si / n) if n > 0 else float("nan"), "sum_coverage": sc, "avg_coverage": (sc / n) if n > 0 else float("nan"), } return merged # ====================== CLI / Main ====================== def main(): parser = argparse.ArgumentParser( description="Compute detection accuracy per technique (IoU≥0.5, same class), " "with face filtering (overlap/nonoverlap/any) OR plot Δ (overlap−nonoverlap), " "optional two-dataset merge, optional grouping to super-categories, " "min-instance filtering, and plots." ) # Dataset A (required) parser.add_argument("--before", required=True, help="Path to ground-truth folder (dataset A).") parser.add_argument("--after_base", required=True, help="Path to folder containing technique subfolders (dataset A).") # Dataset B (optional) parser.add_argument("--before2", default=None, help="Path to second ground-truth folder (dataset B).") parser.add_argument("--after_base2", default=None, help="Path to folder with technique subfolders (dataset B).") parser.add_argument("--out", required=True, help="Path to write results JSON. In delta mode, writes {'overlap':..., 'nonoverlap':...}.") parser.add_argument("--out_per_dataset", default=None, help="Optional path to write per-dataset results JSON (contains keys for each dataset).") parser.add_argument("--iou", type=float, default=0.5, help="IoU threshold for matching objects (default 0.5).") parser.add_argument("--min_instances", type=int, default=10, help="Only include labels with at least this many GT instances (default 10) in plots.") parser.add_argument("--class_sort", choices=["accuracy", "prevalence", "alpha", "face_iou", "face_cover"], default="accuracy", help="Order label columns by accuracy, prevalence (GT count), alphabetically, " "average IoU to faces, or average coverage by faces.") parser.add_argument("--face_mode", choices=["overlap", "nonoverlap", "any", "delta"], default="overlap", help="Which GT objects to evaluate/plot: overlap, nonoverlap, any, or Δ (overlap−nonoverlap).") parser.add_argument("--group_by", choices=["class", "super"], default="class", help="Plot label space: 'class' (default) or MSCOCO 'super' categories.") parser.add_argument("--heatmap_out", default=None, help="Directory to save plots; files are created with suffixes based on group & sort.") parser.add_argument("--heatmap_title", default="Technique × Label", help="Title to show on the plots.") args = parser.parse_args() # Validate dataset B pairing if (args.before2 and not args.after_base2) or (args.after_base2 and not args.before2): raise ValueError("If you provide --before2, you must also provide --after_base2 (and vice versa).") # ---------- NON-DELTA MODES ---------- if args.face_mode in ("overlap", "nonoverlap", "any"): face_filter = args.face_mode # Compute per-dataset results + face stats under the chosen filter print("Computing dataset A results…") results_ds1, face_stats_ds1 = _compute_results_for_dataset(args.before, args.after_base, args.iou, face_filter) results_list = [results_ds1] face_stats_list = [face_stats_ds1] per_dataset_out = {"dataset1": results_ds1, "face_stats1": face_stats_ds1} if args.before2 and args.after_base2: print("Computing dataset B results…") results_ds2, face_stats_ds2 = _compute_results_for_dataset(args.before2, args.after_base2, args.iou, face_filter) results_list.append(results_ds2) face_stats_list.append(face_stats_ds2) per_dataset_out["dataset2"] = results_ds2 per_dataset_out["face_stats2"] = face_stats_ds2 # Merge into global (per-class internally) print("Merging datasets into GLOBAL results…") results_global = _merge_results_across_datasets(results_list) face_stats_global = _merge_face_stats_across_datasets(face_stats_list) # Save GLOBAL results JSON (per-class) os.makedirs(os.path.dirname(args.out), exist_ok=True) with open(args.out, "w", encoding="utf-8") as f: json.dump(results_global, f, indent=2) print(f"[OK] Wrote GLOBAL metrics to: {args.out}") # Optionally save per-dataset results if args.out_per_dataset: os.makedirs(os.path.dirname(args.out_per_dataset), exist_ok=True) with open(args.out_per_dataset, "w", encoding="utf-8") as f: json.dump(per_dataset_out, f, indent=2) print(f"[OK] Wrote per-dataset metrics to: {args.out_per_dataset}") # Prepare label space for plots (class or super) results_for_plot = _regroup_results_to(results_global, args.group_by) face_stats_for_plot = _regroup_face_stats_to(face_stats_global, args.group_by) x_label_name = "Super-Category" if args.group_by == "super" else "Class" # Optional plots if args.heatmap_out: try: os.makedirs(args.heatmap_out, exist_ok=True) save_confusion_style_matrix( results_for_plot, os.path.join(args.heatmap_out, f"confusion_{args.group_by}_{args.class_sort}.pdf"), title=f"{args.heatmap_title} (matched/GT; %)", class_sort=args.class_sort, min_instances=args.min_instances, face_overlap_stats=face_stats_for_plot, face_mode=args.face_mode, x_label_name=x_label_name, ) save_heatmap( results_for_plot, os.path.join(args.heatmap_out, f"heatmap_{args.group_by}_{args.class_sort}.pdf"), title=f"{args.heatmap_title} (accuracy %)", class_sort=args.class_sort, min_instances=args.min_instances, face_overlap_stats=face_stats_for_plot, face_mode=args.face_mode, x_label_name=x_label_name, ) print(f"[OK] Wrote figures to: {args.heatmap_out}") except Exception as e: print(f"[WARN] Could not create figures: {e}") return # ---------- DELTA MODE ---------- # Compute overlap subset print("Computing OVERLAP results…") o_ds1, o_face1 = _compute_results_for_dataset(args.before, args.after_base, args.iou, "overlap") o_list = [o_ds1]; o_face_list = [o_face1] per_dataset_out = {"overlap_dataset1": o_ds1, "overlap_face_stats1": o_face1} if args.before2 and args.after_base2: print("Computing OVERLAP results (dataset B)…") o_ds2, o_face2 = _compute_results_for_dataset(args.before2, args.after_base2, args.iou, "overlap") o_list.append(o_ds2); o_face_list.append(o_face2) per_dataset_out["overlap_dataset2"] = o_ds2 per_dataset_out["overlap_face_stats2"] = o_face2 results_global_overlap = _merge_results_across_datasets(o_list) face_stats_overlap = _merge_face_stats_across_datasets(o_face_list) # Compute nonoverlap subset print("Computing NONOVERLAP results…") n_ds1, n_face1 = _compute_results_for_dataset(args.before, args.after_base, args.iou, "nonoverlap") n_list = [n_ds1]; n_face_list = [n_face1] per_dataset_out["nonoverlap_dataset1"] = n_ds1 per_dataset_out["nonoverlap_face_stats1"] = n_face1 if args.before2 and args.after_base2: print("Computing NONOVERLAP results (dataset B)…") n_ds2, n_face2 = _compute_results_for_dataset(args.before2, args.after_base2, args.iou, "nonoverlap") n_list.append(n_ds2); n_face_list.append(n_face2) per_dataset_out["nonoverlap_dataset2"] = n_ds2 per_dataset_out["nonoverlap_face_stats2"] = n_face2 results_global_nonoverlap = _merge_results_across_datasets(n_list) face_stats_nonoverlap = _merge_face_stats_across_datasets(n_face_list) # mostly zeros for coverage/IoU # Save JSON with both subsets os.makedirs(os.path.dirname(args.out), exist_ok=True) with open(args.out, "w", encoding="utf-8") as f: json.dump({"overlap": results_global_overlap, "nonoverlap": results_global_nonoverlap}, f, indent=2) print(f"[OK] Wrote OVERLAP & NONOVERLAP metrics to: {args.out}") if args.out_per_dataset: os.makedirs(os.path.dirname(args.out_per_dataset), exist_ok=True) with open(args.out_per_dataset, "w", encoding="utf-8") as f: json.dump(per_dataset_out, f, indent=2) print(f"[OK] Wrote per-dataset metrics to: {args.out_per_dataset}") # Regroup for plots ro_plot = _regroup_results_to(results_global_overlap, args.group_by) rn_plot = _regroup_results_to(results_global_nonoverlap, args.group_by) # Use OVERLAP stats for face_iou/face_cover sorting annotations face_stats_for_plot = _regroup_face_stats_to(face_stats_overlap, args.group_by) x_label_name = "Super-Category" if args.group_by == "super" else "Class" # Delta plots if args.heatmap_out: try: os.makedirs(args.heatmap_out, exist_ok=True) save_confusion_style_matrix_delta( ro_plot, rn_plot, os.path.join(args.heatmap_out, f"confusion_delta_{args.group_by}_{args.class_sort}.pdf"), title=f"{args.heatmap_title} (Δ accuracy, pp)", class_sort=args.class_sort, min_instances=args.min_instances, face_overlap_stats=face_stats_for_plot, x_label_name=x_label_name, ) save_heatmap_delta( ro_plot, rn_plot, os.path.join(args.heatmap_out, f"heatmap_delta_{args.group_by}_{args.class_sort}.pdf"), title=f"{args.heatmap_title} (Δ overlap − nonoverlap, pp)", class_sort=args.class_sort, min_instances=args.min_instances, face_overlap_stats=face_stats_for_plot, x_label_name=x_label_name, ) print(f"[OK] Wrote Δ figures to: {args.heatmap_out}") except Exception as e: print(f"[WARN] Could not create Δ figures: {e}") if __name__ == "__main__": main() #python class_object_analysis.py --before C:/Users/bijan/Desktop/obfuscation_platform/project/datasets/filtered_yolom_yunet/celeba --after_base C:/Users/bijan/Desktop/obfuscation_platform/project/datasets/obfuscated_yolom_yunet/celeba --before2 C:/Users/bijan/Desktop/obfuscation_platform/project/datasets/filtered_yolom_yunet/wider --after_base2 C:/Users/bijan/Desktop/obfuscation_platform/project/datasets/obfuscated_yolom_yunet/wider --out results/global.json --out_per_dataset C:\Users\bijan\Desktop\obfuscation_platform\project\evaluation_results\class_analysis_0.5.json --heatmap_out C:/Users/bijan/Desktop/obfuscation_platform/project/visual_results/in_paper/object_class_analysis --class_sort prevalence --iou 0.5