import json import os from deepface import DeepFace import numpy as np from shapely.geometry import Polygon, box from shapely.geometry.polygon import orient from shapely.validation import make_valid import math 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 meta = None with open(path_to_meta, 'r') as f: meta = json.load(f) path_to_img = path_to_meta.replace(".json", file_type_postfix) img = cv2.imread(path_to_img) return img, meta def _safe_polygon(coords) -> Polygon: """ • entfernt Duplikate • erzwingt mind. 3 eindeutige Punkte • schließt Ring bei Bedarf Gibt ein *leeres* Polygon zurück, wenn nicht möglich. """ arr = np.asarray(coords, dtype=np.float32) if arr.size == 0: return Polygon() # empty arr = np.unique(arr, axis=0) # doppelte Punkte raus if arr.shape[0] < 3: return Polygon() # empty # Ring schließen, falls offenes Ende if not np.allclose(arr[0], arr[-1]): arr = np.vstack([arr, arr[0]]) return Polygon(arr) def _to_valid_poly(coords) -> Polygon: poly = _safe_polygon(coords) if poly.is_empty: # leer = ok, wird area=0 return poly poly = orient(poly, sign=1.0) # äussere CCW if not poly.is_valid: if make_valid is not None: # Shapely ≥ 2 poly = make_valid(poly) else: # älter: buffer(0)-Trick poly = poly.buffer(0) return poly def _bbox_iou(a, b) -> float: pa = box(*a) # (minx, miny, maxx, maxy) pb = box(*b) iou = 0.0 try: inter = pa.intersection(pb).area union = pa.union(pb).area iou = inter / union except Exception as e: print("Exception during bbox_iou", e) iou = 0.0 return iou def _poly_iou(poly_a, poly_b) -> float: pa = _to_valid_poly(poly_a) pb = _to_valid_poly(poly_b) iou = 0.0 try: inter = pa.intersection(pb).area union = pa.union(pb).area iou = inter / union except Exception as e: print("Exception during poly_iou", e) print("poly_a", poly_a) print("poly_b", poly_b) print(pa) print(pb) exit() #TODO Möglicherweise entfernen iou = 0 return iou def _find_best_matching_object(obj, other_objects, min_iou): 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"]) if bbox_iou > best_bbox_iou: best = [other, bbox_iou, seg_iou] best_bbox_iou = bbox_iou 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): w = bbox[2] - bbox[0] h = bbox[3] - bbox[1] for kp in kps: #Filter by empty if (kp[0] == bbox[0]) and (kp[1] == bbox[1]): kp[0] = 0 kp[1] = 0 else: #Keypoints are in image space, convert to bbox space kp[0] = (kp[0] - bbox[0]) kp[1] = (kp[1] - bbox[1]) #Normalize by bbox size kp[0] /= w kp[1] /= h def _adapt_face_keypoints(kps, bbox): w = bbox[2] - bbox[0] h = bbox[3] - bbox[1] adapted_kps = [] for kp in kps: #No filtering by 0,0; keypoints always available, just normalization new_kp = [] #Keypoints are in image space, convert to bbox space new_kp.append(kp[0] - bbox[0]) new_kp.append(kp[1] - bbox[1]) #Normalize by bbox size new_kp[0] = new_kp[0] / w new_kp[1] = new_kp[1] / h adapted_kps.append(new_kp) return adapted_kps def _compare_keypoints(kps_a, kps_b): #First check how many keypoints could be found in comparison same_estimation = 0 for idx, kp_a in enumerate(kps_a): kp_b = kps_b[idx] if ((kp_a[0] == 0) and (kp_a[1] == 0)) and ((kp_b[0] == 0) and (kp_b[1] == 0)): same_estimation += 1 elif ((kp_a[0] > 0) or (kp_a[1] > 0)) and ((kp_b[0] > 0) or (kp_b[1] > 0)): same_estimation += 1 person_keypoint_accuracy = (same_estimation / len(kps_a)) * 100.0 #Then check the accuracy and deviation of the keypoints point_position_similarities = [] for kp_a, kp_b in zip(kps_a, kps_b): if (kp_a[0] == 0) and (kp_a[1] == 0): continue if (kp_b[0] == 0) and (kp_b[1] == 0): continue similarity = (1.0 - (np.linalg.norm(np.array(kp_a) - np.array(kp_b)) / math.sqrt(2))) * 100.0 point_position_similarities.append(similarity) return person_keypoint_accuracy, point_position_similarities def _compute_body_keypoint_similarity(kps_a, kps_b, bbox_a, bbox_b): if bbox_b is None or len(bbox_b) == 0 or kps_b is None or len(kps_b) == 0: return 0.0, [] #Is shape the same? if len(kps_a) != len(kps_b): raise ValueError(f"Key-point shapes differ: {kps_a} vs {kps_b}") #Filter keypoints with (x,y) == (0,0) coordinates, based on Bounding box origin //keypoints were shifted by bbox offset in advance, this causes not found keypoints (0,0) to be exactly at bbox origin _adapt_body_keypoints(kps_a, bbox_a) _adapt_body_keypoints(kps_b, bbox_b) person_keypoint_accuracy, point_position_similarities = _compare_keypoints(kps_a, kps_b) return person_keypoint_accuracy, point_position_similarities def _compute_face_keypoint_similarity(kps_a, kps_b, bbox_a, bbox_b): if bbox_b is None or len(bbox_b) == 0 or kps_b is None or len(kps_b) == 0: return 0.0, [] #Is shape the same? if len(kps_a) != len(kps_b): raise ValueError(f"Key-point shapes differ: {kps_a} vs {kps_b}") kps_a = _adapt_face_keypoints(kps_a, bbox_a) kps_b = _adapt_face_keypoints(kps_b, bbox_b) person_keypoint_accuracy, point_position_similarities = _compare_keypoints(kps_a, kps_b) return person_keypoint_accuracy, point_position_similarities def _vec_from_dict(d) -> np.ndarray: EMOTIONS = ("angry", "disgust", "fear", "happy", "sad", "surprise", "neutral") return np.array([d.get(k, 0.0) for k in EMOTIONS]) def _emotion_cosine_similarity(emotions1, emotions2): v1 = _vec_from_dict(emotions1) v2 = _vec_from_dict(emotions2) cos_distance = None try: cos_distance = float(cosine(v1, v2)) except: print("PROBLEM WHILE COMPUTING EMOTION COSINE SIMILARITY") print("EMOTION VECTORS 1:", emotions1) print("EMOTION VECTORS 2:", emotions2) exit() return (1.0 - cos_distance) * 100.0 def _match_persons(face_img1, face_img2): result = DeepFace.verify(face_img1, face_img2, model_name="Facenet512", distance_metric="cosine", detector_backend="skip", enforce_detection=False) verified = result["verified"] distance = result["distance"] #FaceNet-512d -> highes accuracy in paper return verified, distance * 100.0 def init_folder_insights_dict(): folder_insights = { "found_matching_persons_count": 0, "before_person_count": 0, "person_bbox_ious": [], "person_segment_ious": [], "person_keypoint_accuracies": [], "person_keypoint_position_similarities": [], "found_face_count": 0, "face_segment_ious": [], "face_bbox_ious": [], "same_emotion_count": 0, "emotion_vector_similarities": [], "same_person_counter": 0, "identity_distances": [], "face_keypoint_position_similarities": [], "found_matching_objects_count": 0, "before_object_count": 0, "object_bbox_ious": [], "object_segment_ious": [], "found_matching_classes_count": 0, ###FACE-OBJECT-ANALYSIS### "object_count_while_overlap_with_face": 0, "found_matching_objects_count_while_overlap_with_face": 0, "object_count_without_overlap_with_face": 0, "found_matching_objects_count_without_overlap_with_face": 0, ### } return folder_insights def write_image_results_to_folder_result_dict(image_result_dict, folder_result_dict): folder_result_dict["found_matching_persons_count"] += image_result_dict["found_matching_persons_count"] folder_result_dict["before_person_count"] += image_result_dict["before_person_count"] folder_result_dict["person_bbox_ious"].extend(image_result_dict["person_bbox_ious"]) folder_result_dict["person_segment_ious"].extend(image_result_dict["person_segment_ious"]) 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"]) folder_result_dict["same_person_counter"] += image_result_dict["same_person_counter"] folder_result_dict["identity_distances"].extend(image_result_dict["identity_distances"]) folder_result_dict["face_keypoint_position_similarities"].extend(image_result_dict["face_keypoint_position_similarities"]) folder_result_dict["found_matching_objects_count"] += image_result_dict["found_matching_objects_count"] folder_result_dict["before_object_count"] += image_result_dict["before_object_count"] folder_result_dict["object_bbox_ious"].extend(image_result_dict["object_bbox_ious"]) folder_result_dict["object_segment_ious"].extend(image_result_dict["object_segment_ious"]) folder_result_dict["found_matching_classes_count"] += image_result_dict["found_matching_classes_count"] ###FACE-OBJECT-ANALYSIS### folder_result_dict["object_count_while_overlap_with_face"] += image_result_dict["object_count_while_overlap_with_face"] folder_result_dict["found_matching_objects_count_while_overlap_with_face"] += image_result_dict["found_matching_objects_count_while_overlap_with_face"] folder_result_dict["object_count_without_overlap_with_face"] += image_result_dict["object_count_without_overlap_with_face"] folder_result_dict["found_matching_objects_count_without_overlap_with_face"] += image_result_dict["found_matching_objects_count_without_overlap_with_face"] ### 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, "\mathrm{mIoU}_\mathrm{seg}": np.mean(folder_result_dict["person_segment_ious"]) if len(folder_result_dict["person_segment_ious"]) > 0 else 0.0 }, "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{deID}": (1.0 - (folder_result_dict["same_person_counter"] / folder_result_dict["before_person_count"])) * 100.0 if folder_result_dict["found_face_count"] > 0 else 100.0 }, "object": { "\mathrm{Acc}_\mathrm{det}": (folder_result_dict["found_matching_objects_count"] / folder_result_dict["before_object_count"]) * 100.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 }, ###FACE-OBJECT-INSIGHTS### "face-object-insights":{ "object_count_while_overlap_with_face": folder_result_dict["object_count_while_overlap_with_face"], "found_matching_objects_count_while_overlap_with_face": folder_result_dict["found_matching_objects_count_while_overlap_with_face"], "object_count_without_overlap_with_face": folder_result_dict["object_count_without_overlap_with_face"], "found_matching_objects_count_without_overlap_with_face": folder_result_dict["found_matching_objects_count_without_overlap_with_face"], "\mathrm{Acc}_{\mathrm{det}}^{\mathrm{with\,overlap}}": (folder_result_dict["found_matching_objects_count_while_overlap_with_face"] / folder_result_dict["object_count_while_overlap_with_face"]), "\mathrm{Acc}_{\mathrm{det}}^{\mathrm{without\,overlap}}": (folder_result_dict["found_matching_objects_count_without_overlap_with_face"] / folder_result_dict["object_count_without_overlap_with_face"]) }, ### "meta": { "person": { "found_matching_persons_count": folder_result_dict["found_matching_persons_count"], "before_person_count": folder_result_dict["before_person_count"], "len_person_bbox_ious": len(folder_result_dict["person_bbox_ious"]), "len_person_segment_ious": len(folder_result_dict["person_segment_ious"]), "len_person_keypoint_accuracies": len(folder_result_dict["person_keypoint_accuracies"]), "len_person_keypoint_position_similarities": len(folder_result_dict["person_keypoint_position_similarities"]) }, "face": { "face_found_count": folder_result_dict["found_face_count"], "len_face_bbox_ious": len(folder_result_dict["face_bbox_ious"]), "same_emotion_count": folder_result_dict["same_emotion_count"], "len_emotion_vector_similarities": len(folder_result_dict["emotion_vector_similarities"]), "same_person_counter": folder_result_dict["same_person_counter"], "len_identity_distances": len(folder_result_dict["identity_distances"]), "len_face_keypoint_position_similarities": len(folder_result_dict["face_keypoint_position_similarities"]) }, "object": { "found_matching_objects_count": folder_result_dict["found_matching_objects_count"], "before_object_count": folder_result_dict["before_object_count"], "len_object_bbox_ious": len(folder_result_dict["object_bbox_ious"]), "len_object_segment_ious": len(folder_result_dict["object_segment_ious"]), "found_matching_classes_count": folder_result_dict["found_matching_classes_count"] } }, "other": { "\mathrm{Acc}_\mathrm{cls}": (folder_result_dict["found_matching_classes_count"] / folder_result_dict["before_object_count"]) * 100.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{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, "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 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 dataset_name = os.path.basename(before_directory) if dataset_name not in obfuscated_directory: raise ValueError("Datasets are not the same", "before_directory", before_directory, "obfuscated_directory", obfuscated_directory) #Validate there are the same number of images in both directories before_image_count = len(os.listdir(before_directory)) obfuscated_image_count = len(os.listdir(obfuscated_directory)) if before_image_count != obfuscated_image_count: raise ValueError("Not same amount of files in both directories", "before_directory", before_directory, "obfuscated_directory", obfuscated_directory) folder_insights = init_folder_insights_dict() #Iterate through all images in before directory and find the corresponding image in the obfuscated directory for before_image_name in tqdm(os.listdir(before_directory)): if before_image_name.endswith(".jpg"): #Based on the images name, find the corresponding meta file (.json) in both directories before_meta_path = os.path.join(before_directory, before_image_name.replace(".jpg", ".json")) after_meta_path = os.path.join(obfuscated_directory, before_image_name.replace(".jpg", ".json")) img_insights = self._get_insights_from_comparison(before_meta_path, after_meta_path) #Aggregate meta_data into folder_result_dict write_image_results_to_folder_result_dict(img_insights, folder_insights) scores = compute_scores(folder_insights) return scores #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, ".jpg") after_img, after_meta = _load_meta_and_images(path_to_meta_after, ".png") #Person scores before_person_count = len(before_meta["persons"]) found_matching_persons_count = 0 person_bbox_ious = [] person_segment_ious = [] person_keypoint_accuracies = [] person_keypoint_position_similarities = [] found_face_count = 0 face_bbox_ious = [] face_segment_ious = [] same_emotion_count = 0 emotion_vector_similarities = [] same_person_counter = 0 identity_distances = [] face_keypoint_position_similarities = [] #Object scores before_object_count = len(before_meta["objects"]) found_matching_objects_count = 0 found_matching_classes_count = 0 object_bbox_ious = [] object_segment_ious = [] ###FACE-OBJECT-ANALYSIS### object_count_while_overlap_with_face = 0 found_matching_objects_count_while_overlap_with_face = 0 object_count_without_overlap_with_face = 0 found_matching_objects_count_without_overlap_with_face = 0 ### for before_person in before_meta["persons"]: 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 found_matching_persons_count += 1 person_bbox_ious.append(bbox_iou) person_segment_ious.append(segment_iou) person_keypoint_accuracy, point_position_similarities = _compute_body_keypoint_similarity(before_person["body_keypoints"], after_person["body_keypoints"], before_person["bbox"], after_person["bbox"]) person_keypoint_accuracies.append(person_keypoint_accuracy) person_keypoint_position_similarities.extend(point_position_similarities) #Check for validity of before data if before_person["face_bbox"] is None: 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 > 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 emotion_vector_similarities.append(_emotion_cosine_similarity(before_person["emotion_vector"], after_person["emotion_vector"])) _, face_point_position_similarities = _compute_face_keypoint_similarity(before_person["face_keypoints"], after_person["face_keypoints"], before_person["face_bbox"], after_person["face_bbox"]) 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"], Config.bbox_matching_iou) ###FACE-OBJECT-ANALYSIS### if _bbox_iou(before_person["face_bbox"], before_object["bbox"]) > 0: object_count_while_overlap_with_face += 1 if result is not None: found_matching_objects_count_while_overlap_with_face += 1 else: object_count_without_overlap_with_face += 1 if result is not None: found_matching_objects_count_without_overlap_with_face += 1 ### if result is None: continue after_object, bbox_iou, segment_iou = result found_matching_objects_count += 1 object_bbox_ious.append(bbox_iou) object_segment_ious.append(segment_iou) if before_object["label"] == after_object["label"]: found_matching_classes_count += 1 #For Each Before-Person; Check identifitcation for before_person in before_meta["persons"]: before_face_crop = before_img[before_person["face_bbox"][1]:before_person["face_bbox"][3], before_person["face_bbox"][0]:before_person["face_bbox"][2]] after_face_crop = after_img[before_person["face_bbox"][1]:before_person["face_bbox"][3], before_person["face_bbox"][0]:before_person["face_bbox"][2]] face_verified, identity_distance = _match_persons(before_face_crop, after_face_crop) if face_verified: same_person_counter += 1 identity_distances.append(identity_distance) image_insights = { "found_matching_persons_count": found_matching_persons_count, "before_person_count": before_person_count, "person_bbox_ious": person_bbox_ious, "person_segment_ious": person_segment_ious, "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, "same_person_counter": same_person_counter, "identity_distances": identity_distances, "face_keypoint_position_similarities": face_keypoint_position_similarities, "found_matching_objects_count": found_matching_objects_count, "before_object_count": before_object_count, "object_bbox_ious": object_bbox_ious, "object_segment_ious": object_segment_ious, "found_matching_classes_count": found_matching_classes_count, ###FACE-OBJECT-ANALYSIS### "object_count_while_overlap_with_face": object_count_while_overlap_with_face, "found_matching_objects_count_while_overlap_with_face": found_matching_objects_count_while_overlap_with_face, "object_count_without_overlap_with_face": object_count_without_overlap_with_face, "found_matching_objects_count_without_overlap_with_face": found_matching_objects_count_without_overlap_with_face ### } return image_insights