Added code to check whether already computed

This commit is contained in:
2025-05-09 12:20:57 +02:00
parent 08939ccbfe
commit 2eaa8058c6
30 changed files with 94 additions and 14224 deletions
+2 -1
View File
@@ -1 +1,2 @@
project/.idea/*
project/.idea/*
datasets/*
+1
View File
@@ -0,0 +1 @@
datasets/*
Binary file not shown.
Binary file not shown.
+22 -2
View File
@@ -1,11 +1,31 @@
from obfuscation.blackening import Blackening
from obfuscation.blurring import Blurring
from obfuscation.pixelation import Pixelation
class Config:
raw_dataset_path="datasets/raw/"
base_filtered_output_directory="datasets/filtered/"
filtered_output_directory="datasets/filtered/"
obfuscated_output_directory="datasets/obfuscated/"
max_images_per_dataset=5000
seg_model_type="yolo11m-seg.pt"
pose_model_type="yolo11m-pose.pt"
face_model_type="retinaface"
verbose=True
tasks = {"preprocessing": True, # optional if already done
"obfuscation": True, # optional if already done
"analysis": True # mandatory
}
#DEBUG
debug_show_preprocessing=False
debug_show_preprocessing=False
obfuscation_techniques=[
Blackening(),
Blurring(),
Pixelation()
]
+3 -1
View File
@@ -6,7 +6,9 @@ class DatasetLoader:
self.path=path
#This function loads the data from the given path and returns a dict with entries for each subfolder in the given path the folder name and strings
def load_data(self) -> Dict[str, List[str]]:
def load_data(self, verbose=False) -> Dict[str, List[str]]:
if verbose:
print(f"Loading data from {self.path}")
subdirs = [sub for sub in os.listdir(self.path) if os.path.isdir(os.path.join(self.path, sub))]
data_dict = {}
for subdir in subdirs:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 685 KiB

File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 400 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 362 KiB

+16 -4
View File
@@ -1,8 +1,10 @@
import os
import json
import random
from config import Config
from meta_data.meta_data_extractor import MetaExtractor, ImageMeta
from tqdm import tqdm
from meta_data.meta_data_visualizer import visualize_metadata
import cv2
@@ -19,13 +21,21 @@ class DataPreprocessor:
faces_ok = all(p.face_bbox for p in meta.persons)
return has_person and has_object and faces_ok
def preprocess_images(self, output_directory):
def preprocess_images(self, output_directory, verbose=False):
extractor = MetaExtractor()
random.shuffle(self.image_paths)
if not os.path.exists(output_directory):
os.mkdir(output_directory)
img_counter = 0
for img_file_path in self.image_paths:
if verbose:
iterator = tqdm(self.image_paths, desc="Preprocessing Images")
else:
iterator = self.image_paths
for img_file_path in iterator:
if img_counter >= self.max_images_per_dataset:
return
image_meta = extractor.extract(img_file_path)
if Config.debug_show_preprocessing:
self._debug_show(image_meta, img_file_path)
@@ -34,13 +44,15 @@ class DataPreprocessor:
if is_accepted:
meta_data_file_path = os.path.join(output_directory, os.path.basename(img_file_path).split(".")[0] + ".json")
output_image_file_path = os.path.join(output_directory, os.path.basename(img_file_path))
if os.path.exists(output_image_file_path):
print("Skipping " + output_image_file_path + " as it already exists")
img_counter += 1
continue
with open(meta_data_file_path, "w") as f:
json.dump(image_meta.to_dict(), f, indent=2)
img = cv2.imread(img_file_path)
cv2.imwrite(output_image_file_path, img)
img_counter += 1
if img_counter >= self.max_images_per_dataset:
return
def _debug_show(self, image_meta, img_file_path):
print("Debug Routine")
+13 -28
View File
@@ -2,6 +2,7 @@ import os
from config import Config
from data_loader import DatasetLoader
from image_preprocessor import DataPreprocessor
from obfuscation.obfuscation_engine import ObfuscationEngine
##Steps:
@@ -89,37 +90,21 @@ from image_preprocessor import DataPreprocessor
def main():
print("Starting obfuscation platform")
#First: load the image datasets
data_loader = DatasetLoader(Config.raw_dataset_path)
raw_datasets_dict = data_loader.load_data() #This variable contains a dict with the filenames for each dataset
#Second: filter the image data and extract meta data
for dataset_name, image_paths in raw_datasets_dict.items():
data_preprocessor = DataPreprocessor(image_paths, Config.max_images_per_dataset)
output_directory = os.path.join(Config.base_filtered_output_directory, dataset_name)
data_preprocessor.preprocess_images(output_directory)
#1: Preprocess images and extract metadata
if Config.tasks["preprocessing"]:
data_loader = DatasetLoader(Config.raw_dataset_path)
raw_datasets_dict = data_loader.load_data(verbose=Config.verbose) #This variable contains a dict with the filenames for each dataset
for dataset_name, image_paths in raw_datasets_dict.items():
data_preprocessor = DataPreprocessor(image_paths, Config.max_images_per_dataset)
output_directory = os.path.join(Config.filtered_output_directory, dataset_name)
data_preprocessor.preprocess_images(output_directory, Config.verbose)
init obfuscscation enginge
add obfuscators
obfuscate folders
#2: Obfuscate filtered datasets
if Config.tasks["obfuscation"]:
obfuscation_engine = ObfuscationEngine(Config.obfuscation_techniques)
obfuscation_engine.obfuscate_datasets(Config.filtered_output_directory, Config.obfuscated_output_directory, verbose=Config.verbose)
#obfuscation_engine
#init(path_to_filtered_dataset)
#obfuscate(obfuscation_technique, output_path, draw_images=True)
#TODO: For each image, get the mata data and apply the obfuscation technique
#obfuscation_technique
#init //Custom init
#obfuscate(face_area)
#configure pipeline
#load data
#pre-process data //create dataset based on specific criteria
#Run analysis
#Analyze data (values before obfuscation)
#Obfuscate data (with current method)
#Analyze data (values after obfuscation)
#Evaluate (analyze e.g. delta/error for before vs after, and aggregate results)
#Visualize Statistics
if __name__ == '__main__':
main()
+2 -6
View File
@@ -35,10 +35,6 @@ class ImageMeta:
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]]:
@@ -85,7 +81,7 @@ class MetaExtractor:
def _extract_objects_and_persons(self, img_rgb: np.ndarray) -> Tuple[List[PersonMeta], List[ObjectMeta]]:
H, W = img_rgb.shape[:2]
seg_res = self.segmentor(img_rgb, verbose=False)[0]
seg_res = self.segmentor.predict(img_rgb, verbose=False, device=0)[0]
classes = seg_res.boxes.cls.cpu().numpy().astype(int)
person_ids = np.where(classes == 0)[0] # COCO class 0 == person
@@ -131,7 +127,7 @@ class MetaExtractor:
dom_em, vec_em = "", {}
# -- 2) BODY POSE on this crop only ------------------------------
pose_res = self.pose_estimator(person_crop, verbose=False)[0]
pose_res = self.pose_estimator.predict(person_crop, verbose=False, device=0)[0]
if pose_res.keypoints is not None and len(pose_res.keypoints) > 0:
# take the highest-confidence instance in the crop
kps = pose_res.keypoints.xy[0].cpu().numpy()
+1 -1
View File
@@ -2,7 +2,7 @@ import cv2
import numpy as np
from typing import Tuple
from meta_data_extractor import ImageMeta
from meta_data.meta_data_extractor import ImageMeta
# -------------------------------------------------------------------
# COCO-17 skeleton pairs (0-based indices in YOLO-v11 pose output)
@@ -1,3 +1,6 @@
class ObfuscationTechnique:
def obfuscate(self, face_roi_img_bgr):
raise NotImplementedError
def name(self):
raise NotImplementedError
+4 -1
View File
@@ -14,4 +14,7 @@ class Blackening(ObfuscationTechnique):
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
obf = np.empty_like(face_roi_img_bgr)
obf[:] = self.colour
return obf
return obf
def name(self):
return "blackening"
+4 -1
View File
@@ -2,7 +2,7 @@ from obfuscation.base_obfuscation_technique import ObfuscationTechnique
import numpy as np
import cv2
class Blur(ObfuscationTechnique):
class Blurring(ObfuscationTechnique):
"""
Face obfuscation with Gaussian blur.
"""
@@ -11,3 +11,6 @@ class Blur(ObfuscationTechnique):
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)
def name(self):
return "blurring"
+19 -11
View File
@@ -5,6 +5,7 @@ from typing import Tuple
import cv2
import numpy as np
from tqdm import tqdm
from meta_data.meta_data_extractor import ImageMeta
from obfuscation.base_obfuscation_technique import ObfuscationTechnique
@@ -20,11 +21,8 @@ def get_image_and_meta_file_paths(dataset_folder):
class ObfuscationEngine:
def __init__(self):
self.obfuscation_techniques = []
def add_obfuscation_technique(self, obfuscation_technique: ObfuscationTechnique):
self.obfuscation_techniques.append(obfuscation_technique)
def __init__(self, obfuscation_techniques):
self.obfuscation_techniques = obfuscation_techniques
@staticmethod
def obfuscate_face_in_image(img_bgr: np.ndarray, face_bbox: Tuple[int, int, int, int], technique: ObfuscationTechnique) -> np.ndarray:
@@ -50,22 +48,32 @@ class ObfuscationEngine:
img = cv2.imread(image_path)
image_meta = None
with open(meta_path, 'r') as f:
image_meta = ImageMeta.from_dict(json.load(f))
image_meta = json.load(f)
for person in image_meta.persons:
img = self.obfuscate_face_in_image(img, person.face_bbox, technique)
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):
def obfuscate_datasets(self, path_to_filtered_dataset, output_path, verbose=False):
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:
iterable = sub_dataset_folders
if verbose:
iterable = tqdm(sub_dataset_folders, desc="Obfuscating folders")
for sub_dataset_folder in iterable:
print(f"Obfuscating {sub_dataset_folder}")
image_meta_pairs = get_image_and_meta_file_paths(sub_dataset_folder)
for technique in self.obfuscation_techniques:
technique_path = os.path.join(output_path, technique.name())
if not os.path.exists(technique_path):
os.makedirs(technique_path)
for image_path, meta_path in image_meta_pairs:
obfuscated_image_output_path = os.path.join(technique_path, os.path.basename(image_path))
if os.path.exists(obfuscated_image_output_path):
print(f"Skipping {obfuscated_image_output_path} as it already exists")
continue
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)
+4 -1
View File
@@ -20,4 +20,7 @@ class Pixelation(ObfuscationTechnique):
h_small = max(1, h // self.pixel_size)
# Downscale → upscale
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)
return cv2.resize(tmp, (w, h), interpolation=cv2.INTER_NEAREST)
def name(self):
return "pixelation"