219 lines
7.3 KiB
Python
219 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Grouped bar chart for a single metric at one IoU threshold.
|
|
[... docstring unchanged ...]
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
from pathlib import Path
|
|
from collections import defaultdict
|
|
|
|
import matplotlib.pyplot as plt
|
|
from matplotlib.container import BarContainer
|
|
|
|
from matplotlib.ticker import FuncFormatter
|
|
import math
|
|
|
|
HATCHES = ['x', 'o', 'O', '-', '+', 'O', '.', '*']
|
|
|
|
|
|
# --- NEW: enforce preferred technique order
|
|
PREFERRED_TECHNIQUE_ORDER = ["Black", "Random", "Blur", "Pixel", "Style", "Swap", "Synthetic"]
|
|
|
|
def order_techniques(techniques):
|
|
order_map = {name.lower(): i for i, name in enumerate(PREFERRED_TECHNIQUE_ORDER)}
|
|
# Known items keep specified order; unknowns come after, alphabetically
|
|
return sorted(techniques, key=lambda t: (order_map.get(t.lower(), len(PREFERRED_TECHNIQUE_ORDER)), t.lower()))
|
|
|
|
|
|
def parse_args():
|
|
p = argparse.ArgumentParser(description="Grouped bar chart for one metric at one IoU threshold.")
|
|
p.add_argument("--root", type=str, required=True, help="Root folder containing evaluation_results_{thr}.")
|
|
p.add_argument("--threshold", type=str, required=True, help="IoU threshold to visualize (e.g., 50).")
|
|
p.add_argument("--metric-latex", type=str, default=r"\mathrm{Acc}_\mathrm{deID}",
|
|
help="LaTeX key as it appears in JSON (default: \\mathrm{Acc}_\\mathrm{deID}).")
|
|
p.add_argument("--scope", type=str, default="face", help="Scope to use (default: face).")
|
|
p.add_argument("--out", type=str, default="plots", help="Output directory for the PDF.")
|
|
p.add_argument("--dpi", type=int, default=140, help="DPI for rasterized elements in the PDF.")
|
|
return p.parse_args()
|
|
|
|
def sanitize_filename(s: str) -> str:
|
|
s = re.sub(r'[^A-Za-z0-9._+\-]+', '_', s)
|
|
s = re.sub(r'_+', '_', s).strip('._ ')
|
|
return s
|
|
|
|
def rsplit_dataset_technique(filename: str):
|
|
if not (filename.startswith("results_") and filename.endswith(".json")):
|
|
return None, None
|
|
stem = filename[len("results_"):-len(".json")]
|
|
if "_" not in stem or "NO_OP" in filename:
|
|
return None, None
|
|
dataset, technique = stem.rsplit("_", 1)
|
|
return dataset, technique
|
|
|
|
def load_values_for_threshold(root: Path, threshold: int, scope: str, metric_latex: str):
|
|
folder = root / f"evaluation_results_{threshold}"
|
|
if not folder.is_dir():
|
|
raise FileNotFoundError(f"Folder not found: {folder}")
|
|
|
|
scope_keys = {scope, scope.lower(), scope.capitalize()}
|
|
techniques_set, datasets_set = set(), set()
|
|
values = defaultdict(dict)
|
|
|
|
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
|
|
|
|
scope_block = None
|
|
for k in obj.keys():
|
|
if k in scope_keys:
|
|
scope_block = obj[k]
|
|
break
|
|
if not isinstance(scope_block, dict):
|
|
continue
|
|
|
|
if metric_latex in scope_block:
|
|
try:
|
|
v = float(scope_block[metric_latex])
|
|
except Exception:
|
|
v = math.nan
|
|
else:
|
|
v = math.nan
|
|
|
|
datasets_set.add(dataset)
|
|
techniques_set.add(technique)
|
|
values[technique][dataset] = v
|
|
|
|
datasets = sorted(datasets_set)
|
|
techniques = order_techniques(sorted(techniques_set))
|
|
|
|
for t in techniques:
|
|
for d in datasets:
|
|
values[t].setdefault(d, math.nan)
|
|
|
|
return datasets, techniques, values
|
|
|
|
# --- NEW: pretty names for datasets for legend display
|
|
def pretty_dataset_label(name: str) -> str:
|
|
low = name.lower()
|
|
if low == "celeba":
|
|
return "CelebA'"
|
|
if low == "wider":
|
|
return "WIDER'"
|
|
return name
|
|
|
|
def grouped_bar_chart(datasets, techniques, values, scope, threshold, metric_latex, out_dir: Path, dpi=140):
|
|
if not techniques or not datasets:
|
|
print("[WARN] Nothing to plot (no techniques or datasets discovered).")
|
|
return False
|
|
|
|
fig, ax = plt.subplots(figsize=(5.5, 2.5))
|
|
|
|
n_groups = len(techniques)
|
|
n_bars = len(datasets)
|
|
group_x = list(range(n_groups))
|
|
total_width = 0.8
|
|
bar_w = total_width / max(1, n_bars)
|
|
offsets = [(i - (n_bars - 1) / 2) * bar_w for i in range(n_bars)]
|
|
|
|
# Draw bars dataset-by-dataset so legend matches dataset order
|
|
for j, dataset in enumerate(datasets):
|
|
heights = [values[t][dataset] for t in techniques]
|
|
x_pos = [x + offsets[j] for x in group_x]
|
|
bars = ax.bar(x_pos, heights, width=bar_w, label=pretty_dataset_label(dataset))
|
|
|
|
hatch = HATCHES[j % len(HATCHES)]
|
|
rects = bars.patches if hasattr(bars, "patches") else list(bars)
|
|
for r in rects:
|
|
r.set_hatch(hatch)
|
|
r.set_edgecolor("black")
|
|
r.set_linewidth(0.6)
|
|
|
|
labels = [f"{h:.0f}" if not math.isnan(h) else "" for h in heights]
|
|
if hasattr(ax, "bar_label") and isinstance(bars, BarContainer):
|
|
ax.bar_label(bars, labels=labels, padding=2, fontsize=8)
|
|
else:
|
|
for rect, lab in zip(rects, labels):
|
|
if not lab:
|
|
continue
|
|
ax.text(
|
|
rect.get_x() + rect.get_width() / 2.0,
|
|
rect.get_height(),
|
|
lab,
|
|
ha="center",
|
|
va="bottom",
|
|
fontsize=8,
|
|
)
|
|
|
|
ax.set_xticks(group_x)
|
|
ax.set_xticklabels(techniques)
|
|
|
|
ax.set_ylim(0, 109)
|
|
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y:.0f}%"))
|
|
|
|
ax.set_ylabel(f"${metric_latex}$", fontsize=10)
|
|
ax.grid(axis="y", linestyle="--", alpha=0.4)
|
|
|
|
# --- Legend INSIDE, centered at the top ---
|
|
handles, labels = ax.get_legend_handles_labels()
|
|
#ncols = min(len(datasets), 4) if len(datasets) > 1 else 1
|
|
leg = ax.legend(
|
|
handles,
|
|
labels,
|
|
loc="lower left",
|
|
#bbox_to_anchor=(0.5, 0.98), # inside the axes near the top edge
|
|
#ncol=ncols,
|
|
frameon=True,
|
|
framealpha=1
|
|
#borderaxespad=0.4,
|
|
)
|
|
|
|
# No extra bottom space needed; tighten a bit at the top so legend doesn't clip
|
|
fig.tight_layout()
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
outfile = out_dir / sanitize_filename(f"grouped_{scope}_IoU{threshold}_{metric_latex}.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()
|
|
|
|
datasets, techniques, values = load_values_for_threshold(
|
|
root=root,
|
|
threshold=args.threshold,
|
|
scope=args.scope,
|
|
metric_latex=args.metric_latex,
|
|
)
|
|
|
|
ok = grouped_bar_chart(
|
|
datasets=datasets,
|
|
techniques=techniques,
|
|
values=values,
|
|
scope=args.scope,
|
|
threshold=args.threshold,
|
|
metric_latex=args.metric_latex,
|
|
out_dir=out_dir,
|
|
dpi=args.dpi,
|
|
)
|
|
if not ok:
|
|
print("[WARN] No plot generated. Check the folder/JSON contents and the metric key.")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|