diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index aea8cb8..4d505ff 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 68568f6..6f91e46 100644 --- a/project/config.py +++ b/project/config.py @@ -2,6 +2,7 @@ from obfuscation.block_black import Blackening from obfuscation.block_random import Randoming from obfuscation.block_white import Whitening from obfuscation.blurring import Blurring +from obfuscation.no_op import NO_OP from obfuscation.swap import Swap #from obfuscation.fams import FAMS from obfuscation.pixelation import Pixelation @@ -17,7 +18,7 @@ class Config: raw_dataset_path="datasets/raw/" filtered_output_directory="datasets/filtered/" obfuscated_output_directory="datasets/obfuscated/" - max_images_per_dataset=1000 + max_images_per_dataset= 1000 # 1000 seg_model_type="models/yolo11l-seg.pt" pose_model_type="models/yolo11l-pose.pt" @@ -28,11 +29,11 @@ class Config: verbose=True - tasks = {"preprocessing": False, # optional if already done + tasks = {"preprocessing": True, # optional if already done "obfuscation": True, # optional if already done - "post_extract": False, # optional if already done - "analysis": False, # optional if already done - "visualize": False #Should be always true, since it is the last step for reasoning + "post_extract": True, # optional if already done + "analysis": True, # optional if already done + "visualize": True #Should be always true, since it is the last step for reasoning } @@ -40,9 +41,10 @@ class Config: debug_show_preprocessing=False obfuscation_techniques=[ - # Synthetic(), - # Style(), - # Swap(), + NO_OP(), + Synthetic(), + Style(), + Swap(), Blackening(), Randoming(), Blurring(), diff --git a/project/main.py b/project/main.py index 11d74b9..518fdd4 100644 --- a/project/main.py +++ b/project/main.py @@ -13,6 +13,8 @@ from visualization.visualizer import Visualizer import random import torch +from visualization.visualizer2 import Visualizer2 + random.seed(Config.seed) torch.manual_seed(Config.seed) @@ -67,23 +69,35 @@ def main(): 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}.pdf" + # save_path = out_dir / fname + # viz.plot_category_by_tech(dataset=ds, + # category=cat, + # save=save_path) + # print(f"📊 {save_path} gespeichert") 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}.pdf" - save_path = out_dir / fname - viz.plot_category_by_tech(dataset=ds, - category=cat, - save=save_path) - print(f"📊 {save_path} gespeichert") - - + viz = Visualizer2(Config.evaluation_results_directory) + for cat in viz.categories(): + if cat == "meta": + continue + viz.plot_category_range( + category=cat, + save=out_dir / f"range_{cat}.pdf", + hatches=("///", "..", "xx"), # optional: or leave None for colour‑only + percent_axis=True + ) +#TODO: NO-OP zum Testen +#TODO: PNG #TODO In paper beispiele zeigen mit den modellen diff --git a/project/meta_data/__pycache__/comparator.cpython-310.pyc b/project/meta_data/__pycache__/comparator.cpython-310.pyc index 3d03580..43e91de 100644 Binary files a/project/meta_data/__pycache__/comparator.cpython-310.pyc and b/project/meta_data/__pycache__/comparator.cpython-310.pyc differ diff --git a/project/meta_data/comparator.py b/project/meta_data/comparator.py index e8438f9..ed7af6b 100644 --- a/project/meta_data/comparator.py +++ b/project/meta_data/comparator.py @@ -13,12 +13,12 @@ from scipy.spatial.distance import cosine import cv2 -def _load_meta_and_images(path_to_meta: str): +def _load_meta_and_images(path_to_meta: str, file_type_postfix): #Load dict meta = None with open(path_to_meta, 'r') as f: meta = json.load(f) - path_to_img = path_to_meta.replace(".json", ".jpg") + path_to_img = path_to_meta.replace(".json", file_type_postfix) img = cv2.imread(path_to_img) return img, meta @@ -252,23 +252,16 @@ def compute_scores(folder_result_dict): scores = { "person": { "\mathrm{Acc}_\mathrm{det}": (folder_result_dict["found_matching_persons_count"] / folder_result_dict["before_person_count"]) * 100.0, - #"person_bbox_iou_avg": np.mean(folder_result_dict["person_bbox_ious"]) if len(folder_result_dict["person_bbox_ious"]) > 0 else 0.0, "\mathrm{mIoU}_\mathrm{seg}": np.mean(folder_result_dict["person_segment_ious"]) if len(folder_result_dict["person_segment_ious"]) > 0 else 0.0, - #"person_keypoint_accuracy_avg": np.mean(folder_result_dict["person_keypoint_accuracies"]) if len(folder_result_dict["person_keypoint_accuracies"]) > 0 else 0.0, "\mathrm{Sim}_\mathrm{kp}": np.mean(folder_result_dict["person_keypoint_position_similarities"]) if len(folder_result_dict["person_keypoint_position_similarities"]) > 0 else 0.0, }, "face": { "\mathrm{Acc}_\mathrm{det}": (folder_result_dict["found_face_count"] / folder_result_dict["before_person_count"]) * 100.0, - #"face_bbox_iou_avg": np.mean(folder_result_dict["face_bbox_ious"]) if len(folder_result_dict["face_bbox_ious"]) > 0 else 0.0, "\mathrm{Acc}_\mathrm{emo}": (folder_result_dict["same_emotion_count"] / folder_result_dict["found_face_count"]) * 100.0 if folder_result_dict["found_face_count"] > 0 else 0.0, - #"emotion_vector_similarity_avg": np.mean(folder_result_dict["emotion_vector_similarities"]) if len(folder_result_dict["emotion_vector_similarities"]) > 0 else 0.0, "\mathrm{Acc}_\mathrm{deID}": (1.0 - (folder_result_dict["same_person_counter"] / folder_result_dict["found_face_count"])) * 100.0 if folder_result_dict["found_face_count"] > 0 else 100.0, - #"identity_distance_avg": np.mean(folder_result_dict["identity_distances"]) if len(folder_result_dict["identity_distances"]) > 0 else 100.0, - #"face_keypoint_position_similarity_avg": np.mean(folder_result_dict["face_keypoint_position_similarities"]) if len(folder_result_dict["face_keypoint_position_similarities"]) > 0 else 0.0 }, "object": { "\mathrm{Acc}_\mathrm{det}": (folder_result_dict["found_matching_objects_count"] / folder_result_dict["before_object_count"]) * 100.0, - #"object_bbox_iou_avg": np.mean(folder_result_dict["object_bbox_ious"]) if len(folder_result_dict["object_bbox_ious"]) > 0 else 0.0, "\mathrm{mIoU}_\mathrm{seg}": np.mean(folder_result_dict["object_segment_ious"]) if len(folder_result_dict["object_segment_ious"]) > 0 else 0.0, "\mathrm{Acc}_\mathrm{cls}": (folder_result_dict["found_matching_classes_count"] / folder_result_dict["before_object_count"]) * 100.0 }, @@ -297,10 +290,20 @@ def compute_scores(folder_result_dict): "len_object_segment_ious": len(folder_result_dict["object_segment_ious"]), "found_matching_classes_count": folder_result_dict["found_matching_classes_count"] } + }, + "other": { + "person_bbox_iou_avg": np.mean(folder_result_dict["person_bbox_ious"]) if len(folder_result_dict["person_bbox_ious"]) > 0 else 0.0,### + "person_keypoint_accuracy_avg": np.mean(folder_result_dict["person_keypoint_accuracies"]) if len(folder_result_dict["person_keypoint_accuracies"]) > 0 else 0.0,### + "face_bbox_iou_avg": np.mean(folder_result_dict["face_bbox_ious"]) if len(folder_result_dict["face_bbox_ious"]) > 0 else 0.0,### + "emotion_vector_similarity_avg": np.mean(folder_result_dict["emotion_vector_similarities"]) if len(folder_result_dict["emotion_vector_similarities"]) > 0 else 0.0,### + "identity_distance_avg": np.mean(folder_result_dict["identity_distances"]) if len(folder_result_dict["identity_distances"]) > 0 else 100.0,### + "face_keypoint_position_similarity_avg": np.mean(folder_result_dict["face_keypoint_position_similarities"]) if len(folder_result_dict["face_keypoint_position_similarities"]) > 0 else 0.0, + "object_bbox_iou_avg": np.mean(folder_result_dict["object_bbox_ious"]) if len(folder_result_dict["object_bbox_ious"]) > 0 else 0.0### } } return scores + class Comparator: def compare_with_before_and_after_folder(self, before_directory: str, obfuscated_directory: str): #Validate it's the same dataset @@ -329,8 +332,8 @@ class Comparator: #Compare two images def _get_insights_from_comparison(self, path_to_meta_before: str, path_to_meta_after: str) -> dict: - before_img, before_meta = _load_meta_and_images(path_to_meta_before) - after_img, after_meta = _load_meta_and_images(path_to_meta_after) + before_img, before_meta = _load_meta_and_images(path_to_meta_before, ".jpg") + after_img, after_meta = _load_meta_and_images(path_to_meta_after, ".png") #Person scores before_person_count = len(before_meta["persons"]) diff --git a/project/models/epic/image_cache/face.jpg b/project/models/epic/image_cache/face.jpg index 74490c8..c1ed063 100644 Binary files a/project/models/epic/image_cache/face.jpg and b/project/models/epic/image_cache/face.jpg differ diff --git a/project/models/epic/image_cache/obfuscated_face.jpg b/project/models/epic/image_cache/obfuscated_face.jpg index bb1a4f9..d2fa83e 100644 Binary files a/project/models/epic/image_cache/obfuscated_face.jpg and b/project/models/epic/image_cache/obfuscated_face.jpg differ diff --git a/project/models/ganonymization/image_cache/face.jpg b/project/models/ganonymization/image_cache/face.jpg index 74490c8..c1ed063 100644 Binary files a/project/models/ganonymization/image_cache/face.jpg and b/project/models/ganonymization/image_cache/face.jpg differ diff --git a/project/models/ganonymization/image_cache/obfuscated_face.jpg b/project/models/ganonymization/image_cache/obfuscated_face.jpg index 82fd8a7..86ecd1f 100644 Binary files a/project/models/ganonymization/image_cache/obfuscated_face.jpg and b/project/models/ganonymization/image_cache/obfuscated_face.jpg differ diff --git a/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc b/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc index 8d60719..36fe9d3 100644 Binary files a/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc and b/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc differ diff --git a/project/obfuscation/no_op.py b/project/obfuscation/no_op.py new file mode 100644 index 0000000..33c7cd3 --- /dev/null +++ b/project/obfuscation/no_op.py @@ -0,0 +1,22 @@ +import os + +import numpy as np +import cv2 + +from obfuscation.base_obfuscation_technique import ObfuscationTechnique +import requests + +#NOTE: Run the server with conda obfuscation_platform_p37 +class NO_OP(ObfuscationTechnique): + """ + Replace face with generated face + """ + def __init__(self): + print("Initializing NO_OP") + + + def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray: + return face_roi_img_bgr + + def name(self): + return "NO_OP" \ No newline at end of file diff --git a/project/obfuscation/obfuscation_engine.py b/project/obfuscation/obfuscation_engine.py index cda5a04..2e4a487 100644 --- a/project/obfuscation/obfuscation_engine.py +++ b/project/obfuscation/obfuscation_engine.py @@ -70,7 +70,8 @@ class ObfuscationEngine: if not os.path.exists(technique_path): os.makedirs(technique_path) for image_path, meta_path in image_meta_pairs: - obfuscated_image_output_path = os.path.join(technique_path, os.path.basename(image_path)) + image_as_png = os.path.basename(image_path).split(".")[0] + ".png" + obfuscated_image_output_path = os.path.join(technique_path, image_as_png) if os.path.exists(obfuscated_image_output_path): print(f"Skipping {obfuscated_image_output_path} as it already exists") continue diff --git a/project/obfuscation/style.py b/project/obfuscation/style.py index a0cf26c..e68f5e0 100644 --- a/project/obfuscation/style.py +++ b/project/obfuscation/style.py @@ -13,15 +13,15 @@ class Style(ObfuscationTechnique): Replace face with generated face """ def __init__(self): - print("Style not activated") - # self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/vtoonify/image_cache/" - # resp = requests.get("http://127.0.0.1:8000/init", timeout=180) - # resp.raise_for_status() + # print("Style not activated") + self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/vtoonify/image_cache/" + resp = requests.get("http://127.0.0.1:8002/init", timeout=180) + resp.raise_for_status() def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray: cv2.imwrite(os.path.join(self.image_processing_path, "face.jpg"), face_roi_img_bgr) - resp = requests.get("http://127.0.0.1:8000/obfuscate", timeout=180) + resp = requests.get("http://127.0.0.1:8002/obfuscate", timeout=180) resp.raise_for_status() obfuscated_face = cv2.imread(os.path.join(self.image_processing_path, "obfuscated_face.jpg")) return obfuscated_face diff --git a/project/obfuscation/swap.py b/project/obfuscation/swap.py index 9f608f3..8cf87ab 100644 --- a/project/obfuscation/swap.py +++ b/project/obfuscation/swap.py @@ -12,10 +12,10 @@ class Swap(ObfuscationTechnique): Replace face with generated face """ def __init__(self): - print("epic not active") - # self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/epic/image_cache/" - # resp = requests.get(f"http://127.0.0.1:8000/init", timeout=60) - # resp.raise_for_status() + # print("epic not active") + self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/epic/image_cache/" + resp = requests.get(f"http://127.0.0.1:8000/init", timeout=60) + resp.raise_for_status() def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray: diff --git a/project/obfuscation/synthetic.py b/project/obfuscation/synthetic.py index e0a020c..082f7d0 100644 --- a/project/obfuscation/synthetic.py +++ b/project/obfuscation/synthetic.py @@ -13,15 +13,15 @@ class Synthetic(ObfuscationTechnique): """ def __init__(self): - print("synthetic not active") - # self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/ganonymization/image_cache/" - # resp = requests.get(f"http://127.0.0.1:8000/init", timeout=120) - # resp.raise_for_status() + # print("synthetic not active") + self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/ganonymization/image_cache/" + resp = requests.get(f"http://127.0.0.1:8003/init", timeout=120) + resp.raise_for_status() def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray: cv2.imwrite(os.path.join(self.image_processing_path, "face.jpg"), face_roi_img_bgr) - resp = requests.get(f"http://127.0.0.1:8000/obfuscate", timeout=120) + resp = requests.get(f"http://127.0.0.1:8003/obfuscate", timeout=120) resp.raise_for_status() obfuscated_face = cv2.imread(os.path.join(self.image_processing_path, "obfuscated_face.jpg")) return obfuscated_face diff --git a/project/visualization/visualizer2.py b/project/visualization/visualizer2.py new file mode 100644 index 0000000..c2de570 --- /dev/null +++ b/project/visualization/visualizer2.py @@ -0,0 +1,184 @@ +from __future__ import annotations +from pathlib import Path +import re, json, itertools +import pandas as pd +import matplotlib.pyplot as plt +import matplotlib.ticker as mtick +from matplotlib.lines import Line2D +from matplotlib.patches import Patch +import numpy as np + + +class Visualizer2: + """ + 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[^_]+)_(?P[^.]+)\.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_range( + self, + category: str, + figsize=(11, 5), + save: str | Path | None = None, + *, + font_sizes: dict | None = None, # {'axes':13,'ticks':11,'legend':11,'title':14,'annot':7} + cmap: str = "tab10", + hatches: tuple[str, ...] | None = None,# ("///","..","xx") or leave None + bar_width: float = .18, + metric_jitter: float = .25, # sideways spacing between metrics + group_gap: float = .6, # whitespace between technique groups + percent_axis: bool = True, + show_values: bool = False, # numeric labels at min & max + ): + """ + One figure per category. Each vertical bar shows min–max across datasets. + The bar colour / hatch identifies the metric. The x‑axis shows techniques. + """ + df = self.df[self.df["category"] == category].copy() + if df.empty: + print(f"[⚠] No data for category={category!r}") + return + + # ---------- aggregate min & max across datasets -------------- + agg = ( + df.groupby(["technique", "metric"])["value"] + .agg(["min", "max"]) + .reset_index() + ) + + techs = sorted(agg["technique"].unique()) + metrics = sorted(agg["metric"].unique()) + + # ---------- colour & hatch palettes -------------------------- + colours = plt.get_cmap(cmap).colors + colour_map = {m: colours[i % len(colours)] for i, m in enumerate(metrics)} + hatch_map = ({m: "" for m in metrics} if hatches is None + else {m: hatches[i % len(hatches)] for i, m in enumerate(metrics)}) + + # ---------- figure scaffold ---------------------------------- + fig, ax = plt.subplots(figsize=figsize) + fs = dict(title=14, axes=13, ticks=11, legend=11, annot=7) + if font_sizes: + fs.update(font_sizes) + + # ---------- x‑positions -------------------------------------- + group_centres = np.arange(len(techs)) * (1 + group_gap) + offset_range = np.linspace( + -metric_jitter * (len(metrics)-1)/2, + metric_jitter * (len(metrics)-1)/2, + len(metrics) + ) + xloc = { + (tech, met): group_centres[t_idx] + offset_range[m_idx] + for t_idx, tech in enumerate(techs) + for m_idx, met in enumerate(metrics) + } + + # ---------- draw bars + caps + labels ------------------------ + cap_half = bar_width * 0.8 # little horizontal line ends + for _, row in agg.iterrows(): + tech, met, vmin, vmax = row + x = xloc[(tech, met)] + + # main bar + ax.bar(x, + height=vmax - vmin, + bottom=vmin, + width=bar_width, + color=colour_map[met], + hatch=hatch_map[met], + edgecolor="black", + linewidth=0.7, + zorder=3) + + # black caps at min & max + ax.hlines([vmin, vmax], + x - cap_half, x + cap_half, + color="black", + linewidth=1.2, + zorder=4) + + # numeric labels (optional) + if show_values: + ax.text(x, vmax - 1, f"{vmax:.0f}", + ha="center", va="top", + fontsize=fs["annot"]) + ax.text(x, vmin + 1, f"{vmin:.0f}", + ha="center", va="bottom", + fontsize=fs["annot"]) + + # ---------- axes formatting ---------------------------------- + ax.set_xticks(group_centres, techs, fontsize=fs["ticks"]) + ax.set_xlabel("Technique", fontsize=fs["axes"]) + + ax.set_ylim(-1, 105) + ax.set_ylabel("Score [%]" if percent_axis else "Score", + fontsize=fs["axes"]) + if percent_axis: + ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=100)) + ax.tick_params(axis="y", labelsize=fs["ticks"]) + ax.grid(axis="y", linestyle="--", alpha=.3, zorder=0) + + fig.suptitle(category.capitalize(), fontsize=fs["title"]) + + # ---------- legend (metrics) --------------------------------- + handles = [Patch(facecolor=colour_map[m], + edgecolor="black", + hatch=hatch_map[m], + label=f"${m}$") + for m in metrics] + ax.legend(handles=handles, + title="Metric", + loc="upper left", bbox_to_anchor=(1.02, 1), + frameon=True, fontsize=fs["legend"]) + + # ---------- export ------------------------------------------- + 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)