From d848ebde28de629504c4f9e810f06aab60ef079f Mon Sep 17 00:00:00 2001 From: Bijan Date: Wed, 20 Aug 2025 15:33:27 +0200 Subject: [PATCH] Added script to analyze class of obejcts and their accuracy drop --- project/class_object_analysis.py | 766 +++++++++++++++++++++++++++++++ 1 file changed, 766 insertions(+) create mode 100644 project/class_object_analysis.py diff --git a/project/class_object_analysis.py b/project/class_object_analysis.py new file mode 100644 index 0000000..a3931d3 --- /dev/null +++ b/project/class_object_analysis.py @@ -0,0 +1,766 @@ +import os +import json +import argparse +from glob import glob +from collections import defaultdict +from shapely.geometry import box +import numpy as np +import matplotlib +matplotlib.use("Agg") # safe for headless / servers +import matplotlib.pyplot as plt + + +# ====================== Aggregation / Sorting ====================== + +def _aggregate_class_stats(results: dict): + """ + Aggregate per-class GT totals and matches across all techniques. + Returns (totals, matches) dicts keyed by class string. + """ + totals = defaultdict(int) + matches = defaultdict(int) + for tech_metrics in results.values(): + for cls, stats in tech_metrics.get("per_class", {}).items(): + totals[cls] += int(stats.get("gt_objects", 0)) + matches[cls] += 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 class 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 + Only classes with totals >= min_instances are included. + """ + totals, matches = _aggregate_class_stats(results) + classes = [c for c in totals.keys() if totals[c] >= min_instances] + + if mode == "prevalence": + classes.sort(key=lambda c: (-totals[c], c)) + return classes + if mode == "alpha": + classes.sort() + return classes + if mode == "face_iou": + def avg_iou(c): + if not face_overlap_stats or c not in face_overlap_stats: + return float("nan") + return face_overlap_stats[c].get("avg_iou", float("nan")) + classes.sort( + key=lambda c: (np.isnan(avg_iou(c)), -(avg_iou(c) if not np.isnan(avg_iou(c)) else -1.0), c) + ) + return classes + + # default: accuracy + acc = { + c: (matches[c] / totals[c]) if totals[c] > 0 else float("nan") + for c in classes + } + classes.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 classes + + +# ====================== Visualization ====================== + +def _face_filter_label(face_filter: str) -> str: + return { + "overlap": "filter=overlap", + "nonoverlap": "filter=nonoverlap", + "any": "filter=any", + }.get(face_filter, f"filter={face_filter}") + + +def save_confusion_style_matrix(results: dict, out_path: str, + title: str = "Technique × Class (matched/GT; %)", + class_sort: str = "accuracy", + min_instances: int = 10, + face_overlap_stats: dict | None = None, + face_filter: str = "overlap"): + """ + Builds a Technique x Class matrix from `results['per_class']`. + Only classes with >= min_instances GT are included. + Cell text shows "matched/GT" and "acc%". + Includes Σ row/column with totals; missing cells are light gray. + """ + techniques = sorted(results.keys()) + classes = _class_order(results, class_sort, min_instances, face_overlap_stats) + if not techniques or not classes: + raise ValueError("No techniques or classes found to plot (check filters).") + + n_t, n_c = len(techniques), len(classes) + 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, cls in enumerate(classes): + d = per.get(cls) + 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 + + classes_ext = classes + ["Σ classes"] + techniques_ext = techniques + ["Σ techniques"] + + # Plot + fig_w = max(10, 0.6 * len(classes_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(classes_ext))) + ax.set_yticks(np.arange(len(techniques_ext))) + # Optionally append avg face IoU to column labels when sorting by face_iou + if class_sort == "face_iou" and face_overlap_stats: + def label_with_iou(c): + info = face_overlap_stats.get(c, {}) + avg = info.get("avg_iou", float("nan")) + return f"{c}\n(μ IoU={avg:.2f})" if not np.isnan(avg) else c + core_labels = [label_with_iou(c) for c in classes] + else: + core_labels = classes + + ax.set_xticklabels(core_labels + ["Σ classes"], rotation=45, ha="right") + ax.set_yticklabels(techniques_ext) + ax.set_xlabel(f"MSCOCO Class ({_face_filter_label(face_filter)}, ≥{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 class", + class_sort: str = "accuracy", + min_instances: int = 10, + face_overlap_stats: dict | None = None, + face_filter: str = "overlap"): + """ + Technique x Class heatmap from `results['per_class']`. Values are percentages. + Only classes with >= min_instances GT are included. + """ + techniques = sorted(results.keys()) + classes = _class_order(results, class_sort, min_instances, face_overlap_stats) + if not techniques or not classes: + raise ValueError("No techniques or classes found to plot (check filters).") + + M = np.full((len(techniques), len(classes)), np.nan, dtype=float) + for i, tech in enumerate(techniques): + per = results[tech].get("per_class", {}) + for j, cls in enumerate(classes): + acc = per.get(cls, {}).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(classes) + 2) + fig_h = max(5, 0.6 * len(techniques) + 1) + 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(classes))) + if class_sort == "face_iou" and face_overlap_stats: + def label_with_iou(c): + info = face_overlap_stats.get(c, {}) + avg = info.get("avg_iou", float("nan")) + return f"{c}\n(μ IoU={avg:.2f})" if not np.isnan(avg) else c + xticklabels = [label_with_iou(c) for c in classes] + else: + xticklabels = classes + ax.set_xticklabels(xticklabels, rotation=45, ha="right") + + ax.set_yticks(np.arange(len(techniques))) + ax.set_yticklabels(techniques) + ax.set_xlabel(f"MSCOCO Class ({_face_filter_label(face_filter)}, ≥{min_instances} GT)") + ax.set_ylabel("Technique") + ax.set_title(title, pad=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=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) + + +# ====================== IoU & 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 if union > 0 else 0.0 + except Exception as e: + print("Exception during bbox_iou", e) + iou = 0.0 + return iou + + +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.get("_matched"): + continue + 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: + """Return max IoU between `bbox` and any face bbox in list. 0.0 if none or empty.""" + 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): + """ + Reads all .json files. + Returns two dicts: + objects_by_file: { "": [ {"label": str, "bbox": [x1,y1,x2,y2]}, ... ], ... } + faces_by_file: { "": [ [x1,y1,x2,y2], ... ], ... } # from persons[*].face_bbox + """ + 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): + """Only returns objects (used for technique folders).""" + 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): + """List of technique subfolders (excludes 'NO_OP' and hidden).""" + 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) + # "any" + return True + + +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: + { + "overall": {"gt_objects": int, "matched": int, "detection_accuracy": float}, + "per_class": {class_label: {"gt_objects": int, "matched": int, "detection_accuracy": float}, ...} + } + """ + 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 between each GT object and faces in the same file. + For each GT object, use MAX IoU with ANY face. Objects are included according to `face_filter`. + Returns: { cls: {"count": n, "sum_iou": s, "avg_iou": s/n} } + """ + sums = 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 + cls = gt.get("label", "") + counts[cls] += 1 + sums[cls] += max_iou + + stats = {} + for cls in counts.keys(): + n = counts[cls] + s = sums[cls] + stats[cls] = {"count": n, "sum_iou": s, "avg_iou": (s / 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-overlap IoU 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-overlap stats (independent of technique) + 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 class + for cls, stats in metrics.get("per_class", {}).items(): + pc = tgt["per_class"].setdefault(cls, {"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 cls, 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 {cls: {"count": n, "sum_iou": s, "avg_iou": ...}} + Output: {cls: {"count": N, "sum_iou": S, "avg_iou": S/N}} + """ + merged_counts = defaultdict(int) + merged_sums = defaultdict(float) + for stats in face_stats_list: + for cls, d in stats.items(): + merged_counts[cls] += int(d.get("count", 0)) + merged_sums[cls] += float(d.get("sum_iou", 0.0)) + merged = {} + for cls in merged_counts.keys(): + n = merged_counts[cls] + s = merged_sums[cls] + merged[cls] = {"count": n, "sum_iou": s, "avg_iou": (s / n) if n > 0 else float("nan")} + return merged + + +# ====================== Data IO helpers (unchanged) ====================== + +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) + + +# ====================== CLI / Main ====================== + +def main(): + parser = argparse.ArgumentParser( + description="Compute detection accuracy per technique (IoU≥0.5, same class), " + "with face-overlap filtering (overlap/nonoverlap/any), optional two-dataset merge, " + "min-instance filtering, and Technique×Class 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 GLOBAL (merged) results JSON.") + parser.add_argument("--out_per_dataset", default=None, + help="Optional path to write per-dataset results JSON (contains keys 'dataset1'/'dataset2').") + + 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 classes with at least this many GT instances (default 10) in plots.") + parser.add_argument("--class_sort", choices=["accuracy", "prevalence", "alpha", "face_iou"], default="accuracy", + help="Order class columns by accuracy, prevalence (GT count), alphabetically, or by avg IoU to face.") + parser.add_argument("--face_filter", choices=["overlap", "nonoverlap", "any"], default="overlap", + help="Which GT objects to consider: overlap with a face, do not overlap, or any.") + + parser.add_argument("--heatmap_out", default=None, + help="Directory to save plots; files 'confusion_.pdf' and 'heatmap_.pdf' are created.") + parser.add_argument("--heatmap_title", default="Technique × Class", + 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).") + + # Compute per-dataset results + face IoU stats under the chosen face_filter + print("Computing dataset A results…") + results_ds1, face_stats_ds1 = _compute_results_for_dataset(args.before, args.after_base, args.iou, args.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, args.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 + 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 + 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 (for transparency/debugging) + 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}") + + # Optional plots (use GLOBAL merged results) + if args.heatmap_out: + try: + os.makedirs(args.heatmap_out, exist_ok=True) + save_confusion_style_matrix( + results_global, + os.path.join(args.heatmap_out, f"confusion_{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_global, + face_filter=args.face_filter, + ) + save_heatmap( + results_global, + os.path.join(args.heatmap_out, f"heatmap_{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_global, + face_filter=args.face_filter, + ) + 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() + + + +#TODO: Prüfen ist das matching noch korrekt? Sehr wichtig + +#TODO: 1. Min. Anzahl filtern MUSS KLAPPEN + + + + +#TODO: 2. TOP-N Überlappungsgrad sortierung + +#Zwei grafiken + +#TODO: Schlechteste Accuracy +#TODO: Meiste IoU mit Gesicht + + +#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 \ No newline at end of file