MFAF-Net / mfaf_net /module1_feature_extraction.py
haresh2792005's picture
Upload MFAF-Net (model)
c4a514c verified
Raw History Blame Contribute Delete
8.98 kB
"""
Module 1 – Facial Feature Extraction using MediaPipe FaceMesh / FaceLandmarker.
Extracts 468 facial landmarks, computes region-specific measurements,
draws annotated landmarks on the image, and saves the annotated copy.
Supports both legacy `mediapipe.solutions.face_mesh` and modern
MediaPipe (>=0.10.20) `mediapipe.tasks.python.vision.FaceLandmarker`.
"""
import os
import urllib.request
import cv2
import numpy as np
import mediapipe as mp
# ---------------------------------------------------------------------------
# Region landmark index definitions (MediaPipe FaceMesh canonical indices)
# ---------------------------------------------------------------------------
REGION_INDICES = {
'nose': [1, 2, 3, 4, 5, 6, 19, 20, 94, 97, 98, 99, 115, 116, 117, 118,
119, 120, 121, 122, 174, 196, 197, 198, 209, 217, 236, 239, 240,
241, 242, 243, 244, 245, 246, 248, 281, 294, 331, 358, 360, 363,
399, 420, 429, 437, 456, 460, 461, 462, 463, 464],
'eyes': [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159,
160, 161, 246, 263, 249, 390, 373, 374, 380, 381, 382, 362, 398,
384, 385, 386, 387, 388, 466],
'eyebrows': [70, 63, 105, 66, 107, 55, 65, 52, 53, 46, 300, 293, 334,
296, 336, 285, 295, 282, 283, 276],
'chin': [152, 148, 176, 149, 150, 377, 400, 378, 379, 175, 199, 200, 171, 396],
'jawline': [172, 136, 150, 149, 176, 58, 132, 93, 234,
397, 365, 379, 378, 400, 288, 361, 323, 454],
'forehead': [10, 109, 67, 103, 54, 21, 338, 297, 332, 284, 251, 151, 9, 8],
}
# Specific landmark indices for measurement calculations
NOSE_LEFT = 129
NOSE_RIGHT = 358
NOSE_TIP = 1
NOSE_BRIDGE = 6
LEFT_EYE_INNER = 133
LEFT_EYE_OUTER = 33
RIGHT_EYE_INNER = 362
RIGHT_EYE_OUTER = 263
FACE_LEFT = 234
FACE_RIGHT = 454
JAW_LEFT = 172
JAW_RIGHT = 397
CHIN_TIP = 152
NOSE_BASE = 94
FACE_LANDMARKER_URL = (
"https://storage.googleapis.com/mediapipe-models/"
"face_landmarker/face_landmarker/float16/1/face_landmarker.task"
)
FACE_LANDMARKER_PATH = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', 'models', 'face_landmarker.task')
)
def _resolve_solutions_face_mesh():
"""Return MediaPipe legacy face_mesh module if available, else None."""
if hasattr(mp, 'solutions') and hasattr(mp.solutions, 'face_mesh'):
return mp.solutions.face_mesh
try:
from mediapipe.python.solutions import face_mesh as legacy_fm
return legacy_fm
except Exception:
return None
def _ensure_face_landmarker_task() -> str:
"""Download face_landmarker.task into models/ if not already present."""
if os.path.isfile(FACE_LANDMARKER_PATH) and os.path.getsize(FACE_LANDMARKER_PATH) > 100000:
return FACE_LANDMARKER_PATH
os.makedirs(os.path.dirname(FACE_LANDMARKER_PATH), exist_ok=True)
print(f"Downloading MediaPipe FaceLandmarker model to {FACE_LANDMARKER_PATH}...")
urllib.request.urlretrieve(FACE_LANDMARKER_URL, FACE_LANDMARKER_PATH)
return FACE_LANDMARKER_PATH
class FaceLandmarkExtractor:
"""
Cross-version MediaPipe 468-point facial landmark extractor.
Works with both `mp.solutions.face_mesh` and `mp.tasks.vision.FaceLandmarker`.
"""
def __init__(self, min_detection_confidence: float = 0.45):
self.min_conf = min_detection_confidence
self._mode = None
self._engine = None
legacy_fm = _resolve_solutions_face_mesh()
if legacy_fm is not None:
self._mode = 'solutions'
self._engine = legacy_fm.FaceMesh(
static_image_mode=True,
max_num_faces=1,
refine_landmarks=True,
min_detection_confidence=self.min_conf,
)
return
# Modern MediaPipe Tasks API (mediapipe >= 0.10.20 / 0.10.30+)
try:
from mediapipe.tasks import python as mp_tasks
from mediapipe.tasks.python import vision as mp_vision
model_path = _ensure_face_landmarker_task()
with open(model_path, 'rb') as f:
model_bytes = f.read()
base_options = mp_tasks.BaseOptions(model_asset_buffer=model_bytes)
options = mp_vision.FaceLandmarkerOptions(
base_options=base_options,
running_mode=mp_vision.RunningMode.IMAGE,
num_faces=1,
min_face_detection_confidence=self.min_conf,
min_face_presence_confidence=self.min_conf,
)
self._mode = 'tasks'
self._engine = mp_vision.FaceLandmarker.create_from_options(options)
except Exception as exc:
raise RuntimeError(
f"Failed to initialize MediaPipe FaceLandmarker: {exc}. "
"Ensure internet access on first run to download face_landmarker.task, "
"or install `mediapipe==0.10.14`."
) from exc
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
if self._engine is not None:
try:
self._engine.close()
except Exception:
pass
self._engine = None
def extract(self, image_bgr: np.ndarray):
"""Return (468, 2) float32 pixel landmarks or None if no face detected."""
h, w = image_bgr.shape[:2]
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
if self._mode == 'solutions':
results = self._engine.process(image_rgb)
if not results.multi_face_landmarks:
return None
face_lms = results.multi_face_landmarks[0].landmark[:468]
elif self._mode == 'tasks':
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=image_rgb)
results = self._engine.detect(mp_image)
if not results.face_landmarks:
return None
face_lms = results.face_landmarks[0][:468]
else:
return None
return np.array([[lm.x * w, lm.y * h] for lm in face_lms], dtype=np.float32)
def compute_measurements(landmarks_array: np.ndarray) -> dict:
"""Compute Euclidean anthropometric distances from (468, 2) landmarks."""
def dist(a, b):
return float(np.linalg.norm(landmarks_array[a] - landmarks_array[b]))
return {
'nose_width': dist(NOSE_LEFT, NOSE_RIGHT),
'nose_length': dist(NOSE_BRIDGE, NOSE_TIP),
'left_eye_width': dist(LEFT_EYE_INNER, LEFT_EYE_OUTER),
'right_eye_width': dist(RIGHT_EYE_INNER, RIGHT_EYE_OUTER),
'face_width': dist(FACE_LEFT, FACE_RIGHT),
'jaw_width': dist(JAW_LEFT, JAW_RIGHT),
'chin_projection': dist(NOSE_BASE, CHIN_TIP),
'eye_width': (dist(LEFT_EYE_INNER, LEFT_EYE_OUTER) +
dist(RIGHT_EYE_INNER, RIGHT_EYE_OUTER)) / 2.0,
}
def extract_features(image_path: str, output_dir: str, uid: str) -> dict:
"""
Extract facial landmarks and compute measurements from an image.
Returns
-------
dict with keys:
landmarks_array – np.ndarray shape (468, 2) pixel coordinates
regions – dict mapping region name → np.ndarray of coords
measurements – dict of scalar float measurements
annotated_image_path – str path to annotated PNG
"""
image_bgr = cv2.imread(image_path)
if image_bgr is None:
raise ValueError(f"Cannot read image at {image_path}")
with FaceLandmarkExtractor(min_detection_confidence=0.45) as extractor:
landmarks_array = extractor.extract(image_bgr)
if landmarks_array is None:
raise RuntimeError("No face detected in the uploaded image.")
regions = {}
for region, indices in REGION_INDICES.items():
valid = [i for i in indices if i < len(landmarks_array)]
regions[region] = landmarks_array[valid]
measurements = compute_measurements(landmarks_array)
# Draw annotated image
annotated = image_bgr.copy()
color_map = {
'nose': (0, 255, 0),
'eyes': (255, 0, 0),
'eyebrows': (0, 165, 255),
'chin': (0, 255, 255),
'jawline': (255, 255, 0),
'forehead': (255, 0, 255),
}
for region, coords in regions.items():
color = color_map.get(region, (200, 200, 200))
for pt in coords:
cv2.circle(annotated, (int(pt[0]), int(pt[1])), 2, color, -1)
for pt in landmarks_array:
cv2.circle(annotated, (int(pt[0]), int(pt[1])), 1, (180, 180, 180), -1)
annotated_filename = f'annotated_{uid}.png'
annotated_path = os.path.join(output_dir, annotated_filename)
cv2.imwrite(annotated_path, annotated)
return {
'landmarks_array': landmarks_array,
'regions': regions,
'measurements': measurements,
'annotated_image_path': annotated_path,
}