Added obfuscation engine

This commit is contained in:
2025-05-09 10:45:17 +02:00
parent 123d0a1df1
commit 08939ccbfe
19 changed files with 143 additions and 61 deletions
Binary file not shown.
+2 -2
View File
@@ -2,8 +2,8 @@ import os
import json
from config import Config
from meta_data_extractor import MetaExtractor, ImageMeta
from meta_data_visualizer import visualize_metadata
from meta_data.meta_data_extractor import MetaExtractor, ImageMeta
from meta_data.meta_data_visualizer import visualize_metadata
import cv2
+3
View File
@@ -98,6 +98,9 @@ def main():
output_directory = os.path.join(Config.base_filtered_output_directory, dataset_name)
data_preprocessor.preprocess_images(output_directory)
init obfuscscation enginge
add obfuscators
obfuscate folders
#obfuscation_engine
#init(path_to_filtered_dataset)
@@ -17,24 +17,29 @@ from config import Config
class ObjectMeta:
label: str
bbox: List[int]# [x0,y0,x1,y1]
segment: List[List[int]]# polygon
segment: List[List[int]] # n×[x,y]
@dataclass
class PersonMeta(ObjectMeta):
body_keypoints: List[List[float]] | None
face_bbox: List[int] | None
face_keypoints: List[List[float]] # n×[x,y,z]
dominant_emotion: str
emotion_vector: Dict[str, float]
body_keypoints: List[List[float]] | None # n×[x,y,z]
face_bbox: List[int] | None # [x0,y0,x1,y1]
face_keypoints: List[List[float]] # 428×[x,y,z]
dominant_emotion: str # emotion name
emotion_vector: Dict[str, float] # {emotion: value}
@dataclass
class ImageMeta:
image: str
persons: List[PersonMeta]
objects: List[ObjectMeta]
persons: List[PersonMeta] # persons in the image
objects: List[ObjectMeta] # objects in the image
# for easy json.dumps(ImageMeta) later on
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ImageMeta":
from utils_dataclass import from_dict # avoid circular import
return from_dict(cls, data)
def _emotion(crop_rgb: np.ndarray) -> Tuple[str, Dict[str, float]]:
"""
+33
View File
@@ -0,0 +1,33 @@
from dataclasses import is_dataclass, fields
from typing import get_origin, get_args, List, Dict, Any, Type, TypeVar
T = TypeVar("T")
def from_dict(cls: Type[T], data: Dict[str, Any]) -> T:
kwargs = {}
for f in fields(cls):
val = data.get(f.name)
if val is None:
kwargs[f.name] = None
continue
typ = f.type
origin = get_origin(typ)
# List[something]
if origin in (list, List):
inner = get_args(typ)[0]
if is_dataclass(inner):
kwargs[f.name] = [from_dict(inner, v) for v in val]
else:
kwargs[f.name] = val
# Nested dataclass
elif is_dataclass(typ):
kwargs[f.name] = from_dict(typ, val)
# Plain field (int, str, float, dict, ...)
else:
kwargs[f.name] = val
return cls(**kwargs)
@@ -1,3 +1,3 @@
class ObfuscationTechnique:
def obfuscate(self, face_roi_img):
def obfuscate(self, face_roi_img_bgr):
raise NotImplementedError
@@ -1,6 +1,6 @@
import numpy as np
from obfuscation_techniques.obfuscation_technique import ObfuscationTechnique
from obfuscation.base_obfuscation_technique import ObfuscationTechnique
class Blackening(ObfuscationTechnique):
@@ -11,7 +11,7 @@ class Blackening(ObfuscationTechnique):
# Normalise to 3-tuple BGR
self.colour=(0, 0, 0)
def obfuscate(self, face_roi_img: np.ndarray) -> np.ndarray:
obf = np.empty_like(face_roi_img)
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
obf = np.empty_like(face_roi_img_bgr)
obf[:] = self.colour
return obf
+13
View File
@@ -0,0 +1,13 @@
from obfuscation.base_obfuscation_technique import ObfuscationTechnique
import numpy as np
import cv2
class Blur(ObfuscationTechnique):
"""
Face obfuscation with Gaussian blur.
"""
def __init__(self):
self.kernel = 42 + 1
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
return cv2.GaussianBlur(face_roi_img_bgr, ksize=(self.kernel, self.kernel), sigmaX=0, sigmaY=0)
+71
View File
@@ -0,0 +1,71 @@
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)
@@ -1,7 +1,7 @@
import cv2
import numpy as np
from obfuscation_techniques.obfuscation_technique import ObfuscationTechnique
from obfuscation.base_obfuscation_technique import ObfuscationTechnique
class Pixelation(ObfuscationTechnique):
@@ -13,11 +13,11 @@ class Pixelation(ObfuscationTechnique):
def __init__(self, pixel_size: int = 16):
self.pixel_size = max(2, pixel_size)
def obfuscate(self, face_roi_img: np.ndarray) -> np.ndarray:
h, w = face_roi_img.shape[:2]
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
h, w = face_roi_img_bgr.shape[:2]
# Compute new size that is an integer multiple of pixel_size
w_small = max(1, w // self.pixel_size)
h_small = max(1, h // self.pixel_size)
# Downscale → upscale
tmp = cv2.resize(face_roi_img, (w_small, h_small), interpolation=cv2.INTER_LINEAR)
tmp = cv2.resize(face_roi_img_bgr, (w_small, h_small), interpolation=cv2.INTER_LINEAR)
return cv2.resize(tmp, (w, h), interpolation=cv2.INTER_NEAREST)
@@ -1,13 +0,0 @@
from obfuscation_techniques.obfuscation_technique import ObfuscationTechnique
import numpy as np
import cv2
class Blur(ObfuscationTechnique):
"""
Face obfuscation with Gaussian blur.
"""
def __init__(self):
self.kernel = 42 + 1
def obfuscate(self, face_roi_img: np.ndarray) -> np.ndarray:
return cv2.GaussianBlur(face_roi_img, ksize=(self.kernel, self.kernel), sigmaX=0, sigmaY=0)
@@ -1,30 +0,0 @@
import os
from obfuscation_techniques.obfuscation_technique import ObfuscationTechnique
def get_image_and_meta_file_paths(sub_dataset_folder):
#TODO: hier die methode schreiben
image_meta_paths = [(os.path.join(sub_dataset_folder, image_path), os.path.join(sub_dataset_folders, (image_path.split(".")[0] + ".json"))) for image_path in os.listdir(sub_dataset_folder)]
class ObfuscationEngine:
def __init__(self, path_to_filtered_dataset):
self.obfuscation_techniques = []
self.path_to_filtered_dataset = path_to_filtered_dataset
def add_obfuscation_technique(self, obfuscation_technique: ObfuscationTechnique):
self.obfuscation_techniques.append(obfuscation_technique)
def obfuscate(self, output_path, draw_images=True):
sub_dataset_folders = [os.path.join(self.path_to_filtered_dataset, sub_dataset_folder) for sub_dataset_folder in os.listdir(self.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:
#TODO: For each technique and For each subdataset and for each image, get the mata data and apply the obfuscation technique to the face
raise NotImplementedError
View File