348 lines
16 KiB
Python
348 lines
16 KiB
Python
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
|
|
|
|
|
|
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 _to_valid_poly(coords) -> Polygon:
|
|
poly = orient(Polygon(coords), sign=1.0) # CCW erzwingen
|
|
if not poly.is_valid:
|
|
try:
|
|
poly = make_valid(poly)
|
|
except Exception:
|
|
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(Polygon(poly_a))
|
|
pb = _to_valid_poly(Polygon(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)
|
|
iou = 0
|
|
return iou
|
|
|
|
|
|
#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 _adapt_body_keypoints(kps, bbox, img_w, img_h):
|
|
for kp in kps:
|
|
if (kp[0] == bbox[0]) and (kp[1] == bbox[1]):
|
|
kp[0] = 0
|
|
kp[1] = 0
|
|
else:
|
|
#Normalize by image size
|
|
kp[0] = kp[0] / img_w
|
|
kp[1] = kp[1] / img_h
|
|
|
|
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)])
|
|
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 = []
|
|
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
|
|
deviation = np.linalg.norm(np.array(kp_a) - np.array(kp_b))
|
|
point_wise_deviations.append(deviation)
|
|
|
|
average_position_deviation = None
|
|
if len(point_wise_deviations) > 0:
|
|
average_position_deviation = np.mean(point_wise_deviations)
|
|
|
|
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: {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
|
|
_adapt_body_keypoints(kps_a, bbox_a, img_w, img_h)
|
|
_adapt_body_keypoints(kps_b, bbox_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 _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")
|
|
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)
|
|
cos_sim = 1.0
|
|
try:
|
|
cos_sim = float(cosine(v1, v2))
|
|
if not cos_sim:
|
|
cos_sim = 1.0
|
|
except:
|
|
cos_sim = 1.0
|
|
return 1.0 - cos_sim
|
|
|
|
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_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: #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_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,
|
|
"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
|
|
}
|
|
}
|
|
iterations = 0
|
|
#Iterate through all images in before directory and find the corresponding image in the obfuscated 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"))
|
|
|
|
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 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] /= 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
|
|
|
|
#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 = []
|
|
person_n_keypoint_deviations = []
|
|
person_keypoint_position_deviations = []
|
|
|
|
found_face_count = 0
|
|
face_bbox_ious = []
|
|
same_emotion_count = 0
|
|
emotion_vector_similarities = []
|
|
same_person_counter = 0
|
|
identity_distances = []
|
|
#face_n_keypoint_deviations= []
|
|
face_keypoint_position_deviations = []
|
|
|
|
#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)
|
|
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)
|
|
|
|
#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, identity_distance = _match_persons(before_face_crop, after_face_crop)
|
|
if face_verified:
|
|
same_person_counter += 1
|
|
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"])
|
|
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) * 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 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) * 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) * 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 = {
|
|
"person": {
|
|
"person_found_accuracy": person_found_accuracy,
|
|
"person_bbox_iou_avg": person_bbox_iou_avg,
|
|
"person_segment_iou_avg": person_segment_iou_avg,
|
|
"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,
|
|
"top1_emotion_accuracy": top1_emotion_accuracy,
|
|
"emotion_vector_similarity_avg": emotion_vector_similarity_avg,
|
|
"obfuscation_accuracy": obfuscation_accuracy,
|
|
"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,
|
|
"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 |