face_analyze / app /models /face_segmentation.py
phucbienvan
commit first
1bd7909
Raw History Blame Contribute Delete
5.8 kB
import cv2
import numpy as np
import dlib
import os
import logging
from typing import Dict, Optional, Tuple
logger = logging.getLogger(__name__)
# Path to the shape predictor model
SHAPE_PREDICTOR_PATH = os.environ.get(
"SHAPE_PREDICTOR_PATH",
"app/models/shape_predictor_68_face_landmarks.dat"
)
class FaceSegmenter:
def __init__(self):
"""Initialize the face segmenter with dlib models"""
try:
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor(SHAPE_PREDICTOR_PATH)
logger.info("Face segmenter initialized successfully")
except Exception as e:
logger.error(f"Error initializing face segmenter: {e}")
raise RuntimeError(f"Failed to initialize face segmenter: {str(e)}")
def detect_face(self, image: np.ndarray) -> Optional[dlib.rectangle]:
"""Detect face in the image"""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = self.detector(gray)
if len(faces) == 0:
logger.warning("No face detected in the image")
return None
# Return the largest face if multiple faces are detected
if len(faces) > 1:
logger.info(f"Multiple faces detected, using the largest one")
return max(faces, key=lambda rect: rect.width() * rect.height())
return faces[0]
def get_landmarks(self, image: np.ndarray, face: dlib.rectangle) -> np.ndarray:
"""Get facial landmarks for the detected face"""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
landmarks = self.predictor(gray, face)
# Convert landmarks to numpy array
points = np.zeros((68, 2), dtype=int)
for i in range(68):
points[i] = (landmarks.part(i).x, landmarks.part(i).y)
return points
def segment_face_regions(self, image: np.ndarray) -> Dict[str, np.ndarray]:
"""
Segment the face into different regions
Returns a dictionary of masks for each region
"""
# Detect face
face = self.detect_face(image)
if face is None:
raise ValueError("No face detected in the image")
# Get landmarks
landmarks = self.get_landmarks(image, face)
# Create masks for each region
height, width = image.shape[:2]
masks = {}
# Forehead mask
forehead_mask = np.zeros((height, width), dtype=np.uint8)
forehead_points = np.vstack([
landmarks[17:22], # Eyebrow
[landmarks[21][0], max(0, landmarks[21][1] - int(face.height() * 0.2))], # Top right
[landmarks[17][0], max(0, landmarks[17][1] - int(face.height() * 0.2))] # Top left
])
cv2.fillPoly(forehead_mask, [forehead_points], 255)
masks['forehead'] = forehead_mask
# Left cheek mask
left_cheek_mask = np.zeros((height, width), dtype=np.uint8)
left_cheek_points = np.vstack([
landmarks[0:4], # Jaw line
landmarks[31:32], # Nose
landmarks[48:49], # Mouth
landmarks[3:4] # Connect back
])
hull = cv2.convexHull(left_cheek_points)
cv2.fillConvexPoly(left_cheek_mask, hull, 255)
masks['left_cheek'] = left_cheek_mask
# Right cheek mask
right_cheek_mask = np.zeros((height, width), dtype=np.uint8)
right_cheek_points = np.vstack([
landmarks[13:17], # Jaw line
landmarks[35:36], # Nose
landmarks[54:55], # Mouth
landmarks[13:14] # Connect back
])
hull = cv2.convexHull(right_cheek_points)
cv2.fillConvexPoly(right_cheek_mask, hull, 255)
masks['right_cheek'] = right_cheek_mask
# Nose mask (T-zone)
nose_mask = np.zeros((height, width), dtype=np.uint8)
nose_points = landmarks[27:36] # Nose landmarks
hull = cv2.convexHull(nose_points)
cv2.fillConvexPoly(nose_mask, hull, 255)
masks['nose'] = nose_mask
# Chin mask
chin_mask = np.zeros((height, width), dtype=np.uint8)
chin_points = np.vstack([
landmarks[6:11], # Jaw line
landmarks[57:59], # Bottom lip
landmarks[56:57], # Connect
landmarks[6:7] # Connect back
])
hull = cv2.convexHull(chin_points)
cv2.fillConvexPoly(chin_mask, hull, 255)
masks['chin'] = chin_mask
# Under eyes mask
under_eyes_mask = np.zeros((height, width), dtype=np.uint8)
# Left eye
left_eye_bottom = landmarks[36:40]
left_eye_top = np.array([landmarks[17], landmarks[18], landmarks[19], landmarks[20]])
left_eye_region = np.vstack([left_eye_bottom, left_eye_top[::-1]])
# Right eye
right_eye_bottom = landmarks[42:46]
right_eye_top = np.array([landmarks[23], landmarks[24], landmarks[25], landmarks[26]])
right_eye_region = np.vstack([right_eye_bottom, right_eye_top[::-1]])
cv2.fillPoly(under_eyes_mask, [left_eye_region, right_eye_region], 255)
masks['under_eyes'] = under_eyes_mask
return masks
def apply_masks_to_image(self, image: np.ndarray, masks: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
"""Apply masks to the original image to get segmented regions"""
segmented_regions = {}
for region_name, mask in masks.items():
# Apply mask to the original image
segmented_regions[region_name] = cv2.bitwise_and(image, image, mask=mask)
return segmented_regions