Added Visualiztion code
This commit is contained in:
+2
-1
@@ -1,2 +1,3 @@
|
||||
datasets/*
|
||||
evaluation_results/*
|
||||
evaluation_results/*
|
||||
visual_results/*
|
||||
Binary file not shown.
+6
-4
@@ -16,13 +16,15 @@ class Config:
|
||||
face_model_type="yunet"
|
||||
|
||||
evaluation_results_directory = "evaluation_results/"
|
||||
visual_results_directory = "visual_results/"
|
||||
|
||||
verbose=True
|
||||
|
||||
tasks = {"preprocessing": True, # optional if already done
|
||||
"obfuscation": True, # optional if already done
|
||||
"post_extract": True, # optional if already done
|
||||
"analysis": True # optional if already done
|
||||
tasks = {"preprocessing": False, # optional if already done
|
||||
"obfuscation": False, # optional if already done
|
||||
"post_extract": False, # optional if already done
|
||||
"analysis": False, # optional if already done
|
||||
"visualize": True #Should be always true, since it is the last step for reasoning
|
||||
}
|
||||
|
||||
|
||||
|
||||
+26
-1
@@ -1,11 +1,14 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from config import Config
|
||||
from data_loader import DatasetLoader
|
||||
from image_preprocessor import DataPreprocessor
|
||||
from meta_data.comparator import Comparator
|
||||
from meta_data.post_extraction import PostExtractor
|
||||
from obfuscation.obfuscation_engine import ObfuscationEngine
|
||||
from visualization.visualizer import Visualizer
|
||||
|
||||
|
||||
##Motivation
|
||||
@@ -76,7 +79,29 @@ def main():
|
||||
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)
|
||||
#TODO: 5. Visualize results
|
||||
|
||||
if Config.tasks["visualize"]:
|
||||
print("5. Running visualization")
|
||||
out_dir = Path(Config.visual_results_directory); out_dir.mkdir(exist_ok=True)
|
||||
viz = Visualizer(Config.evaluation_results_directory)
|
||||
for ds in viz.datasets():
|
||||
for cat in viz.categories():
|
||||
if cat == "meta":
|
||||
continue
|
||||
fname = f"{ds}_{cat}.png"
|
||||
save_path = out_dir / fname
|
||||
viz.plot_category_by_tech(dataset=ds,
|
||||
category=cat,
|
||||
save=save_path)
|
||||
print(f"📊 {save_path} gespeichert")
|
||||
|
||||
#TODO: metriken aus grafik rausnehmen; für jeden 3
|
||||
#TODO: ohne UTK
|
||||
|
||||
#TODO Bestes gesicht? FaceBox iou
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -17,4 +17,4 @@ class Randoming(ObfuscationTechnique):
|
||||
return obf
|
||||
|
||||
def name(self):
|
||||
return "random_block"
|
||||
return "random"
|
||||
Binary file not shown.
@@ -0,0 +1,89 @@
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
import re, json
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
class Visualizer:
|
||||
"""
|
||||
Liest results_{dataset}_{technique}.json und hält ein langes DataFrame.
|
||||
• ein Record pro (dataset, technique, category, metric)
|
||||
• keine Aggregation nötig – jede Datei enthält EINEN Wert je Metrik
|
||||
"""
|
||||
|
||||
_PTN = re.compile(r"results_(?P<dataset>[^_]+)_(?P<technique>[^.]+)\.json$")
|
||||
|
||||
def __init__(self, json_dir: str | Path):
|
||||
self.json_dir = Path(json_dir)
|
||||
if not self.json_dir.exists():
|
||||
raise FileNotFoundError(self.json_dir)
|
||||
self.df = self._load_jsons()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public helpers
|
||||
# ------------------------------------------------------------------
|
||||
def datasets(self) -> list[str]:
|
||||
return sorted(self.df["dataset"].unique())
|
||||
|
||||
def categories(self) -> list[str]:
|
||||
return sorted(self.df["category"].unique())
|
||||
|
||||
def metrics_of(self, category: str) -> list[str]:
|
||||
return sorted(self.df[self.df["category"] == category]["metric"].unique())
|
||||
|
||||
# -- Kernplot -------------------------------------------------------
|
||||
def plot_category_by_tech(self,
|
||||
dataset: str,
|
||||
category: str,
|
||||
figsize=(9, 5),
|
||||
save: str | Path | None = None):
|
||||
"""
|
||||
Ein Balkendiagramm: alle Metriken dieser Kategorie,
|
||||
gruppiert nach Technik, nur für EIN Dataset.
|
||||
"""
|
||||
sub = self.df[(self.df["dataset"] == dataset) &
|
||||
(self.df["category"] == category)]
|
||||
if sub.empty:
|
||||
print(f"[⚠] Kein Eintrag für Dataset={dataset}, Cat={category}")
|
||||
return
|
||||
|
||||
# Pivot: index = technique, columns = metrics
|
||||
pivot = sub.pivot(index="technique", columns="metric", values="value")
|
||||
print(pivot)
|
||||
fig, ax = plt.subplots(figsize=figsize)
|
||||
pivot.plot(kind="bar", ax=ax)
|
||||
|
||||
ax.set_title(f"{dataset} – {category.capitalize()} metrics")
|
||||
ax.set_xlabel("Technique")
|
||||
ax.set_ylabel("score")
|
||||
ax.grid(axis="y", linestyle="--", alpha=0.4)
|
||||
ax.legend(title="metric", bbox_to_anchor=(1.02, 1), loc="upper left")
|
||||
|
||||
plt.tight_layout()
|
||||
if save:
|
||||
fig.savefig(save, dpi=150, bbox_inches="tight")
|
||||
plt.close(fig)
|
||||
return fig, ax
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# intern
|
||||
# ------------------------------------------------------------------
|
||||
def _load_jsons(self) -> pd.DataFrame:
|
||||
recs = []
|
||||
for file in self.json_dir.glob("results_*_*.json"):
|
||||
m = self._PTN.match(file.name)
|
||||
if not m:
|
||||
continue
|
||||
dataset, tech = m.group("dataset"), m.group("technique")
|
||||
data = json.load(open(file, "r"))
|
||||
|
||||
for cat, metrics in data.items():
|
||||
for metric, val in metrics.items():
|
||||
recs.append({"dataset": dataset,
|
||||
"technique": tech,
|
||||
"category": cat,
|
||||
"metric": metric,
|
||||
"value": val})
|
||||
if not recs:
|
||||
raise RuntimeError("Keine passenden JSON-Dateien gefunden.")
|
||||
return pd.DataFrame.from_records(recs)
|
||||
Reference in New Issue
Block a user