Files
obfuscation_platform/project/meta_data_extractor.py
T

175 lines
6.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import List, Dict, Tuple, Any
import cv2
import numpy as np
import torch
import torchvision # for IoU
from ultralytics import YOLO
from deepface import DeepFace
import mediapipe as mp
@dataclass
class PersonMeta:
bbox: List[int] # [x0,y0,x1,y1]
segment: List[List[int]] # polygon
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]
@dataclass
class ObjectMeta:
label: str
bbox: List[int]
segment: List[List[int]]
@dataclass
class ImageMeta:
image: str
persons: List[PersonMeta]
objects: List[ObjectMeta]
# for easy json.dumps(ImageMeta) later on
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
def _emotion(crop_rgb: np.ndarray) -> Tuple[str, Dict[str, float]]:
"""
Return (dominant, full_vector) from a RGB face crop.
We skip DeepFace's own detector because we already have the bbox.
"""
res = DeepFace.analyze(cv2.cvtColor(crop_rgb, cv2.COLOR_RGB2BGR), detector_backend="skip", actions=["emotion"], enforce_detection=False)[0]
return res["dominant_emotion"], res["emotion"]
def _deepface_bbox_to_xyxy(face_dict: Dict[str, Any]) -> List[int]:
"""
DeepFace's 'facial_area' dict → [x0,y0,x1,y1] ints.
"""
area = face_dict["facial_area"]
return [area["x"], area["y"],
area["x"] + area["w"],
area["y"] + area["h"]]
# -----------------------------------------------------------------------------
# Main reusable component
# -----------------------------------------------------------------------------
class MetaExtractor:
def __init__(self,
seg_weights: str = "yolo11m-seg.pt",
pose_weights: str = "yolo11m-pose.pt",
face_backend: str = "retinaface"):
self.segmentor = YOLO(seg_weights)
self.pose_estimator = YOLO(pose_weights)
# DeepFace will lazy-load the detector the first time we call it.
self._face_backend = face_backend
# MediaPipe
self._mp_mesh = mp.solutions.face_mesh.FaceMesh(static_image_mode=True, refine_landmarks=True, max_num_faces=1)
def extract(self, image_path: str) -> ImageMeta | None:
img_bgr = cv2.imread(str(image_path))
if img_bgr is None:
raise FileNotFoundError(image_path)
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
persons, objects = self._extract_objects_and_persons(img_rgb)
return ImageMeta(image=Path(image_path).name,
persons=persons,
objects=objects)
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]
classes = seg_res.boxes.cls.cpu().numpy().astype(int)
person_ids = np.where(classes == 0)[0] # COCO class 0 == person
other_ids = np.where(classes != 0)[0]
# ----------- PER-PERSON METADATA -----------------------------------
persons: list[PersonMeta] = []
for idx in person_ids:
# person bbox and crop ------------------------------------------
px0, py0, px1, py1 = map(int, seg_res.boxes.xyxy[idx].tolist())
person_crop = img_rgb[py0:py1, px0:px1]
# -- 1) Face detection (DeepFace) --------------------------------
try:
faces = DeepFace.extract_faces(
cv2.cvtColor(person_crop, cv2.COLOR_RGB2BGR),
detector_backend=self._face_backend,
enforce_detection=True
)
except ValueError:
faces = []
if faces:
fx0, fy0, fx1, fy1 = _deepface_bbox_to_xyxy(faces[0])
face_bbox = [fx0 + px0, fy0 + py0, fx1 + px0, fy1 + py0]
# crop the exact face for emotion / mesh
face_crop = img_rgb[fy0 + py0:fy1 + py0, fx0 + px0:fx1 + px0]
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([
fx0 + px0 + int(lm.x * face_crop.shape[1]),
fy0 + py0 + int(lm.y * face_crop.shape[0]),
lm.z,
])
else:
face_bbox = None
face_kps = []
dom_em, vec_em = "", {}
# -- 2) BODY POSE on this crop only ------------------------------
pose_res = self.pose_estimator(person_crop, verbose=False)[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()
kps[:, 0] += px0 # translate back to full-image space
kps[:, 1] += py0
body_kps = kps.tolist()
else:
body_kps = None
# -- 3) assemble record -----------------------------------------
persons.append(
PersonMeta(
bbox=[px0, py0, px1, py1],
segment=seg_res.masks.xy[idx].astype(int).tolist() if seg_res.masks is not None else [],
body_keypoints=body_kps,
face_bbox=face_bbox,
face_keypoints=face_kps,
dominant_emotion=dom_em,
emotion_vector=vec_em,
)
)
# ----------- NON-PERSON OBJECTS -----------------------------------
objects: List[ObjectMeta] = []
for idx in other_ids:
cls_id = int(classes[idx])
objects.append(
ObjectMeta(
label=self.segmentor.model.names[cls_id],
bbox=list(map(int, seg_res.boxes.xyxy[idx].tolist())),
segment=seg_res.masks.xy[idx].astype(int).tolist() if seg_res.masks is not None else [],
)
)
return persons, objects