Spaces:
Runtime error

ConcreteAI / utils /face_detector.py
knightsam's picture
Create face_detector.py
f9ffe36 verified
Raw History Blame Contribute Delete
6.44 kB
"""
Face Landmark Detection Module
Uses MediaPipe Face Mesh for robust 468-point facial landmark detection.
MediaPipe is chosen over dlib because:
- No need for external shape predictor files
- Better performance on diverse faces
- GPU acceleration support
- Easier deployment on Hugging Face Spaces
"""
import mediapipe as mp
import numpy as np
from dataclasses import dataclass
from typing import Optional, List, Tuple
@dataclass
class FaceLandmarks:
"""Data class holding extracted facial landmark groups."""
left_eye: np.ndarray # 6 landmarks for left eye
right_eye: np.ndarray # 6 landmarks for right eye
mouth: np.ndarray # Landmarks for mouth region
face_bbox: Optional[Tuple[int, int, int, int]] = None
all_landmarks: Optional[np.ndarray] = None
confidence: float = 0.0
class FaceLandmarkDetector:
"""
Detects facial landmarks using MediaPipe Face Mesh.
Extracts specific landmark indices for eyes and mouth regions.
"""
# MediaPipe Face Mesh landmark indices for left eye (6 points)
# These correspond to the eye contour points needed for EAR calculation
LEFT_EYE_INDICES = [362, 385, 387, 263, 373, 380]
# MediaPipe Face Mesh landmark indices for right eye (6 points)
RIGHT_EYE_INDICES = [33, 160, 158, 133, 153, 144]
# MediaPipe Face Mesh landmark indices for mouth (inner lips)
# Top, bottom, left, right points for MAR calculation
MOUTH_INDICES = [
# Outer vertical points
13, # Top lip center (upper)
14, # Bottom lip center (lower)
# Inner vertical points
82, # Upper inner left
312, # Upper inner right
87, # Lower inner left
317, # Lower inner right
# Horizontal points
78, # Left corner
308, # Right corner
]
def __init__(
self,
max_num_faces: int = 1,
min_detection_confidence: float = 0.5,
min_tracking_confidence: float = 0.5,
):
"""
Initialize the MediaPipe Face Mesh detector.
Args:
max_num_faces: Maximum number of faces to detect
min_detection_confidence: Minimum confidence for face detection
min_tracking_confidence: Minimum confidence for landmark tracking
"""
self.mp_face_mesh = mp.solutions.face_mesh
self.face_mesh = self.mp_face_mesh.FaceMesh(
max_num_faces=max_num_faces,
refine_landmarks=True, # Enables iris landmarks for better eye tracking
min_detection_confidence=min_detection_confidence,
min_tracking_confidence=min_tracking_confidence,
)
self.mp_drawing = mp.solutions.drawing_utils
self.mp_drawing_styles = mp.solutions.drawing_styles
def detect(self, frame: np.ndarray) -> Optional[FaceLandmarks]:
"""
Detect facial landmarks in the given frame.
Args:
frame: BGR image from OpenCV (numpy array)
Returns:
FaceLandmarks object if face detected, None otherwise
"""
import cv2
# MediaPipe requires RGB input
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, _ = frame.shape
# Process the frame through MediaPipe Face Mesh
results = self.face_mesh.process(rgb_frame)
if not results.multi_face_landmarks:
return None
# Take the first detected face
face_landmarks = results.multi_face_landmarks[0]
# Convert normalized landmarks to pixel coordinates
all_points = np.array([
(lm.x * w, lm.y * h)
for lm in face_landmarks.landmark
])
# Extract specific landmark groups
left_eye = np.array([all_points[i] for i in self.LEFT_EYE_INDICES])
right_eye = np.array([all_points[i] for i in self.RIGHT_EYE_INDICES])
mouth = np.array([all_points[i] for i in self.MOUTH_INDICES])
# Calculate face bounding box from all landmarks
x_coords = all_points[:, 0]
y_coords = all_points[:, 1]
bbox = (
int(x_coords.min()),
int(y_coords.min()),
int(x_coords.max()),
int(y_coords.max()),
)
return FaceLandmarks(
left_eye=left_eye,
right_eye=right_eye,
mouth=mouth,
face_bbox=bbox,
all_landmarks=all_points,
confidence=min(
face_landmarks.landmark[0].visibility
if hasattr(face_landmarks.landmark[0], 'visibility')
else 1.0,
1.0
),
)
def draw_landmarks(
self,
frame: np.ndarray,
landmarks: FaceLandmarks,
draw_eyes: bool = True,
draw_mouth: bool = True,
draw_bbox: bool = True,
) -> np.ndarray:
"""
Draw detected landmarks on the frame for visualization.
Args:
frame: Input BGR image
landmarks: Detected FaceLandmarks
draw_eyes: Whether to draw eye landmarks
draw_mouth: Whether to draw mouth landmarks
draw_bbox: Whether to draw face bounding box
Returns:
Frame with landmarks drawn
"""
import cv2
annotated = frame.copy()
if draw_eyes:
# Draw left eye contour in green
pts_left = landmarks.left_eye.astype(np.int32)
cv2.polylines(annotated, [pts_left], True, (0, 255, 0), 2)
for pt in pts_left:
cv2.circle(annotated, tuple(pt), 2, (0, 255, 0), -1)
# Draw right eye contour in green
pts_right = landmarks.right_eye.astype(np.int32)
cv2.polylines(annotated, [pts_right], True, (0, 255, 0), 2)
for pt in pts_right:
cv2.circle(annotated, tuple(pt), 2, (0, 255, 0), -1)
if draw_mouth:
# Draw mouth landmarks in blue
pts_mouth = landmarks.mouth.astype(np.int32)
for pt in pts_mouth:
cv2.circle(annotated, tuple(pt), 3, (255, 0, 0), -1)
if draw_bbox and landmarks.face_bbox:
x1, y1, x2, y2 = landmarks.face_bbox
cv2.rectangle(annotated, (x1, y1), (x2, y2), (255, 255, 0), 2)
return annotated
def cleanup(self):
"""Release MediaPipe resources."""
self.face_mesh.close()