Detect faces with MediaPipe Face Mesh instead of just bounding boxes. Overlay the 468 facial landmarks in real-time on a webcam stream and implement blink detection by calculating the aspect ratio of eye landmarks.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing real-time MediaPipe Face Mesh with blink detection
Here is Python code using OpenCV and MediaPipe Face Mesh to overlay 468 facial landmarks on webcam frames and detect blinks via Eye Aspect Ratio computed from specific eye landmarks. It includes drawing landmarks, computing EAR, and counting blinks with a threshold and consecutive frame logic.
Below is a minimal example in Python that uses MediaPipe Face Mesh to track 468 facial landmarks on a webcam stream, render them in real time, and implement blink detection via the eye aspect ratio (EAR). The key steps are:
Capture frames from the webcam.
Run the MediaPipe Face Mesh model.
Compute the EAR from specific eye landmarks.
Detect blinks when EAR drops below a threshold for a few consecutive frames.
Overlay landmarks and blink count on the output.
python
import cv2
import numpy as np
import mediapipe as mp
# Initialize webcam
cap = cv2.VideoCapture(0)
mp_face_mesh = mp.solutions.face_mesh
mp_drawing = mp.solutions.drawing_utils
# Use refine_landmarks=True for extra iris landmarks (optional but improves eye alignment)
face_mesh = mp_face_mesh.FaceMesh(
max_num_faces=1,
refine_landmarks=True,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
# Indices for eye landmarks (p1..p6) to compute EAR
# These come from the 468-point MediaPipe Face Mesh.
LEFT_EYE = [33, 160, 158, 133, 153, 144] # p1, p2, p3, p4, p5, p6
RIGHT_EYE = [362, 385, 387, 263, 373, 380] # p1, p2, p3, p4, p5, p6
def eye_aspect_ratio(landmarks, eye_indices, frame_w, frame_h):
"""Compute eye aspect ratio (EAR) from 6 eye landmarks."""
coords = [(int(landmarks[i].x * frame_w), int(landmarks[i].y * frame_h)) for i in eye_indices]
p1, p2, p3, p4, p5, p6 = coords
# Euclidean distances
def euclid_dist(pA, pB):
return np.linalg.norm(np.array(pA) - np.array(pB))
# EAR formula
ear = (euclid_dist(p2, p6) + euclid_dist(p3, p5)) / (2.0 * euclid_dist(p1, p4))
return ear
# Thresholds for blink detection
EAR_THRESHOLD = 0.23 # Adjust if needed
CONSEC_FRAMES = 3 # Minimum consecutive frames with EAR below threshold to register a blink
blink_count = 0
frame_counter = 0 # Counts consecutive frames under EAR threshold
while cap.isOpened():
success, frame = cap.read()
if not success:
break
# Flip frame horizontally for a selfie-view display
frame = cv2.flip(frame, 1)
h, w, _ = frame.shape
# Convert BGR to RGB for MediaPipe
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = face_mesh.process(rgb_frame)
if results.multi_face_landmarks:
# We only track the first face here, adjust as needed
face_landmarks = results.multi_face_landmarks[0]
# Draw all 468 landmarks
mp_drawing.draw_landmarks(
image=frame,
landmark_list=face_landmarks,
connections=mp_face_mesh.FACEMESH_TESSELATION, # or FACEMESH_CONTOURS
landmark_drawing_spec=mp_drawing.DrawingSpec(
color=(0, 255, 0), thickness=1, circle_radius=1
),
connection_drawing_spec=mp_drawing.DrawingSpec(
color=(0, 0, 255), thickness=1, circle_radius=1
)
)
# Compute EAR for left and right eye
landmarks = face_landmarks.landmark
ear_left = eye_aspect_ratio(landmarks, LEFT_EYE, w, h)
ear_right = eye_aspect_ratio(landmarks, RIGHT_EYE, w, h)
ear = (ear_left + ear_right) / 2.0
# Blink detection logic
if ear < EAR_THRESHOLD:
frame_counter += 1
else:
if frame_counter >= CONSEC_FRAMES:
blink_count += 1
frame_counter = 0
# Draw a small circle around eye landmarks used for EAR
for idx in LEFT_EYE + RIGHT_EYE:
x = int(landmarks[idx].x * w)
y = int(landmarks[idx].y * h)
cv2.circle(frame, (x, y), 2, (255, 0, 0), -1)
# Display EAR and blink count
cv2.putText(frame, f"EAR: {ear:.2f}", (30, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(frame, f"Blinks: {blink_count}", (30, 70),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
cv2.imshow("MediaPipe Face Mesh - Blink Detection", frame)
if cv2.waitKey(1) & 0xFF == 27: # Press 'ESC' to quit
break
cap.release()
cv2.destroyAllWindows()
Notes/Tips:
Install dependencies with pip install opencv-python mediapipe.
Adjust EAR_THRESHOLD and CONSEC_FRAMES for your camera and lighting. Typical EAR thresholds are around 0.20–0.25, but you may need to tune.
If you experience performance issues, lower the frame resolution or reduce the number of drawn connections (e.g., use FACEMESH_CONTOURS instead of full FACEMESH_TESSELATION).