diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index adcd605..156e024 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 ac6d922..4e4c6a3 100644 --- a/project/config.py +++ b/project/config.py @@ -13,6 +13,8 @@ class Config: pose_model_type="yolo11m-pose.pt" face_model_type="yunet" + evaluation_results_directory = "evaluation_results/" + verbose=True tasks = {"preprocessing": True, # optional if already done diff --git a/project/main.py b/project/main.py index 9f2ceeb..4d6c88a 100644 --- a/project/main.py +++ b/project/main.py @@ -3,6 +3,7 @@ import os from config import Config from data_loader import DatasetLoader from image_preprocessor import DataPreprocessor +from meta_data.comparator import Comparator from meta_data.meta_data_extractor import MetaExtractor from meta_data.post_extraction import PostExtractor from obfuscation.obfuscation_engine import ObfuscationEngine @@ -78,26 +79,23 @@ def main(): post_extractor.extract() #4: Analyze impact of obfuscation - # Comparator: TODO: Die daten müssen definitiv gleich sortiert werden und geprüft werden, ob der basename identisch ist - - #TODO: Compare before and after metadata for each dataset, for each technique; - #TODO: ES FEHLT NOCH EIN MODEL FÜR GESICHTER MATCHING; WIe gut ist verschleierung eigentlich? - #TODO: Generate some "evaluation_output" for dataset and technique - - #Für jedes Datenset, für jede Technik messen, welchen einfluss die anonymisierung hat - #Person - #Person Accuracy: Wird Person gefunden? Bbox IoU > 0.5 - #Person Segment Similarity: Wie ähnlich sind die Segmentierungen? Polygon Similarity - - #Face Accuracy: Wird Gesicht gefunden? Bbox IoU > 0.5 - #Obfuscation Success: Wurde Person nicht wiedererkannt? Face Matching - #Face Mesh Similarity: Wie ähnlich sind die Meshpunkte? Facial Keypoints Similarity - #Face Emotion Accuracy: Wird Emotion erkannt? Top1 Emotion Matching - #Face Emotion Vector Similarity: Wie ähnlich sind die Emotionen? Vector Similarity - - #Global (Für jedes weitere Objekt im Ursprungsbild) - #Object Accuracy: Wird das Objekt erkannt? Bbox IoU > 0.5 - #Object Segment Similarity: Wie ähnlich sind die Segmentierungen? Polygon Similarity + #For each before folder, compare with after folder (after each technique) + if Config.tasks["analysis"]: + results = {} + comparator = Comparator() + for before_dataset_name in os.listdir(Config.filtered_output_directory): + before_dataset_path = os.path.join(Config.filtered_output_directory, before_dataset_name) + for after_dataset_name in os.listdir(Config.obfuscated_output_directory): + if before_dataset_name == after_dataset_name: + after_dataset_path = os.path.join(Config.obfuscated_output_directory, after_dataset_name) + #For each technique, compare the datasets + for technique_name in os.listdir(after_dataset_path): + technique_path = os.path.join(after_dataset_path, technique_name) + technique_result_dict = comparator.compare_with_before_and_after(before_dataset_path, technique_path) + results[f"{before_dataset_name}_{technique_name}"] = technique_result_dict + #Save results in evaluation_results_directory as json + with open(os.path.join(Config.evaluation_results_directory, "results.json"), "w") as f: + json.dump(results, f, indent=3) if __name__ == '__main__': diff --git a/project/meta_data/__pycache__/comparator.cpython-310.pyc b/project/meta_data/__pycache__/comparator.cpython-310.pyc new file mode 100644 index 0000000..a551e92 Binary files /dev/null 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 3120a09..f7411e3 100644 --- a/project/meta_data/comparator.py +++ b/project/meta_data/comparator.py @@ -1,5 +1,7 @@ import json -from deepface import Deepface +import os + +from deepface import DeepFace import numpy as np from shapely.geometry import Polygon, box from scipy.spatial.distance import cosine @@ -18,8 +20,6 @@ def load_meta_and_images(path_to_meta: str): def _bbox_iou(a, b) -> float: pa = box(*a) # (minx, miny, maxx, maxy) - print(pa) - exit() pb = box(*b) inter = pa.intersection(pb).area union = pa.union(pb).area @@ -69,9 +69,60 @@ def _match_persons(face_img1, face_img2): return verified, distance class Comparator: - #Compare two images - def compare_metadata(self, path_to_meta_before: str, path_to_meta_after: str): + 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) @@ -80,6 +131,7 @@ class Comparator: found_matching_persons_count = 0 person_bbox_ious = [] person_segment_ious = [] + found_face_count = 0 face_bbox_ious = [] same_emotion_count = 0 @@ -102,23 +154,25 @@ class Comparator: found_matching_persons_count += 1 person_bbox_ious.append(bbox_iou) person_segment_ious.append(segment_iou) - if after_person["face"] is not None: - face_iou = _bbox_iou(before_person["face"]["bbox"], after_person["face"]["bbox"]) + #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["face"]["dominant_emotion"] == after_person["face"]["dominant_emotion"] + 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["face"]["emotion_vector"], after_person["face"]["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]] + 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: @@ -130,15 +184,42 @@ class Comparator: 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) - #TODO die eigentlich scores berechnen mit den aggregierten daten oben + 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_scores": { - + "person": { + "person_found_accuracy": person_found_accuracy, + "person_bbox_iou_avg": person_bbox_iou_avg, + "person_segment_iou_avg": person_segment_iou_avg, }, - "object_scores": { - + "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, } } - raise NotImplementedError + return result_score_dict \ No newline at end of file