diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index 0753512..269480b 100644 Binary files a/project/__pycache__/config.cpython-310.pyc and b/project/__pycache__/config.cpython-310.pyc differ diff --git a/project/__pycache__/image_preprocessor.cpython-310.pyc b/project/__pycache__/image_preprocessor.cpython-310.pyc index c797b2d..beb8624 100644 Binary files a/project/__pycache__/image_preprocessor.cpython-310.pyc and b/project/__pycache__/image_preprocessor.cpython-310.pyc differ diff --git a/project/config.py b/project/config.py index 5971a96..35f1635 100644 --- a/project/config.py +++ b/project/config.py @@ -29,8 +29,7 @@ class Config: verbose=True - dataset_names = ["aaa", "celeba", "wider"] - + dataset_names = ["aaa"]#, "celeba", "wider"] tasks = {"preprocessing": True, # optional if already done "obfuscation": True, # optional if already done diff --git a/project/obfuscation/face_segmenter.py b/project/face_mask/face_segmenter.py similarity index 86% rename from project/obfuscation/face_segmenter.py rename to project/face_mask/face_segmenter.py index f59cf4a..1e1ed54 100644 --- a/project/obfuscation/face_segmenter.py +++ b/project/face_mask/face_segmenter.py @@ -9,6 +9,7 @@ class FaceSegmenter: # 19-Klassen Mapping (CelebAMask-HQ) FACE_LABELS_NO_HAIR = {1,2,3,4,5,6,7,8,9,10,11,12,13} FACE_LABELS_WITH_HAIR = {1,2,3,4,5,6,7,8,9,10,11,12,13,17} + MIN_COVERAGE = 0.01 def __init__(self, weight_path: str, device=None, input_size=512, include_hair=False): """ @@ -34,7 +35,7 @@ class FaceSegmenter: std=[0.229, 0.224, 0.225]), ]) - def extract_face(self, face_roi_bgr: np.ndarray) -> np.ndarray: + def extract_face(self, face_roi_bgr: np.ndarray): if face_roi_bgr is None or face_roi_bgr.size == 0: raise ValueError("Eingabebild ist leer.") if face_roi_bgr.ndim == 2: @@ -60,9 +61,14 @@ class FaceSegmenter: out = np.zeros_like(face_roi_bgr, dtype=np.uint8) out[mask_3 == 1] = face_roi_bgr[mask_3 == 1] + + coverage = (cv2.cvtColor(out, cv2.COLOR_BGR2GRAY) > 0).mean() + if coverage < self.MIN_COVERAGE: # 1% + return None return out + if __name__ == '__main__': - seg = FaceSegmenter(weight_path="C:/Users/bijan/Desktop/obfuscation_platform/project/models/79999_iter.pth", include_hair=False) - face_only = seg.extract_face(cv2.imread("C:/Users/bijan/Desktop/obfuscation_platform/project/test/face.jpg")) - cv2.imwrite("C:/Users/bijan/Desktop/obfuscation_platform/project/test/face_only.png", face_only) + seg = FaceSegmenter(weight_path="/models/79999_iter.pth", include_hair=False) + face_only = seg.extract_face(cv2.imread("/test/face.jpg")) + cv2.imwrite("/test/face_only.png", face_only) diff --git a/project/face_mask/image_encoder_decoder.py b/project/face_mask/image_encoder_decoder.py new file mode 100644 index 0000000..942aa9b --- /dev/null +++ b/project/face_mask/image_encoder_decoder.py @@ -0,0 +1,16 @@ +import base64 +import cv2 +import numpy as np + +def mask_to_png_base64(mask: np.ndarray) -> str: + if mask.dtype != np.uint8: + mask = (mask > 0).astype(np.uint8) * 255 + ok, buf = cv2.imencode(".png", mask) + if not ok: + raise RuntimeError("PNG encoding failed") + return base64.b64encode(buf).decode("ascii") + +def png_base64_to_mask(png_b64: str) -> np.ndarray: + buf = np.frombuffer(base64.b64decode(png_b64), dtype=np.uint8) + m = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE) + return (m > 0).astype(np.uint8) \ No newline at end of file diff --git a/project/image_preprocessor.py b/project/image_preprocessor.py index c644f05..b3b840e 100644 --- a/project/image_preprocessor.py +++ b/project/image_preprocessor.py @@ -34,6 +34,8 @@ class DataPreprocessor: return False if person.face_keypoints is None or len(person.face_keypoints) == 0: return False + if person.face_segment is None or len(person.face_segment) == 0: + return False if person.dominant_emotion is None: return False if person.emotion_vector is None or len(person.emotion_vector) == 0: diff --git a/project/meta_data/__pycache__/meta_data_extractor.cpython-310.pyc b/project/meta_data/__pycache__/meta_data_extractor.cpython-310.pyc index 5e06036..542be7e 100644 Binary files a/project/meta_data/__pycache__/meta_data_extractor.cpython-310.pyc and b/project/meta_data/__pycache__/meta_data_extractor.cpython-310.pyc differ diff --git a/project/meta_data/meta_data_extractor.py b/project/meta_data/meta_data_extractor.py index 399f352..8849239 100644 --- a/project/meta_data/meta_data_extractor.py +++ b/project/meta_data/meta_data_extractor.py @@ -10,7 +10,10 @@ from deepface import DeepFace import mediapipe as mp from config import Config +from face_mask.face_segmenter import FaceSegmenter +from face_mask.converter import SegConverter +from face_mask.image_encoder_decoder import mask_to_png_base64 @dataclass @@ -25,6 +28,7 @@ class PersonMeta(ObjectMeta): face_keypoints: List[List[float]] # 468 ×[x,y,z] dominant_emotion: str # emotion name emotion_vector: Dict[str, float] # {emotion: value} + face_segment: List[List[int]] | None # n×[x,y] @dataclass class ImageMeta: image: str @@ -81,6 +85,7 @@ class MetaExtractor: # MediaPipe self._mp_mesh = mp.solutions.face_mesh.FaceMesh(static_image_mode=True, refine_landmarks=True, max_num_faces=1) + self._face_segmenter = FaceSegmenter("/models/79999_iter.pth") def extract(self, image_path: str) -> ImageMeta | None: img_bgr = cv2.imread(str(image_path)) @@ -107,11 +112,16 @@ class MetaExtractor: # person bbox and crop ------------------------------------------ px0, py0, px1, py1 = map(int, seg_res.boxes.xyxy[idx].tolist()) person_crop = img_rgb[py0:py1, px0:px1] + face_bbox = None + face_kps = [] + dom_em, vec_em = "", {} + body_kps = None + face_segment = None - # -- 1) Face detection (DeepFace) -------------------------------- + + # -- 1) Face detection (DeepFace) -------------------------------- highest_confidence_face = None try: - # faces = self.face_detector.detect_faces(cv2.cvtColor(person_crop, cv2.COLOR_RGB2BGR)) faces = DeepFace.extract_faces( cv2.cvtColor(person_crop, cv2.COLOR_RGB2BGR), detector_backend=self._face_backend, @@ -141,10 +151,8 @@ class MetaExtractor: fy0 + py0 + int(lm.y * face_crop.shape[0]), lm.z, ]) - else: - face_bbox = None - face_kps = [] - dom_em, vec_em = "", {} + + face_segment = self._face_segmenter.extract_face(face_crop) # -- 2) BODY POSE on this crop only ------------------------------ pose_result = self.pose_estimator.predict(person_crop, verbose=False, device=0)[0] @@ -159,10 +167,6 @@ class MetaExtractor: kps[:, 0] += px0 # translate back to full-image space kps[:, 1] += py0 body_kps = kps.tolist() - else: - body_kps = None - else: - body_kps = None # -- 3) assemble record ----------------------------------------- persons.append( @@ -175,6 +179,7 @@ class MetaExtractor: face_keypoints=face_kps, dominant_emotion=dom_em, emotion_vector=vec_em, + face_segment=mask_to_png_base64(face_segment) if face_segment is not None else None ) ) diff --git a/project/obfuscation/__pycache__/base_obfuscation_technique.cpython-310.pyc b/project/obfuscation/__pycache__/base_obfuscation_technique.cpython-310.pyc index 255ddec..41aed3b 100644 Binary files a/project/obfuscation/__pycache__/base_obfuscation_technique.cpython-310.pyc and b/project/obfuscation/__pycache__/base_obfuscation_technique.cpython-310.pyc differ diff --git a/project/obfuscation/__pycache__/block_black.cpython-310.pyc b/project/obfuscation/__pycache__/block_black.cpython-310.pyc index 5e1ec3d..3c6077e 100644 Binary files a/project/obfuscation/__pycache__/block_black.cpython-310.pyc and b/project/obfuscation/__pycache__/block_black.cpython-310.pyc differ diff --git a/project/obfuscation/base_obfuscation_technique.py b/project/obfuscation/base_obfuscation_technique.py index 60225c4..ca6061b 100644 --- a/project/obfuscation/base_obfuscation_technique.py +++ b/project/obfuscation/base_obfuscation_technique.py @@ -1,13 +1,8 @@ -from obfuscation.face_segmenter import FaceSegmenter - class ObfuscationTechnique: def __init__(self): - self.face_segmenter = FaceSegmenter(weight_path="C:/Users/bijan/Desktop/obfuscation_platform/project/models/79999_iter.pth", include_hair=False) + raise NotImplementedError - def extract_face(self, face_roi_img_bgr): - return self.face_segmenter.extract_face(face_roi_img_bgr) - - def obfuscate(self, face_roi_img_bgr): + def obfuscate(self, face_roi_img_bgr, face_mask): raise NotImplementedError def name(self): diff --git a/project/obfuscation/block_black.py b/project/obfuscation/block_black.py index 982c9fe..5832969 100644 --- a/project/obfuscation/block_black.py +++ b/project/obfuscation/block_black.py @@ -8,21 +8,18 @@ class Blackening(ObfuscationTechnique): Simply fill the face ROI with a constant colour (black). """ def __init__(self): - super().__init__() # Normalise to 3-tuple BGR self.colour=(0, 0, 0) - def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray: + def obfuscate(self, face_roi_img_bgr: np.ndarray, face_mask) -> np.ndarray: if face_roi_img_bgr is None or face_roi_img_bgr.size == 0: raise ValueError("Eingabebild ist leer.") - face_only = self.extract_face(face_roi_img_bgr) + #TODO Das problem finden mit dem converter usw.; ggf da auch was fixen - mask = (cv2.cvtColor(face_only, cv2.COLOR_BGR2GRAY) > 0).astype(np.uint8) - obf = face_roi_img_bgr.copy() - obf[mask.astype(bool)] = self.colour + obf[face_mask.astype(bool)] = self.colour return obf def name(self): diff --git a/project/obfuscation/obfuscation_engine.py b/project/obfuscation/obfuscation_engine.py index c3e5323..eda6e18 100644 --- a/project/obfuscation/obfuscation_engine.py +++ b/project/obfuscation/obfuscation_engine.py @@ -6,6 +6,8 @@ import cv2 import numpy as np from tqdm import tqdm + +from face_mask.image_encoder_decoder import png_base64_to_mask from meta_data.meta_data_extractor import ImageMeta from obfuscation.base_obfuscation_technique import ObfuscationTechnique @@ -25,7 +27,7 @@ class ObfuscationEngine: 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: + def obfuscate_face_in_image(img_bgr: np.ndarray, face_bbox: Tuple[int, int, int, int], face_segment, technique: ObfuscationTechnique) -> np.ndarray: h, w = img_bgr.shape[:2] x0, y0, x1, y1 = map(int, face_bbox) @@ -37,7 +39,8 @@ class ObfuscationEngine: # ---- 2) extract ROI, obfuscate it ------------------------------ roi = img_bgr[y0:y1, x0:x1] - obf_roi = technique.obfuscate(roi) + face_mask = png_base64_to_mask(face_segment) + obf_roi = technique.obfuscate(roi, face_mask) # ---- 3) paste back into a COPY of the original ----------------- out = img_bgr.copy() @@ -52,7 +55,7 @@ class ObfuscationEngine: image_meta = json.load(f) for person in image_meta["persons"]: - img = self.obfuscate_face_in_image(img, person["face_bbox"], technique) + img = self.obfuscate_face_in_image(img, person["face_bbox"], person["face_segment"], technique) return img