#!/usr/bin/env python3 import argparse import json import math import os import re from collections import defaultdict from pathlib import Path import itertools import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter FOLDER_PATTERN = re.compile(r"^evaluation_results_(\d+)$") # Map LaTeX-like metric keys used in JSON to friendly names METRIC_KEY_MAP = { r"\mathrm{Acc}_\mathrm{det}": "Acc_det", r"\mathrm{mIoU}_\mathrm{seg}": "mIoU_seg", } # Labels to show on the Y axis (mathtext/LaTeX style) METRIC_LABELS_MATH = { "Acc_det": r"$\mathrm{Acc}_{\mathrm{det}}$", "mIoU_seg": r"$\mathrm{mIoU}_{\mathrm{seg}}$", } ALL_SCOPES = ["person", "face", "object"] ALL_METRICS = ["Acc_det", "mIoU_seg"] # Distinct markers to differentiate techniques (in addition to color) MARKER_STYLES = ['o', 'x', 's', '^', 'D', 'P', '*', 'v', 'X', '+', '<', '>', 'h', 'H', '1', '2', '3', '4', 'p'] def parse_args(): p = argparse.ArgumentParser(description="Visualize metrics across IoU thresholds.") p.add_argument("--root", type=str, required=True, help="Root directory with evaluation_results_{thr} folders.") p.add_argument("--out", type=str, default="plots", help="Output directory for figures (PDF).") p.add_argument("--metric", type=str, choices=["Acc_det", "mIoU_seg", "both"], default="both", help="Metric to plot. 'both' makes two stacked subplots per figure.") p.add_argument("--scopes", type=str, nargs="*", default=None, help="Subset of scopes to include (default: person face object).") p.add_argument("--dpi", type=int, default=140, help="Figure DPI for rasterized parts in the PDF.") p.add_argument("--style", type=str, default=None, help="Optional matplotlib style (e.g., 'ggplot').") return p.parse_args() def sanitize_filename(s: str) -> str: # Allow letters, digits, dot, underscore, plus, and hyphen; replace everything else with "_" # Put "-" at the END of the class so it won't be treated as a range marker. s = re.sub(r'[^A-Za-z0-9._+\-]+', '_', s) # Optional cleanup: collapse repeats and trim s = re.sub(r'_+', '_', s).strip('._ ') return s def discover_threshold_folders(root: Path): thresholds = [] folders = [] for name in os.listdir(root): m = FOLDER_PATTERN.match(name) if m: thr = int(m.group(1)) thresholds.append(thr) folders.append((thr, root / name)) thresholds = sorted(set(thresholds)) folders.sort(key=lambda x: x[0]) return thresholds, folders def rsplit_dataset_technique(filename: str): # Given 'result_{dataset}_{technique}.json' -> (dataset, technique) if not (filename.startswith("results_") and filename.endswith(".json")): return None, None stem = filename[len("results_"):-len(".json")] if "_" not in stem: return None, None dataset, technique = stem.rsplit("_", 1) return dataset, technique def load_data(root: Path, scopes_filter=None): """ data[dataset][scope][technique][metric][threshold] = value """ thresholds, folders = discover_threshold_folders(root) data = defaultdict( # dataset lambda: defaultdict( # scope lambda: defaultdict( # technique lambda: defaultdict(dict) # metric -> {thr: value} ) ) ) for thr, folder in folders: for fname in os.listdir(folder): dataset, technique = rsplit_dataset_technique(fname) if not dataset or not technique: continue fpath = folder / fname try: with open(fpath, "r", encoding="utf-8") as f: obj = json.load(f) except Exception as e: print(f"[WARN] Skipping {fpath}: {e}") continue for scope in (scopes_filter or ALL_SCOPES): if scope not in obj or not isinstance(obj[scope], dict): continue for raw_key, val in obj[scope].items(): key = METRIC_KEY_MAP.get(raw_key, raw_key) if key not in ALL_METRICS: continue try: val_num = float(val) except Exception: continue data[dataset][scope][technique][key][thr] = val_num return thresholds, data def plot_dataset_scope(thresholds, dataset, scope, techniques_dict, out_dir: Path, dpi=140, style=None, metric_mode="both"): """ techniques_dict: techniques_dict[technique][metric][thr] = value """ metrics = ALL_METRICS if metric_mode == "both" else [metric_mode] # Keep only metrics that actually have any data metrics_present = [] for m in metrics: present = any( any(not math.isnan(v) for v in [techniques_dict[t][m].get(thr, float("nan")) for thr in thresholds]) for t in techniques_dict.keys() if m in techniques_dict[t] ) if present: metrics_present.append(m) if not metrics_present: return False if style: try: plt.style.use(style) except Exception as e: print(f"[WARN] Could not set style '{style}': {e}") # Create figure/axes if len(metrics_present) == 1: fig, ax = plt.subplots(figsize=(5, 3)) axes = [ax] # list for uniform handling else: fig, axes = plt.subplots( nrows=len(metrics_present), ncols=1, figsize=(8, 5 * len(metrics_present)), sharex=True ) axes = list(axes) # Assign a distinct marker per technique (consistent across subplots) marker_cycle = itertools.cycle(MARKER_STYLES) markers_by_tech = {tech: next(marker_cycle) for tech in sorted(techniques_dict.keys())} for ax, metric in zip(axes, metrics_present): any_line = False for technique, metric_dicts in sorted(techniques_dict.items()): metric_values_by_thr = metric_dicts.get(metric, {}) ys = [metric_values_by_thr.get(thr, float("nan")) for thr in thresholds] if any(not math.isnan(v) for v in ys): ax.plot( thresholds, ys, marker=markers_by_tech[technique], linestyle="-", label=technique, ) any_line = True # Axis formatting #ax.set_title(f"{dataset} – {scope} – {metric}") ax.set_ylim(0, 105) # 0–100% # Y ticks as percentages ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y:.0f}%")) # X ticks as percentages (thresholds like 25 -> "25%") ax.set_xticks(thresholds) ax.set_xticklabels([f"{thr}%" for thr in thresholds]) # Labels: x in %, y is the LaTeX metric name ax.set_xlabel("IoU threshold (%)") ax.set_ylabel(METRIC_LABELS_MATH.get(metric, metric)) ax.grid(True, linestyle="--", alpha=0.4) if any_line: ax.legend(loc="lower left") #fig.suptitle(f"{dataset} • {scope}", y=0.995, fontsize=12) fig.tight_layout() outfile = out_dir / sanitize_filename(f"{dataset}__{scope}__{metric_mode}.pdf") fig.savefig(outfile, dpi=dpi, bbox_inches="tight") plt.close(fig) print(f"[OK] Saved {outfile}") return True def main(): args = parse_args() root = Path(args.root).expanduser().resolve() out_dir = Path(args.out).expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) scopes_filter = args.scopes if args.scopes else ALL_SCOPES thresholds, data = load_data(root, scopes_filter=scopes_filter) if not thresholds: print("[ERROR] No evaluation_results_{thr} folders found.") return made_any = False for dataset, scopes in sorted(data.items()): for scope, techniques in sorted(scopes.items()): if not techniques: continue ok = plot_dataset_scope( thresholds=thresholds, dataset=dataset, scope=scope, techniques_dict=techniques, out_dir=out_dir, dpi=args.dpi, style=args.style, metric_mode=args.metric, ) made_any = made_any or ok if not made_any: print("[WARN] No plots generated. Check your JSON naming/contents.") if __name__ == "__main__": main()