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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
| """ 驾驶员疲劳多模态检测系统 """
import numpy as np from typing import Dict, List, Tuple
class MultiModalFatigueDetector: """ 多模态疲劳检测器 检测维度: 1. 面部特征:EAR, MAR, 头部姿态 2. 身体姿态:肩部位置、脊柱角度、手部位置 3. 行为模式:打哈欠频率、眨眼频率、头部运动 """ def __init__(self): self.face_analyzer = FacialFeatureAnalyzer() self.pose_analyzer = BodyPoseAnalyzer() self.fusion = MultiModalFusion() self.ear_threshold = 0.2 self.mar_threshold = 0.6 self.head_pose_threshold = 30 def detect(self, frame: np.ndarray) -> Dict: """ 检测疲劳状态 Args: frame: 输入帧 (H, W, 3) Returns: result: 检测结果 """ face_features = self.face_analyzer.extract(frame) pose_features = self.pose_analyzer.extract(frame) fatigue_score = self.fusion.fuse( face_features, pose_features ) is_fatigued = fatigue_score > 0.7 fatigue_level = self.get_fatigue_level(fatigue_score) return { 'is_fatigued': is_fatigued, 'fatigue_score': fatigue_score, 'fatigue_level': fatigue_level, 'face_features': face_features, 'pose_features': pose_features } def get_fatigue_level(self, score: float) -> str: """获取疲劳等级""" if score < 0.4: return 'normal' elif score < 0.6: return 'mild' elif score < 0.8: return 'moderate' else: return 'severe'
class FacialFeatureAnalyzer: """面部特征分析器""" def extract(self, frame: np.ndarray) -> Dict: """ 提取面部特征 关键指标: - EAR: 眼睛开度比 - MAR: 嘴巴开度比 - 头部姿态(pitch, yaw, roll) - 眨眼频率 - 打哈欠频率 """ return { 'ear': 0.0, 'mar': 0.0, 'head_pose': (0.0, 0.0, 0.0), 'blink_rate': 0.0, 'yawn_rate': 0.0, 'eye_closure_duration': 0.0 } def calculate_ear(self, eye_landmarks: np.ndarray) -> float: """ 计算眼睛开度比 (Eye Aspect Ratio) EAR = (|p2-p6| + |p3-p5|) / (2 * |p1-p4|) Args: eye_landmarks: 眼睛关键点 (6, 2) Returns: ear: 眼睛开度比 [0, 1] """ v1 = np.linalg.norm(eye_landmarks[1] - eye_landmarks[5]) v2 = np.linalg.norm(eye_landmarks[2] - eye_landmarks[4]) h = np.linalg.norm(eye_landmarks[0] - eye_landmarks[3]) ear = (v1 + v2) / (2 * h + 1e-7) return ear def calculate_mar(self, mouth_landmarks: np.ndarray) -> float: """ 计算嘴巴开度比 (Mouth Aspect Ratio) MAR = (|p2-p8| + |p3-p7| + |p4-p6|) / (2 * |p1-p9|) Args: mouth_landmarks: 嘴巴关键点 (10, 2) Returns: mar: 嘴巴开度比 """ v1 = np.linalg.norm(mouth_landmarks[1] - mouth_landmarks[7]) v2 = np.linalg.norm(mouth_landmarks[2] - mouth_landmarks[6]) v3 = np.linalg.norm(mouth_landmarks[3] - mouth_landmarks[5]) h = np.linalg.norm(mouth_landmarks[0] - mouth_landmarks[8]) mar = (v1 + v2 + v3) / (2 * h + 1e-7) return mar def estimate_head_pose(self, landmarks: np.ndarray, camera_matrix: np.ndarray) -> Tuple[float, float, float]: """ 估计头部姿态 Args: landmarks: 面部关键点 (68, 2) camera_matrix: 相机内参矩阵 Returns: (pitch, yaw, roll): 欧拉角 (度) """ import cv2 model_points = np.array([ (0.0, 0.0, 0.0), (0.0, -330.0, -65.0), (-225.0, 170.0, -135.0), (225.0, 170.0, -135.0), (-150.0, -150.0, -125.0), (150.0, -150.0, -125.0) ], dtype=np.float64) image_points = np.array([ landmarks[30], landmarks[8], landmarks[36], landmarks[45], landmarks[48], landmarks[54] ], dtype=np.float64) dist_coeffs = np.zeros((4, 1)) success, rotation_vector, translation_vector = cv2.solvePnP( model_points, image_points, camera_matrix, dist_coeffs ) rotation_mat, _ = cv2.Rodrigues(rotation_vector) pitch = np.degrees(np.arcsin(-rotation_mat[2, 0])) yaw = np.degrees(np.arctan2(rotation_mat[2, 1], rotation_mat[2, 2])) roll = np.degrees(np.arctan2(rotation_mat[1, 0], rotation_mat[0, 0])) return (pitch, yaw, roll)
class BodyPoseAnalyzer: """身体姿态分析器""" def extract(self, frame: np.ndarray) -> Dict: """ 提取身体姿态特征 关键指标: - 肩部位置变化(下垂表示疲劳) - 脊柱角度(前倾表示疲劳) - 手部位置(离开方向盘) - 身体晃动频率 """ return { 'shoulder_drop': 0.0, 'spine_angle': 0.0, 'hand_position': 'on_wheel', 'body_sway_rate': 0.0, 'slouch_score': 0.0 } def calculate_shoulder_drop(self, shoulder_landmarks: np.ndarray, baseline: np.ndarray) -> float: """ 计算肩部下垂程度 Args: shoulder_landmarks: 肩部关键点 (左肩, 右肩) baseline: 基线肩部位置 Returns: drop: 下垂程度 (像素) """ current_center = np.mean(shoulder_landmarks, axis=0) baseline_center = np.mean(baseline, axis=0) drop = current_center[1] - baseline_center[1] return max(drop, 0) def calculate_spine_angle(self, spine_landmarks: np.ndarray) -> float: """ 计算脊柱角度 Args: spine_landmarks: 脊柱关键点 (多点和) Returns: angle: 脊柱角度 (度) """ if len(spine_landmarks) < 3: return 0.0 top = spine_landmarks[0] middle = spine_landmarks[len(spine_landmarks)//2] bottom = spine_landmarks[-1] v1 = middle - top v2 = bottom - middle cos_angle = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + 1e-7) angle = np.degrees(np.arccos(np.clip(cos_angle, -1, 1))) return angle
class MultiModalFusion: """多模态融合""" def __init__(self): self.weights = { 'ear': 0.30, 'mar': 0.15, 'head_pose': 0.20, 'blink_rate': 0.15, 'shoulder_drop': 0.10, 'spine_angle': 0.10 } def fuse(self, face_features: Dict, pose_features: Dict) -> float: """ 融合多模态特征 Args: face_features: 面部特征 pose_features: 姿态特征 Returns: fatigue_score: 疲劳评分 [0, 1] """ score = 0.0 ear = face_features.get('ear', 0.5) ear_score = self.normalize_ear(ear) score += self.weights['ear'] * ear_score mar = face_features.get('mar', 0.0) mar_score = self.normalize_mar(mar) score += self.weights['mar'] * mar_score head_pose = face_features.get('head_pose', (0, 0, 0)) pose_score = self.normalize_head_pose(head_pose) score += self.weights['head_pose'] * pose_score blink_rate = face_features.get('blink_rate', 15) blink_score = self.normalize_blink_rate(blink_rate) score += self.weights['blink_rate'] * blink_score shoulder_drop = pose_features.get('shoulder_drop', 0) shoulder_score = self.normalize_shoulder_drop(shoulder_drop) score += self.weights['shoulder_drop'] * shoulder_score spine_angle = pose_features.get('spine_angle', 180) spine_score = self.normalize_spine_angle(spine_angle) score += self.weights['spine_angle'] * spine_score return np.clip(score, 0, 1) def normalize_ear(self, ear: float) -> float: """归一化EAR""" if ear < 0.2: return 1.0 elif ear < 0.3: return 0.5 else: return 0.0 def normalize_mar(self, mar: float) -> float: """归一化MAR""" if mar > 0.6: return 1.0 elif mar > 0.4: return 0.5 else: return 0.0 def normalize_head_pose(self, pose: Tuple[float, float, float]) -> float: """归一化头部姿态""" pitch, yaw, roll = pose pitch_score = min(abs(pitch) / 30, 1.0) yaw_score = min(abs(yaw) / 45, 1.0) roll_score = min(abs(roll) / 20, 1.0) return (pitch_score + yaw_score + roll_score) / 3 def normalize_blink_rate(self, rate: float) -> float: """归一化眨眼频率""" if rate > 25 or rate < 5: return 1.0 elif rate > 20 or rate < 8: return 0.5 else: return 0.0 def normalize_shoulder_drop(self, drop: float) -> float: """归一化肩部下垂""" return min(drop / 20, 1.0) def normalize_spine_angle(self, angle: float) -> float: """归一化脊柱角度""" if angle < 160: return 1.0 elif angle < 170: return 0.5 else: return 0.0
if __name__ == "__main__": detector = MultiModalFatigueDetector() frame = np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8) result = detector.detect(frame) print(f"疲劳评分: {result['fatigue_score']:.2f}") print(f"疲劳等级: {result['fatigue_level']}") print(f"是否疲劳: {'是' if result['is_fatigued'] else '否'}")
|