diff --git a/project/.gitignore b/project/.gitignore index 29a8f77..84e7a25 100644 --- a/project/.gitignore +++ b/project/.gitignore @@ -4,4 +4,5 @@ visual_results/* __pycache__/* project/__pycache__/* project/obfuscation/__pycache__/* -*.pyc \ No newline at end of file +*.pyc +old_results/* \ No newline at end of file diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index 50c3fb0..a053ac1 100644 Binary files a/project/__pycache__/config.cpython-310.pyc and b/project/__pycache__/config.cpython-310.pyc differ diff --git a/project/__pycache__/image_preprocessor.cpython-310.pyc b/project/__pycache__/image_preprocessor.cpython-310.pyc index f9c5af4..f96d7c5 100644 Binary files a/project/__pycache__/image_preprocessor.cpython-310.pyc and b/project/__pycache__/image_preprocessor.cpython-310.pyc differ diff --git a/project/config.py b/project/config.py index bb2b4bf..feeb549 100644 --- a/project/config.py +++ b/project/config.py @@ -16,34 +16,36 @@ class Config: seed = 42 raw_dataset_path="datasets/raw/" - filtered_output_directory="datasets/filtered/" - obfuscated_output_directory="datasets/obfuscated/" + filtered_output_directory="datasets/filtered_yolom_yunet/" # datasets/filtered_yolox_retinaface/ + obfuscated_output_directory="datasets/obfuscated_yolom_yunet/" # #datasets/obfuscated_yolox_retinaface/ max_images_per_dataset= 1000 - seg_model_type="models/yolo11m-seg.pt" - pose_model_type="models/yolo11m-pose.pt" - face_model_type="yunet" + seg_model_type="models/yolo11m-seg.pt" #"models/yolo11x-seg.pt" + pose_model_type="models/yolo11m-pose.pt" #"models/yolo11x-pose.pt" + face_model_type="yunet" # "retinaface" evaluation_results_directory = "evaluation_results/" visual_results_directory = "visual_results/" verbose=True - dataset_names = ["aaa", "celeba", "wider", "utk"] + dataset_names = ["celeba", "wider", "utk"] - tasks = {"preprocessing": True, # optional if already done - "obfuscation": True, # optional if already done - "post_extract": 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": True, # optional if already done "visualize": True #Should be always true, since it is the last step for reasoning } + bbox_matching_iou = 0.5 + #DEBUG debug_show_preprocessing=False obfuscation_techniques=[ - NO_OP(), + #NO_OP(), Synthetic(), Style(), Swap(), diff --git a/project/main.py b/project/main.py index f771dd1..98287c1 100644 --- a/project/main.py +++ b/project/main.py @@ -77,31 +77,37 @@ 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 = 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 - ) + 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 = 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: Kombinierter Ansatz, vllt besser. +#Erzeuge Gesicht mit passenden Gesichtszügen. Passe es nochmal an. + #TODO größenverteilung auch berechnen nicht nur position diff --git a/project/meta_data/__pycache__/comparator.cpython-310.pyc b/project/meta_data/__pycache__/comparator.cpython-310.pyc index aba8692..ada5809 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/__pycache__/meta_data_extractor.cpython-310.pyc b/project/meta_data/__pycache__/meta_data_extractor.cpython-310.pyc index bdc39c7..ed2334f 100644 Binary files a/project/meta_data/__pycache__/meta_data_extractor.cpython-310.pyc and b/project/meta_data/__pycache__/meta_data_extractor.cpython-310.pyc differ diff --git a/project/meta_data/comparator.py b/project/meta_data/comparator.py index 77a2543..c22cb12 100644 --- a/project/meta_data/comparator.py +++ b/project/meta_data/comparator.py @@ -12,6 +12,8 @@ from tqdm import tqdm from scipy.spatial.distance import cosine import cv2 +from config import Config + def _load_meta_and_images(path_to_meta: str, file_type_postfix): #Load dict @@ -86,48 +88,32 @@ def _poly_iou(poly_a, poly_b) -> float: iou = 0 return iou -def _find_best_matching_object(obj,other_objects, min_iou: float = 0.90): - """ - 1. Sammle alle Kandidaten, deren BBox-IoU ≥ min_iou. - 2. Bevorzuge den Kandidaten mit derselben Klasse und - höchster IoU. Gibt es keinen, nimm einfach den Kandidaten - mit der höchsten IoU (klasseunabhängig). - 3. Liefere [obj, bbox_iou %, seg_iou %] oder None. - """ - if not other_objects: - return None +def _find_best_matching_object(obj, other_objects, min_iou): - best_any = None # [other, bbox_iou, seg_iou] - best_any_iou = -1.0 - best_same_class = None - best_same_iou = -1.0 ref_label = obj["label"] + best = None + best_bbox_iou = -1.0 for other in other_objects: + if other["label"] != ref_label: + continue + bbox_iou = _bbox_iou(obj["bbox"], other["bbox"]) if bbox_iou < min_iou: continue seg_iou = _poly_iou(obj["segment"], other["segment"]) - # Aktualisiere globalen Best-Match - if bbox_iou > best_any_iou: - best_any = [other, bbox_iou, seg_iou] - best_any_iou = bbox_iou + if bbox_iou > best_bbox_iou: + best = [other, bbox_iou, seg_iou] + best_bbox_iou = bbox_iou - # Aktualisiere Best-Match gleicher Klasse - if other["label"] == ref_label and bbox_iou > best_same_iou: - best_same_class = [other, bbox_iou, seg_iou] - best_same_iou = bbox_iou - - # Entscheide nach Priorität: erst gleiche Klasse, sonst bester beliebiger - best_match = best_same_class if best_same_class is not None else best_any - - if best_match: - best_match[1] *= 100.0 # BBox-IoU in Prozent - best_match[2] *= 100.0 # Segment-IoU in Prozent - return best_match + if not best: + return None + best[1] *= 100.0 # BBox-IoU % + best[2] *= 100.0 # Segment-IoU % + return best def _adapt_body_keypoints(kps, bbox): @@ -240,6 +226,7 @@ def init_folder_insights_dict(): "person_keypoint_accuracies": [], "person_keypoint_position_similarities": [], "found_face_count": 0, + "face_segment_ious": [], "face_bbox_ious": [], "same_emotion_count": 0, "emotion_vector_similarities": [], @@ -262,6 +249,7 @@ def write_image_results_to_folder_result_dict(image_result_dict, folder_result_d folder_result_dict["person_keypoint_accuracies"].extend(image_result_dict["person_keypoint_accuracies"]) folder_result_dict["person_keypoint_position_similarities"].extend(image_result_dict["person_keypoint_position_similarities"]) folder_result_dict["found_face_count"] += image_result_dict["found_face_count"] + folder_result_dict["face_segment_ious"].extend(image_result_dict["face_segment_ious"]) folder_result_dict["face_bbox_ious"].extend(image_result_dict["face_bbox_ious"]) folder_result_dict["same_emotion_count"] += image_result_dict["same_emotion_count"] folder_result_dict["emotion_vector_similarities"].extend(image_result_dict["emotion_vector_similarities"]) @@ -283,6 +271,7 @@ def compute_scores(folder_result_dict): }, "face": { "\mathrm{Acc}_\mathrm{det}": (folder_result_dict["found_face_count"] / folder_result_dict["before_person_count"]) * 100.0, + "\mathrm{mIoU}_\mathrm{seg}": np.mean(folder_result_dict["face_segment_ious"]) if len(folder_result_dict["face_segment_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, "\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, }, @@ -330,6 +319,159 @@ def compute_scores(folder_result_dict): return scores +import base64 +from typing import Optional, Tuple, Sequence + +import cv2 +import numpy as np + + +def _decode_base64_png_to_mask(b64_png: Optional[str]) -> Optional[np.ndarray]: + """ + Decode a base64-encoded PNG (grayscale/RGB/RGBA) to a boolean mask (H,W). + Returns None on failure. + """ + if not b64_png or not isinstance(b64_png, str): + return None + # allow data URLs + if b64_png.startswith("data:"): + parts = b64_png.split(",", 1) + if len(parts) == 2: + b64_png = parts[1] + try: + buf = base64.b64decode(b64_png, validate=False) + except Exception: + return None + arr = np.frombuffer(buf, dtype=np.uint8) + img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED) + if img is None: + return None + if img.ndim == 3: + img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + return img > 0 + + +def _place_mask_on_full( + mask_local: np.ndarray, + bbox: Sequence[int], + image_hw: Tuple[int, int], +) -> Optional[np.ndarray]: + """ + Place a bbox-local boolean mask into a full-image boolean canvas (H,W). + - mask_local: (h,w) bool + - bbox: [x0,y0,x1,y1] + - image_hw: (H, W) + Handles bbox clipping and resizes mask to bbox size (nearest). + Returns None if placement is impossible. + """ + H, W = image_hw + x0, y0, x1, y1 = map(int, bbox) + if x1 < x0: + x0, x1 = x1, x0 + if y1 < y0: + y0, y1 = y1, y0 + + # fully outside / degenerate + if x1 <= 0 or y1 <= 0 or x0 >= W or y0 >= H: + return None + bw, bh = x1 - x0, y1 - y0 + if bw <= 0 or bh <= 0: + return None + + # resize local mask to bbox size if needed + mh, mw = mask_local.shape[:2] + if (mw, mh) != (bw, bh): + mask_local = cv2.resize(mask_local.astype(np.uint8), (bw, bh), interpolation=cv2.INTER_NEAREST).astype(bool) + + # clip bbox to image bounds + x0c, y0c = max(0, x0), max(0, y0) + x1c, y1c = min(W, x1), min(H, y1) + if x1c <= x0c or y1c <= y0c: + return None + + # crop local mask to the visible part + dx_left = x0c - x0 + dy_top = y0c - y0 + dx_right = (x1 - x0) - (x1c - x0c) - dx_left + dy_bottom = (y1 - y0) - (y1c - y0c) - dy_top + + y_start = int(max(0, dy_top)) + x_start = int(max(0, dx_left)) + y_end = int(mask_local.shape[0] - max(0, dy_bottom)) + x_end = int(mask_local.shape[1] - max(0, dx_right)) + if y_end <= y_start or x_end <= x_start: + return None + + sub = mask_local[y_start:y_end, x_start:x_end] + full = np.zeros((H, W), dtype=bool) + full[y0c:y1c, x0c:x1c] = sub + return full + + +def _iou_same_shape(a: np.ndarray, b: np.ndarray) -> float: + inter = np.logical_and(a, b).sum(dtype=np.int64) + union = np.logical_or(a, b).sum(dtype=np.int64) + if union == 0: + return 1.0 # both empty + return float(inter) / float(union) + + +def compute_face_segment_iou(before_person, before_img, after_person, after_img): + """ + Compute IoU between two face segments in **full-image coordinates**. + + Assumptions: + - before_person and after_person refer to matched faces. + - each has 'face_bbox' and 'face_segment' (base64-PNG of the mask inside the bbox). + + Returns: + IoU in [0,1], or None if essential data is missing/invalid. + """ + b_bbox = before_person["face_bbox"] + a_bbox = after_person["face_bbox"] + b_seg = before_person["face_segment"] + a_seg = after_person["face_segment"] + if a_seg is None: + return 0 + # must have bbox and segment on BOTH sides + if (b_bbox is None) or (a_bbox is None) or (a_seg is None): + print("Problem occurred: (b_bbox is None) or (a_bbox is None) or (a_seg is None)") + print("Before Person", before_person) + print("After Person", after_person) + exit() + if not (isinstance(b_bbox, (list, tuple)) and len(b_bbox) == 4): + print("Problem occurred: not (isinstance(b_bbox, (list, tuple)) and len(b_bbox) == 4)") + print("Before Person", before_person) + print("After Person", after_person) + exit() + if not (isinstance(a_bbox, (list, tuple)) and len(a_bbox) == 4): + print("Problem occurred: not (isinstance(a_bbox, (list, tuple)) and len(a_bbox) == 4)") + print("Before Person", before_person) + print("After Person", after_person) + exit() + + b_local = _decode_base64_png_to_mask(b_seg) + a_local = _decode_base64_png_to_mask(a_seg) + if b_local is None or a_local is None: + print("Problem occurred: b_local is None or a_local is None") + print("Before Person", before_person) + print("After Person", after_person) + exit() + + Hb, Wb = before_img.shape[:2] + Ha, Wa = after_img.shape[:2] + + b_full = _place_mask_on_full(b_local, b_bbox, (Hb, Wb)) + a_full = _place_mask_on_full(a_local, a_bbox, (Ha, Wa)) + if b_full is None or a_full is None: + print("Problem occurred: b_full is None or a_full is None") + print("Before Person", before_person) + print("After Person", after_person) + exit() + + return _iou_same_shape(b_full, a_full) + + class Comparator: def compare_with_before_and_after_folder(self, before_directory: str, obfuscated_directory: str): #Validate it's the same dataset @@ -370,6 +512,7 @@ class Comparator: found_face_count = 0 face_bbox_ious = [] + face_segment_ious = [] same_emotion_count = 0 emotion_vector_similarities = [] same_person_counter = 0 @@ -384,7 +527,7 @@ class Comparator: object_segment_ious = [] for before_person in before_meta["persons"]: - result = _find_best_matching_object(before_person, after_meta["persons"], 0.90) + result = _find_best_matching_object(before_person, after_meta["persons"], Config.bbox_matching_iou) if result is None: continue after_person, bbox_iou, segment_iou = result @@ -400,9 +543,18 @@ class Comparator: raise ValueError("Before person has no face", path_to_meta_before) if after_person["face_bbox"] is not None: face_iou = _bbox_iou(before_person["face_bbox"], after_person["face_bbox"]) * 100.0 - if face_iou > 90.0: + if face_iou > Config.bbox_matching_iou * 100.0: found_face_count += 1 face_bbox_ious.append(face_iou) + face_segment_iou = compute_face_segment_iou(before_person, before_img, after_person, after_img) + if face_segment_iou is None: + print("Face segment iou is None") + print("Before image meta", before_meta) + print("Before person", before_person) + print("After image meta", after_meta) + print("After person", after_person) + exit() + face_segment_ious.append(face_segment_iou * 100.0) is_emotion_matching = before_person["dominant_emotion"] == after_person["dominant_emotion"] if is_emotion_matching: same_emotion_count += 1 @@ -420,7 +572,7 @@ class Comparator: face_keypoint_position_similarities.extend(face_point_position_similarities) for before_object in before_meta["objects"]: - result = _find_best_matching_object(before_object, after_meta["objects"], 0.90) + result = _find_best_matching_object(before_object, after_meta["objects"], Config.bbox_matching_iou) if result is None: continue after_object, bbox_iou, segment_iou = result @@ -438,6 +590,7 @@ class Comparator: "person_keypoint_accuracies": person_keypoint_accuracies, "person_keypoint_position_similarities": person_keypoint_position_similarities, "found_face_count": found_face_count, + "face_segment_ious": face_segment_ious, "face_bbox_ious": face_bbox_ious, "same_emotion_count": same_emotion_count, "emotion_vector_similarities": emotion_vector_similarities, diff --git a/project/meta_data/face_iou_computer.py b/project/meta_data/face_iou_computer.py new file mode 100644 index 0000000..4147d90 --- /dev/null +++ b/project/meta_data/face_iou_computer.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python3 +import argparse +import base64 +import json +from pathlib import Path +from typing import Optional, Tuple, Dict, Any, List + +import cv2 +import numpy as np + + +# ------------------------- Decoding & placement ------------------------- + +def decode_base64_png_to_mask(b64_png: Optional[str]) -> Optional[np.ndarray]: + """ + Decode base64-encoded PNG into a boolean mask (HxW), where any non-zero pixel is True. + Returns None if input is missing or invalid. + """ + if not b64_png or not isinstance(b64_png, str): + return None + if b64_png.startswith("data:"): # allow data URLs + parts = b64_png.split(",", 1) + b64_png = parts[1] if len(parts) == 2 else b64_png + try: + buf = base64.b64decode(b64_png, validate=False) + except Exception: + return None + arr = np.frombuffer(buf, dtype=np.uint8) + img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED) + if img is None: + return None + if img.ndim == 3: + img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + return img > 0 + + +def place_mask_on_full_image( + mask: np.ndarray, + bbox: Tuple[int, int, int, int], + image_hw: Tuple[int, int], +) -> Optional[np.ndarray]: + """ + Place a bbox-local mask into a full-image boolean canvas using bbox coords. + - mask: HxW bool (decoded from base64) + - bbox: [x0,y0,x1,y1] + - image_hw: (H, W) of the full image + + Returns full-image boolean mask (H,W) or None if nothing can be placed. + Handles: + * resizing mask to bbox size with NEAREST + * clipping bbox to image bounds (and cropping mask accordingly) + """ + H, W = image_hw + x0, y0, x1, y1 = map(int, bbox) + if x1 < x0: + x0, x1 = x1, x0 + if y1 < y0: + y0, y1 = y1, y0 + + # Entirely outside? + if x1 <= 0 or y1 <= 0 or x0 >= W or y0 >= H: + return None + + bw = max(0, x1 - x0) + bh = max(0, y1 - y0) + if bw == 0 or bh == 0: + return None + + # Resize local mask to bbox size if needed + mh, mw = mask.shape[:2] + if (mw, mh) != (bw, bh): + mask = cv2.resize(mask.astype(np.uint8), (bw, bh), interpolation=cv2.INTER_NEAREST).astype(bool) + + # Clip bbox to image + x0c = max(0, min(x0, W)) + y0c = max(0, min(y0, H)) + x1c = max(0, min(x1, W)) + y1c = max(0, min(y1, H)) + if x1c <= x0c or y1c <= y0c: + return None + + # Calculate crop inside mask corresponding to the clipped bbox + dx_left = x0c - x0 + dy_top = y0c - y0 + dx_right = (x1 - x0) - (x1c - x0c) - dx_left + dy_bottom = (y1 - y0) - (y1c - y0c) - dy_top + + y_start = int(max(0, dy_top)) + x_start = int(max(0, dx_left)) + y_end = int(mask.shape[0] - max(0, dy_bottom)) + x_end = int(mask.shape[1] - max(0, dx_right)) + if y_end <= y_start or x_end <= x_start: + return None + + submask = mask[y_start:y_end, x_start:x_end] + canvas = np.zeros((H, W), dtype=bool) + canvas[y0c:y1c, x0c:x1c] = submask + return canvas + + +def load_person_full_masks_from_json(json_path: Path) -> Tuple[List[np.ndarray], Dict[str, Any]]: + """ + Loads image + persons from JSON and returns a list of full-image boolean masks (one per person). + JSON format: + { + "image": "filename.jpg", + "persons": [ + {"face_bbox": [x0,y0,x1,y1], "face_segment": ""}, + ... + ] + } + Falls back to single "person" if "persons" missing. + + Returns (list_of_masks, info_dict) + """ + info = {"json": str(json_path), "image_path": None, "status": "ok"} + try: + with json_path.open("r", encoding="utf-8") as f: + data = json.load(f) + except Exception: + info["status"] = "json_load_failed" + return [], info + + img_name = data.get("image") + if not img_name: + info["status"] = "image_field_missing" + return [], info + + img_path = json_path.parent / img_name + info["image_path"] = str(img_path) + img = cv2.imread(str(img_path), cv2.IMREAD_UNCHANGED) + if img is None: + info["status"] = "image_load_failed" + return [], info + H, W = img.shape[:2] + + persons = data.get("persons") + if persons is None: + # fallback to single "person" + p = data.get("person") + persons = [p] if isinstance(p, dict) else [] + + masks: List[np.ndarray] = [] + for p in persons: + if not isinstance(p, dict): + continue + b64 = p.get("face_segment") + bbox = p.get("face_bbox") + if not b64 or bbox is None or not (isinstance(bbox, (list, tuple)) and len(bbox) == 4): + continue + local = decode_base64_png_to_mask(b64) + if local is None: + continue + full = place_mask_on_full_image(local, tuple(map(int, bbox)), (H, W)) + if full is None: + continue + masks.append(full) + + return masks, info + + +# ------------------------- IoU & matching ------------------------- + +def iou_same_shape(a: np.ndarray, b: np.ndarray) -> float: + inter = np.logical_and(a, b).sum(dtype=np.int64) + uni = np.logical_or(a, b).sum(dtype=np.int64) + if uni == 0: + return 1.0 # both empty + return float(inter) / float(uni) + + +def resize_masks_to_shape(masks: List[np.ndarray], shape_hw: Tuple[int, int]) -> List[np.ndarray]: + if not masks: + return [] + H, W = shape_hw + out = [] + for m in masks: + if m.shape != (H, W): + m2 = cv2.resize(m.astype(np.uint8), (W, H), interpolation=cv2.INTER_NEAREST).astype(bool) + out.append(m2) + else: + out.append(m) + return out + + +def greedy_match_by_iou(A: List[np.ndarray], B: List[np.ndarray]) -> List[Tuple[int, int, float]]: + """ + One-to-one greedy matching maximizing IoU. + Returns list of tuples (i_in_A, j_in_B, iou_value). + Matches even if IoU == 0 (so present-only mean includes zero-overlap pairs). + """ + if not A or not B: + return [] + + # Build IoU matrix + H, W = A[0].shape + # Ensure B masks have same shape + B = resize_masks_to_shape(B, (H, W)) + + nA, nB = len(A), len(B) + M = np.zeros((nA, nB), dtype=np.float32) + for i in range(nA): + for j in range(nB): + M[i, j] = iou_same_shape(A[i], B[j]) + + matches: List[Tuple[int, int, float]] = [] + usedA = set() + usedB = set() + + while True: + # find global max among unused rows/cols + best = -1.0 + best_i = best_j = -1 + for i in range(nA): + if i in usedA: + continue + for j in range(nB): + if j in usedB: + continue + val = float(M[i, j]) + if val > best: + best = val + best_i, best_j = i, j + if best_i < 0: + break + matches.append((best_i, best_j, best)) + usedA.add(best_i) + usedB.add(best_j) + if len(usedA) == nA or len(usedB) == nB: + break + + return matches + + +# ------------------------- Main pipeline ------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Compute mean IoU of face segments (full-image) between two folders of JSON files with multiple persons." + ) + parser.add_argument("originals", type=Path, help="Folder with original JSON files and images") + parser.add_argument("modified", type=Path, help="Folder with modified JSON files and images") + parser.add_argument("--ext", default=".json", help="JSON extension (default: .json)") + args = parser.parse_args() + + orig_dir: Path = args.originals + mod_dir: Path = args.modified + ext = args.ext if args.ext.startswith(".") else "." + args.ext + + if not orig_dir.is_dir() or not mod_dir.is_dir(): + raise SystemExit("Both inputs must be directories.") + + orig_files = {p.name: p for p in orig_dir.glob(f"*{ext}") if p.is_file()} + mod_files = {p.name: p for p in mod_dir.glob(f"*{ext}") if p.is_file()} + names = sorted(set(orig_files).intersection(mod_files)) + if not names: + raise SystemExit("No matching JSON filenames found between the two folders.") + + # Aggregates + ious_all: List[float] = [] # includes zeros for unmatched persons + ious_present: List[float] = [] # only matched pairs (both present) + total_A = total_B = 0 + total_matched = total_unmatched_A = total_unmatched_B = 0 + + for name in names: + A_masks, infoA = load_person_full_masks_from_json(orig_files[name]) + B_masks, infoB = load_person_full_masks_from_json(mod_files[name]) + if infoA["status"] != "ok" or infoB["status"] != "ok": + print(infoA) + print(infoB) + exit() + + total_A += len(A_masks) + total_B += len(B_masks) + + + #TODO hier weiter lesen -------------------<<<<<<<<<<<<<<<<<<<<<<<<<<< + + + if not A_masks and not B_masks: + # nothing in either => count as 0 in 'all', skip present-only + continue + + # If both sides have masks but different full-image shapes (shouldn't happen per file), + # we normalize B to A's shape inside the matcher; track if that occurred. + # (Detect by checking any B mask shape vs any A mask shape.) + if A_masks and B_masks and A_masks[0].shape != B_masks[0].shape: + print("Full images have not same shape") + exit() + + matches = greedy_match_by_iou(A_masks, B_masks) + total_matched += len(matches) + + # Present-only IoUs (matched pairs) + for _, _, v in matches: + ious_present.append(float(v)) + ious_all.append(float(v)) + + # Unmatched persons contribute IoU = 0 to 'all' + unmatched_A = len(A_masks) - len(matches) + unmatched_B = len(B_masks) - len(matches) + total_unmatched_A += unmatched_A + total_unmatched_B += unmatched_B + ious_all.extend([0.0] * (unmatched_A + unmatched_B)) + + mean_all = float(np.mean(ious_all)) if ious_all else float("nan") + mean_present = float(np.mean(ious_present)) if ious_present else float("nan") + + print(f"Files compared: {len(names)}") + print(f" persons (original): {total_A}") + print(f" persons (modified): {total_B}") + print(f" matched pairs: {total_matched}") + print(f" unmatched original: {total_unmatched_A}") + print(f" unmatched modified: {total_unmatched_B}") + print() + print(f"Mean IoU (present-only): {mean_present:.6f}") + print(f"Mean IoU (all persons; unmatched ⇒ 0): {mean_all:.6f}") + + +if __name__ == "__main__": + main() diff --git a/project/models/epic/image_cache/face.jpg b/project/models/epic/image_cache/face.jpg deleted file mode 100644 index 74490c8..0000000 Binary files a/project/models/epic/image_cache/face.jpg and /dev/null differ diff --git a/project/models/epic/image_cache/obfuscated_face.jpg b/project/models/epic/image_cache/obfuscated_face.jpg deleted file mode 100644 index bb1a4f9..0000000 Binary files a/project/models/epic/image_cache/obfuscated_face.jpg and /dev/null differ diff --git a/project/models/ganonymization/image_cache/face.jpg b/project/models/ganonymization/image_cache/face.jpg deleted file mode 100644 index 5e6691a..0000000 Binary files a/project/models/ganonymization/image_cache/face.jpg and /dev/null differ diff --git a/project/models/ganonymization/image_cache/obfuscated_face.jpg b/project/models/ganonymization/image_cache/obfuscated_face.jpg deleted file mode 100644 index 3bf5eb9..0000000 Binary files a/project/models/ganonymization/image_cache/obfuscated_face.jpg and /dev/null differ diff --git a/project/obfuscation/style.py b/project/obfuscation/style.py index 0b234dc..da9b62e 100644 --- a/project/obfuscation/style.py +++ b/project/obfuscation/style.py @@ -13,11 +13,11 @@ class Style(ObfuscationTechnique): Replace face with generated face """ def __init__(self): - # print("Style not activated") - print("Style 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() + print("Style not activated") + # print("Style 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, face_mask) -> np.ndarray: diff --git a/project/obfuscation/swap.py b/project/obfuscation/swap.py index 601d8c3..1c28ad6 100644 --- a/project/obfuscation/swap.py +++ b/project/obfuscation/swap.py @@ -12,11 +12,11 @@ class Swap(ObfuscationTechnique): Replace face with generated face """ def __init__(self): - # print("epic not activated") - print("epic activated") - 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 activated") + # print("epic activated") + # 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, face_mask) -> np.ndarray: diff --git a/project/obfuscation/synthetic.py b/project/obfuscation/synthetic.py index fdca758..ebce115 100644 --- a/project/obfuscation/synthetic.py +++ b/project/obfuscation/synthetic.py @@ -13,11 +13,11 @@ class Synthetic(ObfuscationTechnique): """ def __init__(self): - # print("synthetic not activated") - print("synthetic activated") - 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() + print("synthetic not activated") + # print("synthetic activated") + # 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, face_mask) -> np.ndarray: