1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
| import numpy as np import cv2 from typing import Tuple, Dict from dataclasses import dataclass
@dataclass class EyeLandmarks: """眼部关键点""" left_eye: np.ndarray right_eye: np.ndarray
class PERCLOSCalculator: """PERCLOS计算器""" def __init__(self, window_size: int = 1800): """ Args: window_size: 滑动窗口大小(帧数) 30fps × 60秒 = 1800帧 """ self.window_size = window_size self.eye_closure_history = [] self.ear_threshold = 0.2 def calculate_ear(self, eye_landmarks: np.ndarray) -> float: """ 计算Eye Aspect Ratio (EAR) Args: eye_landmarks: (6, 2) 眼部关键点 P0: 左角, P1: 上眼睑左 P2: 上眼睑右, P3: 右角 P4: 下眼睑右, P5: 下眼睑左 Returns: ear: 眼睛纵横比 """ vertical_1 = np.linalg.norm(eye_landmarks[1] - eye_landmarks[5]) vertical_2 = np.linalg.norm(eye_landmarks[2] - eye_landmarks[4]) horizontal = np.linalg.norm(eye_landmarks[0] - eye_landmarks[3]) if horizontal > 0: ear = (vertical_1 + vertical_2) / (2.0 * horizontal) else: ear = 0.0 return ear def is_eye_closed(self, left_ear: float, right_ear: float) -> bool: """ 判定眼睛是否闭合 Args: left_ear: 左眼EAR right_ear: 右眼EAR Returns: is_closed: 是否闭合 """ avg_ear = (left_ear + right_ear) / 2.0 return avg_ear < self.ear_threshold def calculate_perclos(self) -> float: """ 计算PERCLOS值 Returns: perclos: 百分比(0-100) """ if len(self.eye_closure_history) == 0: return 0.0 window = self.eye_closure_history[-self.window_size:] closed_count = sum(window) perclos = closed_count / len(window) * 100.0 return perclos def update(self, is_closed: bool) -> float: """ 更新历史记录并返回PERCLOS Args: is_closed: 当前帧是否闭眼 Returns: perclos: 当前PERCLOS值 """ self.eye_closure_history.append(1 if is_closed else 0) if len(self.eye_closure_history) > self.window_size * 2: self.eye_closure_history = self.eye_closure_history[-self.window_size:] return self.calculate_perclos()
class FatigueDetector: """疲劳检测器""" def __init__(self): self.perclos_calculator = PERCLOSCalculator() self.thresholds = { 'alert': 15.0, 'warning': 30.0, 'critical': 50.0 } def detect(self, eye_landmarks: EyeLandmarks) -> Dict: """ 检测疲劳状态 Args: eye_landmarks: 眼部关键点 Returns: result: 检测结果 """ left_ear = self.perclos_calculator.calculate_ear(eye_landmarks.left_eye) right_ear = self.perclos_calculator.calculate_ear(eye_landmarks.right_eye) is_closed = self.perclos_calculator.is_eye_closed(left_ear, right_ear) perclos = self.perclos_calculator.update(is_closed) if perclos >= self.thresholds['critical']: fatigue_level = 'critical' warning_level = 3 elif perclos >= self.thresholds['warning']: fatigue_level = 'warning' warning_level = 2 elif perclos >= self.thresholds['alert']: fatigue_level = 'alert' warning_level = 1 else: fatigue_level = 'normal' warning_level = 0 return { 'perclos': perclos, 'ear': {'left': left_ear, 'right': right_ear}, 'is_closed': is_closed, 'fatigue_level': fatigue_level, 'warning_level': warning_level }
class RealTimeFatiguePipeline: """实时疲劳检测管道""" def __init__(self): self.detector = FatigueDetector() self.landmark_detector = None def process_frame(self, frame: np.ndarray) -> Dict: """ 处理单帧 Args: frame: (H, W, 3) BGR图像 Returns: result: 检测结果 """ landmarks = self._detect_landmarks(frame) if landmarks is None: return {'success': False, 'message': 'No face detected'} eye_landmarks = self._extract_eye_landmarks(landmarks) fatigue_result = self.detector.detect(eye_landmarks) warning = self._generate_warning(fatigue_result) return { 'success': True, 'fatigue': fatigue_result, 'warning': warning } def _detect_landmarks(self, frame: np.ndarray) -> np.ndarray: """检测面部关键点""" return np.random.rand(68, 2) * np.array([frame.shape[1], frame.shape[0]]) def _extract_eye_landmarks(self, landmarks: np.ndarray) -> EyeLandmarks: """提取眼部关键点""" left_eye = landmarks[36:42] right_eye = landmarks[42:48] return EyeLandmarks(left_eye=left_eye, right_eye=right_eye) def _generate_warning(self, fatigue_result: Dict) -> str: """生成警告信息""" level = fatigue_result['warning_level'] if level == 0: return "状态正常" elif level == 1: return "轻度疲劳,建议休息" elif level == 2: return "中度疲劳,请立即休息" elif level == 3: return "重度疲劳,紧急停车!" return ""
if __name__ == "__main__": pipeline = RealTimeFatiguePipeline() for i in range(900): frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = pipeline.process_frame(frame) if i % 300 == 0: print(f"帧 {i}: PERCLOS={result['fatigue']['perclos']:.1f}%, " f"疲劳等级={result['fatigue']['fatigue_level']}")
|