Spaces:
Runtime error
Runtime error
Create mar_calculator.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""Mouth Aspect Ratio (MAR) Calculator Module
Similar concept to EAR but applied to the mouth for yawning detection.
MAR = (sum of vertical distances) / (horizontal distance)
A high MAR indicates the mouth is wide open (potential yawning).Normal speaking produces moderate MAR values.Yawning produces sustained high MAR values."""
import numpy as npfrom scipy.spatial import distance as distfrom typing import Tuplefrom collections import deque
class MARCalculator: """ Calculates Mouth Aspect Ratio for yawning detection. Uses multiple vertical mouth landmarks for robust detection. """
# Default threshold above which mouth is considered wide open (yawning) DEFAULT_THRESHOLD = 0.75
# Smoothing window for temporal averaging SMOOTHING_WINDOW = 5
# Minimum consecutive frames of high MAR to confirm yawning # (prevents false positives from talking) MIN_YAWN_FRAMES = 8
def __init__(self, threshold: float = DEFAULT_THRESHOLD): """ Initialize the MAR calculator.
Args: threshold: MAR value above which mouth is considered in yawn position """ self.threshold = threshold self._mar_history = deque(maxlen=self.SMOOTHING_WINDOW) self._yawn_frame_count = 0
@staticmethod def compute_mar(mouth_landmarks: np.ndarray) -> float: """ Compute the Mouth Aspect Ratio.
Mouth landmarks (8 points from our detector): [0] = Top lip center (13) [1] = Bottom lip center (14) [2] = Upper inner left (82) [3] = Upper inner right (312) [4] = Lower inner left (87) [5] = Lower inner right (317) [6] = Left corner (78) [7] = Right corner (308)
Args: mouth_landmarks: numpy array of shape (8, 2)
Returns: Float MAR value """ # Vertical distances # Distance between top and bottom lip centers vertical_1 = dist.euclidean(mouth_landmarks[0], mouth_landmarks[1])
# Distance between upper-inner-left and lower-inner-left vertical_2 = dist.euclidean(mouth_landmarks[2], mouth_landmarks[4])
# Distance between upper-inner-right and lower-inner-right vertical_3 = dist.euclidean(mouth_landmarks[3], mouth_landmarks[5])
# Horizontal distance (mouth width) horizontal = dist.euclidean(mouth_landmarks[6], mouth_landmarks[7])
# Avoid division by zero if horizontal == 0: return 0.0
# Calculate MAR: average of vertical distances / horizontal distance mar = (vertical_1 + vertical_2 + vertical_3) / (2.0 * horizontal)
return mar
def calculate(self, mouth_landmarks: np.ndarray) -> Tuple[float, bool]: """ Calculate MAR with smoothing and yawn confirmation.
Args: mouth_landmarks: Mouth landmarks array (8, 2)
Returns: Tuple of (smoothed_mar, is_yawning) """ # Calculate raw MAR raw_mar = self.compute_mar(mouth_landmarks)
# Add to smoothing buffer self._mar_history.append(raw_mar)
# Calculate smoothed MAR smoothed_mar = np.mean(self._mar_history)
# Track consecutive high-MAR frames for yawn confirmation if smoothed_mar > self.threshold: self._yawn_frame_count += 1 else: self._yawn_frame_count = 0
# Only confirm yawning if MAR has been high for enough frames # This distinguishes yawning from normal talking is_yawning = self._yawn_frame_count >= self.MIN_YAWN_FRAMES
return smoothed_mar, is_yawning
def reset(self): """Reset the MAR history and yawn counter.""" self._mar_history.clear() self._yawn_frame_count = 0utils/mar_calculator.pyAdded+123