Anpassungen bei den metriken und bug gefunden (nächstes TODO)

This commit is contained in:
2025-05-20 20:56:34 +02:00
parent ec091c23e9
commit c49d808df7
5 changed files with 99 additions and 75 deletions
+11 -10
View File
@@ -64,16 +64,17 @@ def main():
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):
#if (technique_name == "aaa") and (before_dataset_name == "celeba"): #TODO ENTFERNEN!!!
#TODO aber auch die datensets die dazukamen filtern usw...
technique_path = os.path.join(after_dataset_path, technique_name)
print(f"Comparing {before_dataset_name} with {technique_name} obfuscation")
technique_result_dict = comparator.compare_with_before_and_after_folder(before_dataset_path, technique_path)
#Save results in evaluation_results_directory as json
current_technique_results_directory = os.path.join(Config.evaluation_results_directory, f"results_{before_dataset_name}_{technique_name}.json")
print(f"Saving results in {current_technique_results_directory}")
with open(current_technique_results_directory, "w") as f:
json.dump(technique_result_dict, f, indent=3)
if (technique_name == "aaa") and (before_dataset_name == "celeba"): #TODO ENTFERNEN!!!
#if (technique_name == "aaa") and (before_dataset_name == "zzz"): #TODO ENTFERNEN!!!
#TODO aber auch die datensets die dazukamen filtern usw... also in den ordnern
technique_path = os.path.join(after_dataset_path, technique_name)
print(f"Comparing {before_dataset_name} with {technique_name} obfuscation")
technique_result_dict = comparator.compare_with_before_and_after_folder(before_dataset_path, technique_path)
#Save results in evaluation_results_directory as json
current_technique_results_directory = os.path.join(Config.evaluation_results_directory, f"results_{before_dataset_name}_{technique_name}.json")
print(f"Saving results in {current_technique_results_directory}")
with open(current_technique_results_directory, "w") as f:
json.dump(technique_result_dict, f, indent=3)
if __name__ == '__main__':
+83 -61
View File
@@ -6,6 +6,7 @@ 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
@@ -83,49 +84,55 @@ def _adapt_body_keypoints(kps, bbox, img_w, img_h):
kp[0] = kp[0] / img_w
kp[1] = kp[1] / img_h
def _compare_body_keypoints(kps_a, kps_b):
def _adapt_face_keypoints(kps, img_w, img_h):
adapted_face_keypoints = []
for kp in kps:
#Normalize by image size (only for x, y)
adapted_face_keypoints.append((kp[0] / img_w, kp[1] / img_h))
return adapted_face_keypoints
def _compare_keypoints(kps_a, kps_b):
#First check how many keypoints could be found in comparison
amount_of_points_found_a = len([kp for kp in kps_a if (kp[0] != 0) and (kp[1] != 0)])
amount_of_points_found_b = len([kp for kp in kps_b if (kp[0] != 0) and (kp[1] != 0)])
found_deviation = abs(amount_of_points_found_a - amount_of_points_found_b)
n_point_deviation = abs(amount_of_points_found_a - amount_of_points_found_b) if amount_of_points_found_b > 0 else len(kps_a)
#Then check the accuracy and deviation of the keypoints
point_wise_deviations = []
both_exist_counter = 0
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
both_exist_counter += 1
deviation = np.linalg.norm(np.array(kp_a) - np.array(kp_b))
point_wise_deviations.append(deviation)
average_deviation = np.mean(point_wise_deviations)
#TODO: hier muss man nochmal prüfen, ob das alles ok so ist
#TODO: hier muss man noch mit der deviation alles berechnen
average_position_deviation = None
if len(point_wise_deviations) > 0:
average_position_deviation = np.mean(point_wise_deviations)
point_accuracy = (both_exist_counter / amount_of_points_found_a) * 100.0
return found_deviation, point_accuracy
return n_point_deviation / len(kps_a), average_position_deviation
def _compute_body_keypoint_deviation(kps_a, kps_b, bbox_a, bbox_b, img_w, img_h):
#TODO ES KANN SEIN DASS KEYPOINTS LEER SIND UND SOMIT SHAPE ANDERS
#Is shape the same?
if len(kps_a) != len(kps_b):
raise ValueError(f"Key-point shapes differ: {A.shape} vs {B.shape}")
raise ValueError(f"Key-point shapes differ: {kps_a.shape} vs {kps_b.shape}")
#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
print(kps_a)
print(kps_b)
_adapt_body_keypoints(kps_a, bbox_a, img_w, img_h)
_adapt_body_keypoints(kps_b, bbox_b, img_w, img_h)
print(kps_a)
print(kps_b)
amount_similarity, deviation = _compare_body_keypoints(kps_a, kps_b)
print(amount_similarity)
print(deviation)
exit()
n_point_deviation, avg_position_deviation = _compare_keypoints(kps_a, kps_b)
return n_point_deviation, avg_position_deviation
return amount_similarity, deviation
def _compute_face_keypoint_deviation(kps_a, kps_b, img_w, img_h):
#Is shape the same?
if len(kps_a) != len(kps_b):
raise ValueError(f"Key-point shapes differ: {kps_a.shape} vs {kps_b.shape}")
kps_a = _adapt_face_keypoints(kps_a, img_w, img_h)
kps_b = _adapt_face_keypoints(kps_b, img_w, img_h)
n_point_deviation, avg_position_deviation = _compare_keypoints(kps_a, kps_b)
return n_point_deviation, avg_position_deviation
def _vec_from_dict(d) -> np.ndarray:
EMOTIONS = ("angry", "disgust", "fear", "happy", "sad", "surprise", "neutral")
@@ -158,49 +165,62 @@ class Comparator:
#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)
# if before_image_count != obfuscated_image_count: #TODO Einkommentiern
#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,
"person_keypoint_similarity_avg": 0.0
"person_n_keypoint_similarity_avg": 0.0,
"person_keypoint_position_similarity_avg": 0.0
},
"face": {
"face_found_accuracy": 0.0,
"face_bbox_iou_avg": 0.0,
"face_keypoint_similarity_avg": 0.0,
"top1_emotion_accuracy": 0.0,
"emotion_vector_similarity_avg": 0.0,
"obfuscation_accuracy": 0.0,
"face_distance_avg": 0.0,
#"face_n_keypoint_deviation_avg": face_n_keypoint_deviation_avg,
"face_keypoint_position_similarity_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,
"object_class_accuracy": 0.0
}
}
iterations = 0
#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)):
for idx, before_image_name in enumerate(tqdm(os.listdir(before_directory))): #TODO Entfernen enumerate
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"))
meta_data = self._compare_metadata(before_meta_path, after_meta_path)
img_comparison_results = self._compare_metadata(before_meta_path, after_meta_path)
print(iterations)#TODO Entfernen
print(img_comparison_results)
#Aggregate meta_data into folder_result_dict
for key, value in meta_data.items():
for key, value in img_comparison_results.items():
for sub_key, sub_value in value.items():
folder_result_dict[key][sub_key] += sub_value
iterations += 1
if iterations == 3:#TODO: entfernen
break
#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
folder_result_dict[key][sub_key] /= iterations #before_image_count
print("after")
print(iterations)
print(folder_result_dict)
exit()
#TODO: FIX --> raise ValueError(f"Key-point shapes differ: {kps_a.shape} vs {kps_b.shape}")
return folder_result_dict
@@ -214,15 +234,17 @@ class Comparator:
found_matching_persons_count = 0
person_bbox_ious = []
person_segment_ious = []
person_keypoint_similarities = []
person_n_keypoint_deviations = []
person_keypoint_position_deviations = []
found_face_count = 0
face_bbox_ious = []
face_keypoint_similarities = []
same_emotion_count = 0
emotion_vector_similarities = []
same_person_counter = 0
face_distances = []
identity_distances = []
#face_n_keypoint_deviations= []
face_keypoint_position_deviations = []
#Object scores
before_object_count = len(before_meta["objects"])
@@ -239,20 +261,11 @@ class Comparator:
found_matching_persons_count += 1
person_bbox_ious.append(bbox_iou)
person_segment_ious.append(segment_iou)
n_point_deviation, avg_position_deviation = _compute_body_keypoint_deviation(before_person["body_keypoints"], after_person["body_keypoints"], before_person["bbox"], after_person["bbox"], before_img.shape[1], before_img.shape[0])
person_n_keypoint_deviations.append(n_point_deviation)
if avg_position_deviation is not None:
person_keypoint_position_deviations.append(avg_position_deviation)
print(before_person)
print(after_person)
print(path_to_meta_after)
person_keypoint_similarities.append(_compute_body_keypoint_deviation(
before_person["body_keypoints"], after_person["body_keypoints"],
before_person["bbox"], after_person["bbox"],
before_img.shape[1], before_img.shape[0]
)
)
exit()
#TODO: person keypoint similarity, normalisieren zu body bounding box
#TODO: face keypoint similarity, normalisieren zu face bounding box
#Check for validity of before data
if before_person["face_bbox"] is None:
raise ValueError("Before person has no face", path_to_meta_before)
@@ -267,11 +280,14 @@ class Comparator:
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)
face_verified, identity_distance = _match_persons(before_face_crop, after_face_crop)
if face_verified:
same_person_counter += 1
face_distances.append(face_distance)
identity_distances.append(identity_distance)
_, face_avg_position_deviation = _compute_face_keypoint_deviation(before_person["face_keypoints"], after_person["face_keypoints"], before_img.shape[1], before_img.shape[0])
#face_n_keypoint_deviations.append(face_n_point_deviation)
if face_avg_position_deviation is not None:
face_keypoint_position_deviations.append(face_avg_position_deviation)
for before_object in before_meta["objects"]:
result = _find_best_matching_object(before_object, after_meta["objects"])
@@ -285,19 +301,23 @@ class Comparator:
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)
person_bbox_iou_avg = np.mean(person_bbox_ious) * 100.0 if len(person_bbox_ious) > 0 else 0.0
person_segment_iou_avg = np.mean(person_segment_ious) * 100.0 if len(person_segment_ious) > 0 else 0.0
person_n_keypoint_similarity_avg = (1.0 - np.mean(person_n_keypoint_deviations)) * 100.0 if len(person_n_keypoint_deviations) > 0 else 0.0
person_keypoint_position_similarity_avg = (1.0 - np.mean(person_keypoint_position_deviations)) * 100.0 if len(person_keypoint_position_deviations) > 0 else 0.0
face_found_accuracy = (found_face_count / before_person_count) * 100.0
face_bbox_iou_avg = np.mean(face_bbox_ious)
face_found_accuracy = (found_face_count / before_person_count) * 100.0 if found_face_count > 0 else 0.0
face_bbox_iou_avg = np.mean(face_bbox_ious) * 100.0 if len(face_bbox_ious) > 0 else 0.0
top1_emotion_accuracy = ((same_emotion_count / found_face_count) * 100.0) if (found_face_count > 0) else 0.0
emotion_vector_similarity_avg = np.mean(emotion_vector_similarities)
obfuscation_accuracy = ((1.0 - (same_person_counter / found_face_count)) * 100.0) if (found_face_count > 0) else 1.0
face_distance_avg = np.mean(face_distances)
emotion_vector_similarity_avg = np.mean(emotion_vector_similarities) * 100.0 if len(emotion_vector_similarities) > 0 else 0.0
obfuscation_accuracy = ((1.0 - (same_person_counter / found_face_count)) * 100.0) if (found_face_count > 0) else 100.0
identity_distance_avg = np.mean(identity_distances) * 100.0 if len(identity_distances) > 0 else 100.0
#face_n_keypoint_deviation_avg = np.mean(face_n_keypoint_deviations)
face_keypoint_position_similarity_avg = (1.0 - np.mean(face_keypoint_position_deviations)) * 100.0 if len(face_keypoint_position_deviations) > 0 else 0.0
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_bbox_iou_avg = np.mean(object_bbox_ious) * 100.0 if len(object_bbox_ious) > 0 else 0.0
object_segment_iou_avg = np.mean(object_segment_ious) * 100.0 if len(object_segment_ious) > 0 else 0.0
object_class_accuracy = (found_matching_classes_count / before_object_count) * 100.0
result_score_dict = {
@@ -305,16 +325,18 @@ class Comparator:
"person_found_accuracy": person_found_accuracy,
"person_bbox_iou_avg": person_bbox_iou_avg,
"person_segment_iou_avg": person_segment_iou_avg,
"person_keypoint_similarity_avg": None #TODO
"person_n_keypoint_similarity_avg": person_n_keypoint_similarity_avg,
"person_keypoint_position_similarity_avg": person_keypoint_position_similarity_avg
},
"face": {
"face_found_accuracy": face_found_accuracy,
"face_bbox_iou_avg": face_bbox_iou_avg,
"face_keypoint_similarity_avg": None, #TODO
"top1_emotion_accuracy": top1_emotion_accuracy,
"emotion_vector_similarity_avg": emotion_vector_similarity_avg,
"obfuscation_accuracy": obfuscation_accuracy,
"face_distance_avg": face_distance_avg,
"face_distance_avg": identity_distance_avg,
#"face_n_keypoint_deviation_avg": face_n_keypoint_deviation_avg,
"face_keypoint_position_similarity_avg": face_keypoint_position_similarity_avg
},
"object": {
"object_found_accuracy": object_found_accuracy,
+5 -4
View File
@@ -55,6 +55,7 @@ def _deepface_bbox_to_xyxy(face_dict: Dict[str, Any]) -> List[int]:
return [area["x"], area["y"],
area["x"] + area["w"],
area["y"] + area["h"]]
def _facial_region_to_xyxy(face) -> list[int]:
"""
Accepts either the dataclass (x,y,w,h,score) or a dict DeepFace
@@ -131,7 +132,7 @@ class MetaExtractor:
face_crop = img_rgb[fy0 + py0:fy1 + py0, fx0 + px0:fx1 + px0]
dom_em, vec_em = _emotion(face_crop)
face_kps: list[list[float]] = []
face_kps = []
mesh = self._mp_mesh.process(face_crop)
@@ -148,11 +149,11 @@ class MetaExtractor:
dom_em, vec_em = "", {}
# -- 2) BODY POSE on this crop only ------------------------------
pose_res = self.pose_estimator.predict(person_crop, verbose=False, device=0)[0]
pose_result = self.pose_estimator.predict(person_crop, verbose=False, device=0)[0]
if pose_res.keypoints is not None and len(pose_res.keypoints) > 0:
if pose_result.keypoints is not None and len(pose_result.keypoints) > 0:
# take the highest-confidence instance in the crop
kps = pose_res.keypoints.xy[0].cpu().numpy()
kps = pose_result.keypoints.xy[0].cpu().numpy()
kps[:, 0] += px0 # translate back to full-image space
kps[:, 1] += py0
body_kps = kps.tolist()