diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index c6d6cb6..0e6181f 100644 Binary files a/project/__pycache__/config.cpython-310.pyc and b/project/__pycache__/config.cpython-310.pyc differ diff --git a/project/config.py b/project/config.py index 4de0b29..8671d2d 100644 --- a/project/config.py +++ b/project/config.py @@ -24,8 +24,8 @@ class Config: pose_model_type="models/yolo11m-pose.pt" #"models/yolo11x-pose.pt" face_model_type="yunet" # "retinaface" - evaluation_results_directory = "evaluation_results/evaluation_results_99_with_correct_acc_deid/" - visual_results_directory = "visual_results/visual_results_99_with_correct_acc_deid/" + evaluation_results_directory = "evaluation_results/evaluation_results_90_with_correct_acc_deid/" + visual_results_directory = "visual_results/visual_results_90_with_correct_acc_deid/" verbose=True @@ -38,7 +38,7 @@ class Config: "visualize": True #Should be always true, since it is the last step for reasoning } - bbox_matching_iou = 0.99 + bbox_matching_iou = 0.9 #DEBUG diff --git a/project/main.py b/project/main.py index 5521d95..f32577e 100644 --- a/project/main.py +++ b/project/main.py @@ -57,24 +57,25 @@ def main(): print("4. Running analysis") comparator = Comparator() for before_dataset_name in os.listdir(Config.filtered_output_directory): - before_dataset_path = os.path.join(Config.filtered_output_directory, before_dataset_name) - for after_dataset_name in os.listdir(Config.obfuscated_output_directory): - if before_dataset_name == after_dataset_name: - after_dataset_path = os.path.join(Config.obfuscated_output_directory, after_dataset_name) - #For each technique, compare the datasets - for technique_name in os.listdir(after_dataset_path): - if technique_name != "NO_OP": - technique_path = os.path.join(after_dataset_path, technique_name) - current_technique_results_directory = os.path.join(Config.evaluation_results_directory, f"results_{before_dataset_name}_{technique_name}.json") - if os.path.exists(current_technique_results_directory): - print(f"Results for {before_dataset_name} with {technique_name} obfuscation already exist, skipping") - continue - print(f"Comparing {before_dataset_name} with {technique_name} obfuscation") - technique_result_dict = comparator.compare_with_before_and_after_folder(before_dataset_path, technique_path) - #Save results in evaluation_results_directory as json - print(f"Saving results in {current_technique_results_directory}") - with open(current_technique_results_directory, "w") as f: - json.dump(technique_result_dict, f, indent=4) + if before_dataset_name in Config.dataset_names: + before_dataset_path = os.path.join(Config.filtered_output_directory, before_dataset_name) + for after_dataset_name in os.listdir(Config.obfuscated_output_directory): + if before_dataset_name == after_dataset_name: + after_dataset_path = os.path.join(Config.obfuscated_output_directory, after_dataset_name) + #For each technique, compare the datasets + for technique_name in os.listdir(after_dataset_path): + if technique_name != "NO_OP": + technique_path = os.path.join(after_dataset_path, technique_name) + current_technique_results_directory = os.path.join(Config.evaluation_results_directory, f"results_{before_dataset_name}_{technique_name}.json") + if os.path.exists(current_technique_results_directory): + print(f"Results for {before_dataset_name} with {technique_name} obfuscation already exist, skipping") + continue + print(f"Comparing {before_dataset_name} with {technique_name} obfuscation") + technique_result_dict = comparator.compare_with_before_and_after_folder(before_dataset_path, technique_path) + #Save results in evaluation_results_directory as json + print(f"Saving results in {current_technique_results_directory}") + with open(current_technique_results_directory, "w") as f: + json.dump(technique_result_dict, f, indent=4) if Config.tasks["visualize"]: print("5. Running visualization") diff --git a/project/visualization/vizualizer4.py b/project/visualization/vizualizer4.py new file mode 100644 index 0000000..6c33561 --- /dev/null +++ b/project/visualization/vizualizer4.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +""" +Grouped bar chart for a single metric at one IoU threshold. + +Layout expected: +root/ + evaluation_results_50/ + result_{datasetA}_{tech1}.json + result_{datasetA}_{tech2}.json + result_{datasetB}_{tech1}.json + result_{datasetB}_{tech2}.json + ... + +Each JSON has keys like: +{ + "face": { + "\\mathrm{Acc}_\\mathrm{deID}": 83.2 + }, + ... +} + +Usage example: + python grouped_metric_bar.py --root /path/to/root --threshold 50 \ + --metric-latex "\\mathrm{Acc}_\\mathrm{deID}" --scope face --out ./plots +""" + +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', '.', '*'] + + +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: + # Allow letters, digits, dot, underscore, plus, hyphen; replace everything else with "_" + s = re.sub(r'[^A-Za-z0-9._+\-]+', '_', s) + s = re.sub(r'_+', '_', s).strip('._ ') + return s + +def rsplit_dataset_technique(filename: str): + # Given 'results_{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 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): + """Return: + datasets: sorted list + techniques: sorted list + values[technique][dataset] = number (0..100) or math.nan if missing + """ + 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()} # be tolerant about case + techniques_set, datasets_set = set(), set() + values = defaultdict(dict) # technique -> dataset -> value + + 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 + + # find scope block (prefer exact, but allow simple case variations) + 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 = sorted(techniques_set) + + # Ensure every (technique, dataset) has an entry + for t in techniques: + for d in datasets: + values[t].setdefault(d, math.nan) + + return datasets, techniques, values + +# Distinct hatch patterns for datasets (cycled if there are many datasets) +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 + + # dynamic width for readability + fig_w = max(8, 0.8 * len(techniques) + 3) + fig, ax = plt.subplots(figsize=(fig_w, 5.5)) # a touch taller to make room for legend + + n_groups = len(techniques) + n_bars = len(datasets) + group_x = list(range(n_groups)) + total_width = 0.8 # fraction of space per group occupied by bars + 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=dataset) + + # Apply hatch pattern + clearer edges for visibility + 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 on bars (percentages), version-safe + 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, + ) + + # X axis: technique names at group centers + ax.set_xticks(group_x) + ax.set_xticklabels(techniques) + + # Y axis: 0–100 with % labels + ax.set_ylim(0, 105) + ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y:.0f}%")) + + # Labels (y uses the LaTeX metric key) + ax.set_ylabel(f"${metric_latex}$", fontsize=14) + + ax.grid(axis="y", linestyle="--", alpha=0.4) + + # --- Legend BELOW the plot --- + handles, labels = ax.get_legend_handles_labels() + ncols = min(len(datasets), 4) if len(datasets) > 1 else 1 + leg = ax.legend( + handles, + labels, + loc="upper center", + bbox_to_anchor=(0.5, -0.05), # push below axes + ncol=ncols, + frameon=True, + ) + + # Make some extra bottom space for the legend + fig.subplots_adjust(bottom=0.22) + + out_dir.mkdir(parents=True, exist_ok=True) + outfile = out_dir / sanitize_filename(f"grouped_{scope}_IoU{threshold}_{metric_latex}.pdf") + fig.tight_layout() + 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()