225 lines
10 KiB
Python
225 lines
10 KiB
Python
import json
|
|
import os
|
|
|
|
from deepface import DeepFace
|
|
import numpy as np
|
|
from shapely.geometry import Polygon, box
|
|
from scipy.spatial.distance import cosine
|
|
import cv2
|
|
|
|
|
|
def load_meta_and_images(path_to_meta: str):
|
|
#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")
|
|
img = cv2.imread(path_to_img)
|
|
return img, meta
|
|
|
|
|
|
def _bbox_iou(a, b) -> float:
|
|
pa = box(*a) # (minx, miny, maxx, maxy)
|
|
pb = box(*b)
|
|
inter = pa.intersection(pb).area
|
|
union = pa.union(pb).area
|
|
return inter / union if union else 0.0
|
|
|
|
|
|
def _poly_iou(poly_a, poly_b) -> float:
|
|
pa, pb = Polygon(poly_a), Polygon(poly_b)
|
|
if (not pa.is_valid) or (not pb.is_valid):
|
|
return 0.0
|
|
inter = pa.intersection(pb).area
|
|
union = pa.union(pb).area
|
|
return inter / union if union else 0.0
|
|
|
|
|
|
#This function returns an object that matches the given object based on class and IoU
|
|
#Returns None or Found Object + Bbox- and Segment-IoU
|
|
def _find_best_matching_object(obj, other_objects, min_iou=0.5):
|
|
best_match = None
|
|
for other_obj in other_objects:
|
|
bbox_iou = _bbox_iou(obj["bbox"], other_obj["bbox"])
|
|
if bbox_iou > min_iou:
|
|
segment_iou = _poly_iou(obj["segment"], other_obj["segment"])
|
|
if best_match is None:
|
|
best_match = (other_obj, bbox_iou, segment_iou)
|
|
else:
|
|
best_bbox_iou_so_far = best_match[1]
|
|
if best_bbox_iou_so_far < bbox_iou:
|
|
best_match = (other_obj, bbox_iou, segment_iou)
|
|
return best_match
|
|
|
|
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], dtype=np.float32)
|
|
|
|
def _emotion_cosine_similarity(emotions1, emotions2):
|
|
v1 = _vec_from_dict(emotions1)
|
|
v2 = _vec_from_dict(emotions2)
|
|
if not np.any(v1) or not np.any(v2):
|
|
return 1.0 # undefined → maximal dist
|
|
return float(cosine(v1, v2))
|
|
|
|
def _match_persons(face_img1, face_img2):
|
|
result = Deepface.verify(face_img1, face_img2, distance_metric="cosine", detector_backend="skip", enforce_detection=False, )
|
|
verified = result["verified"]
|
|
distance = result["distance"] #Default model: VGG-Face; Cosine Similarity, with tuned threshold
|
|
return verified, distance
|
|
|
|
class Comparator:
|
|
def compare_with_before_and_after(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_result_dict = {
|
|
"person": {
|
|
"person_found_accuracy": 0.0,
|
|
"person_bbox_iou_avg": 0.0,
|
|
"person_segment_iou_avg": 0.0,
|
|
},
|
|
"face": {
|
|
"face_found_accuracy": 0.0,
|
|
"face_bbox_iou_avg": 0.0,
|
|
"top1_emotion_accuracy": 0.0,
|
|
"emotion_vector_similarity_avg": 0.0,
|
|
"obfuscation_accuracy": 0.0,
|
|
"face_distance_avg": 0.0,
|
|
},
|
|
"object": {
|
|
"object_found_accuracy": 0.0,
|
|
"object_bbox_iou_avg": 0.0,
|
|
"object_segment_iou_avg": 0.0,
|
|
"object_class_accuracy": 0.0,
|
|
}
|
|
}
|
|
|
|
|
|
#Iterate through all images in before directory and find the corresponding image in the obfuscated directory
|
|
for before_image_name in os.listdir(before_directory):
|
|
#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"))
|
|
|
|
meta_data = self._compare_metadata(before_meta_path, after_meta_path)
|
|
#Aggregate meta_data into folder_result_dict
|
|
for key, value in meta_data.items():
|
|
for sub_key, sub_value in value.items():
|
|
folder_result_dict[key][sub_key] += sub_value
|
|
#Divide by number of images to get averages
|
|
for key, value in folder_result_dict.items():
|
|
for sub_key, sub_value in value.items():
|
|
folder_result_dict[key][sub_key] /= before_image_count
|
|
|
|
return folder_result_dict
|
|
|
|
#Compare two images
|
|
def _compare_metadata(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)
|
|
|
|
#Person scores
|
|
before_person_count = len(before_meta["persons"])
|
|
found_matching_persons_count = 0
|
|
person_bbox_ious = []
|
|
person_segment_ious = []
|
|
|
|
found_face_count = 0
|
|
face_bbox_ious = []
|
|
same_emotion_count = 0
|
|
emotion_vector_similarities = []
|
|
same_person_counter = 0
|
|
face_distances = []
|
|
|
|
#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 = []
|
|
|
|
for before_person in before_meta["persons"]:
|
|
result = _find_best_matching_object(before_person, after_meta["persons"])
|
|
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)
|
|
#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"])
|
|
if face_iou > 0.5:
|
|
found_face_count += 1
|
|
face_bbox_ious.append(face_iou)
|
|
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"]))
|
|
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[after_person["face_bbox"][1]:after_person["face_bbox"][3], after_person["face_bbox"][0]:after_person["face_bbox"][2]]
|
|
face_verified, face_distance = _match_persons(before_face_crop, after_face_crop)
|
|
if face_verified:
|
|
same_person_counter += 1
|
|
face_distances.append(face_distance)
|
|
|
|
for before_object in before_meta["objects"]:
|
|
result = _find_best_matching_object(before_object, after_meta["objects"])
|
|
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
|
|
|
|
person_found_accuracy = (found_matching_persons_count / before_person_count) * 100.0
|
|
person_bbox_iou_avg = np.mean(person_bbox_ious)
|
|
person_segment_iou_avg = np.mean(person_segment_ious)
|
|
|
|
face_found_accuracy = (found_face_count / before_person_count) * 100.0
|
|
face_bbox_iou_avg = np.mean(face_bbox_ious)
|
|
#TODO: JEDEN score überprüfen die machen teilwesie GARKEINEN SINN!!!!
|
|
top1_emotion_accuracy = ((same_emotion_count / found_matching_persons_count) * 100.0) if (found_matching_persons_count > 0) else 0.0
|
|
emotion_vector_similarity_avg = np.mean(emotion_vector_similarities)
|
|
obfuscation_accuracy = ((1.0 - (same_person_counter / found_matching_persons_count)) * 100.0) if (found_matching_persons_count > 0) else 1.0
|
|
face_distance_avg = np.mean(face_distances)
|
|
|
|
object_found_accuracy = (found_matching_objects_count / before_object_count) * 100.0
|
|
object_bbox_iou_avg = np.mean(object_bbox_ious)
|
|
object_segment_iou_avg = np.mean(object_segment_ious)
|
|
object_class_accuracy = (found_matching_classes_count / before_object_count) * 100.0
|
|
|
|
result_score_dict = {
|
|
"person": {
|
|
"person_found_accuracy": person_found_accuracy,
|
|
"person_bbox_iou_avg": person_bbox_iou_avg,
|
|
"person_segment_iou_avg": person_segment_iou_avg,
|
|
},
|
|
"face": {
|
|
"face_found_accuracy": face_found_accuracy,
|
|
"face_bbox_iou_avg": face_bbox_iou_avg,
|
|
"top1_emotion_accuracy": top1_emotion_accuracy,
|
|
"emotion_vector_similarity_avg": emotion_vector_similarity_avg,
|
|
"obfuscation_accuracy": obfuscation_accuracy,
|
|
"face_distance_avg": face_distance_avg,
|
|
},
|
|
"object": {
|
|
"object_found_accuracy": object_found_accuracy,
|
|
"object_bbox_iou_avg": object_bbox_iou_avg,
|
|
"object_segment_iou_avg": object_segment_iou_avg,
|
|
"object_class_accuracy": object_class_accuracy,
|
|
}
|
|
}
|
|
return result_score_dict |