Adapted code to use yunet, which is faster and state of the art (face detection)
This commit is contained in:
Binary file not shown.
Binary file not shown.
+2
-2
@@ -7,11 +7,11 @@ class Config:
|
||||
raw_dataset_path="datasets/raw/"
|
||||
filtered_output_directory="datasets/filtered/"
|
||||
obfuscated_output_directory="datasets/obfuscated/"
|
||||
max_images_per_dataset=5000
|
||||
max_images_per_dataset=500
|
||||
|
||||
seg_model_type="yolo11m-seg.pt"
|
||||
pose_model_type="yolo11m-pose.pt"
|
||||
face_model_type="retinaface"
|
||||
face_model_type="yunet"
|
||||
|
||||
verbose=True
|
||||
|
||||
|
||||
@@ -24,9 +24,13 @@ class DataPreprocessor:
|
||||
def preprocess_images(self, output_directory, verbose=False):
|
||||
extractor = MetaExtractor()
|
||||
random.shuffle(self.image_paths)
|
||||
print("Current output directory: " + output_directory)
|
||||
|
||||
if not os.path.exists(output_directory):
|
||||
os.mkdir(output_directory)
|
||||
already_done_count = len([f for f in os.listdir(output_directory) if f.endswith(".json")])
|
||||
print("Already done: " + str(already_done_count) + " images")
|
||||
print("Remaining: " + str(self.max_images_per_dataset - already_done_count) + " images")
|
||||
|
||||
img_counter = 0
|
||||
if verbose:
|
||||
@@ -34,7 +38,7 @@ class DataPreprocessor:
|
||||
else:
|
||||
iterator = self.image_paths
|
||||
for img_file_path in iterator:
|
||||
if img_counter >= self.max_images_per_dataset:
|
||||
if img_counter >= (self.max_images_per_dataset - already_done_count):
|
||||
return
|
||||
image_meta = extractor.extract(img_file_path)
|
||||
if Config.debug_show_preprocessing:
|
||||
|
||||
@@ -89,6 +89,10 @@ from obfuscation.obfuscation_engine import ObfuscationEngine
|
||||
|
||||
|
||||
def main():
|
||||
#TODO: die analysen vorher/nachher
|
||||
#TODO: gute techniken hinzufügen
|
||||
#TODO: Techniken alle mit GPU
|
||||
|
||||
print("Starting obfuscation platform")
|
||||
#1: Preprocess images and extract metadata
|
||||
if Config.tasks["preprocessing"]:
|
||||
@@ -104,6 +108,8 @@ def main():
|
||||
obfuscation_engine = ObfuscationEngine(Config.obfuscation_techniques)
|
||||
obfuscation_engine.obfuscate_datasets(Config.filtered_output_directory, Config.obfuscated_output_directory, verbose=Config.verbose)
|
||||
|
||||
#3: Extract metadata from obfuscated datasets
|
||||
# if Config.tasks["analysis"]:
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Binary file not shown.
@@ -13,6 +13,7 @@ import mediapipe as mp
|
||||
from config import Config
|
||||
|
||||
|
||||
|
||||
@dataclass
|
||||
class ObjectMeta:
|
||||
label: str
|
||||
@@ -54,15 +55,28 @@ 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
|
||||
returns and converts it to [x0,y0,x1,y1].
|
||||
"""
|
||||
if hasattr(face, "x"): # YuNet dataclass branch
|
||||
return [face.x, face.y,
|
||||
face.x + face.w,
|
||||
face.y + face.h]
|
||||
# fallback: the classic dict
|
||||
area = face["facial_area"]
|
||||
return [area["x"], area["y"],
|
||||
area["x"] + area["w"],
|
||||
area["y"] + area["h"]]
|
||||
|
||||
class MetaExtractor:
|
||||
def __init__(self):
|
||||
self.segmentor = YOLO(Config.seg_model_type)
|
||||
self.pose_estimator = YOLO(Config.pose_model_type)
|
||||
|
||||
# DeepFace will lazy-load the detector the first time we call it.
|
||||
self._face_backend = Config.face_model_type
|
||||
self.face_detector = DeepFace.build_model(model_name=Config.face_model_type, task="face_detector")
|
||||
# self._face_backend = Config.face_model_type
|
||||
|
||||
# MediaPipe
|
||||
self._mp_mesh = mp.solutions.face_mesh.FaceMesh(static_image_mode=True, refine_landmarks=True, max_num_faces=1)
|
||||
@@ -75,6 +89,7 @@ class MetaExtractor:
|
||||
|
||||
persons, objects = self._extract_objects_and_persons(img_rgb)
|
||||
|
||||
|
||||
return ImageMeta(image=Path(image_path).name,
|
||||
persons=persons,
|
||||
objects=objects)
|
||||
@@ -82,6 +97,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.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
|
||||
@@ -96,16 +112,23 @@ class MetaExtractor:
|
||||
|
||||
# -- 1) Face detection (DeepFace) --------------------------------
|
||||
try:
|
||||
faces = DeepFace.extract_faces(
|
||||
cv2.cvtColor(person_crop, cv2.COLOR_RGB2BGR),
|
||||
detector_backend=self._face_backend,
|
||||
enforce_detection=True
|
||||
)
|
||||
faces = self.face_detector.detect_faces(cv2.cvtColor(person_crop, cv2.COLOR_RGB2BGR))
|
||||
# print(faces)
|
||||
# faces1 = DeepFace.extract_faces(
|
||||
# cv2.cvtColor(person_crop, cv2.COLOR_RGB2BGR),
|
||||
# detector_backend=Config.face_model_type,
|
||||
# enforce_detection=True
|
||||
# )
|
||||
|
||||
except ValueError:
|
||||
faces = []
|
||||
|
||||
if faces:
|
||||
fx0, fy0, fx1, fy1 = _deepface_bbox_to_xyxy(faces[0])
|
||||
fx0, fy0, fx1, fy1 = _facial_region_to_xyxy(faces[0])
|
||||
# print(fx0, fy0, fx1, fy1)
|
||||
# fx0, fy0, fx1, fy1 = _deepface_bbox_to_xyxy(faces1[0])
|
||||
# print(fx0, fy0, fx1, fy1)
|
||||
# exit()
|
||||
face_bbox = [fx0 + px0, fy0 + py0, fx1 + px0, fy1 + py0]
|
||||
|
||||
# crop the exact face for emotion / mesh
|
||||
@@ -113,7 +136,9 @@ class MetaExtractor:
|
||||
dom_em, vec_em = _emotion(face_crop)
|
||||
|
||||
face_kps: list[list[float]] = []
|
||||
|
||||
mesh = self._mp_mesh.process(face_crop)
|
||||
|
||||
if mesh.multi_face_landmarks:
|
||||
for lm in mesh.multi_face_landmarks[0].landmark:
|
||||
face_kps.append([
|
||||
@@ -128,6 +153,7 @@ class MetaExtractor:
|
||||
|
||||
# -- 2) BODY POSE on this crop only ------------------------------
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user