72 lines
2.8 KiB
Python
72 lines
2.8 KiB
Python
import json
|
|
import os
|
|
from typing import Tuple
|
|
|
|
import cv2
|
|
import numpy as np
|
|
|
|
from meta_data.meta_data_extractor import ImageMeta
|
|
from obfuscation.base_obfuscation_technique import ObfuscationTechnique
|
|
|
|
def get_image_and_meta_file_paths(dataset_folder):
|
|
image_meta_pairs = []
|
|
for file in os.listdir(dataset_folder):
|
|
if ".json" not in file:
|
|
image_path = os.path.join(dataset_folder, file)
|
|
meta_path = image_path.split(".")[0] + ".json"
|
|
image_meta_pairs.append((image_path, meta_path))
|
|
return image_meta_pairs
|
|
|
|
|
|
|
|
class ObfuscationEngine:
|
|
def __init__(self):
|
|
self.obfuscation_techniques = []
|
|
|
|
def add_obfuscation_technique(self, obfuscation_technique: ObfuscationTechnique):
|
|
self.obfuscation_techniques.append(obfuscation_technique)
|
|
|
|
@staticmethod
|
|
def obfuscate_face_in_image(img_bgr: np.ndarray, face_bbox: Tuple[int, int, int, int], technique: ObfuscationTechnique) -> np.ndarray:
|
|
h, w = img_bgr.shape[:2]
|
|
x0, y0, x1, y1 = map(int, face_bbox)
|
|
|
|
# ---- 1) guard against bboxes outside the image -----------------
|
|
x0, y0 = max(0, x0), max(0, y0)
|
|
x1, y1 = min(w, x1), min(h, y1)
|
|
if x0 >= x1 or y0 >= y1:
|
|
raise ValueError("Face bbox is empty or outside the image")
|
|
|
|
# ---- 2) extract ROI, obfuscate it ------------------------------
|
|
roi = img_bgr[y0:y1, x0:x1]
|
|
obf_roi = technique.obfuscate(roi)
|
|
|
|
# ---- 3) paste back into a COPY of the original -----------------
|
|
out = img_bgr.copy()
|
|
out[y0:y1, x0:x1] = obf_roi
|
|
return out
|
|
|
|
def _obfuscate_faces_in_image(self, technique, image_path, meta_path) -> np.ndarray:
|
|
img = cv2.imread(image_path)
|
|
image_meta = None
|
|
with open(meta_path, 'r') as f:
|
|
image_meta = ImageMeta.from_dict(json.load(f))
|
|
|
|
for person in image_meta.persons:
|
|
img = self.obfuscate_face_in_image(img, person.face_bbox, technique)
|
|
return img
|
|
|
|
|
|
def obfuscate_datasets(self, path_to_filtered_dataset, output_path):
|
|
sub_dataset_folders = [os.path.join(path_to_filtered_dataset, sub_dataset_folder) for sub_dataset_folder in os.listdir(path_to_filtered_dataset)]
|
|
for sub_dataset_folder in sub_dataset_folders:
|
|
image_meta_pairs = get_image_and_meta_file_paths(sub_dataset_folder)
|
|
for technique in self.obfuscation_techniques:
|
|
for image_path, meta_path in image_meta_pairs:
|
|
obfuscated_image = self._obfuscate_faces_in_image(technique, image_path, meta_path)
|
|
#save image
|
|
obfuscated_image_output_path = os.path.join(output_path, os.path.basename(image_path))
|
|
cv2.imwrite(obfuscated_image_output_path, obfuscated_image)
|
|
|
|
|