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
| import numpy as np import torch from typing import List, Dict, Tuple
class RMDDVisualModule: """ RMDD 视觉模块: YOLO26 + 面部关键点 架构: 1. YOLO26 人体/面部检测 2. 面部关键点提取 (98点) 3. 状态分类 (疲劳/分心/情绪) 参考: RMDD, Electronics 2026 硬件: Raspberry Pi 5 (8GB RAM) """ def __init__(self, config: dict = None): config = config or {} self.device = config.get('device', 'cpu') self.input_size = config.get('input_size', 640) self.confidence_threshold = config.get('confidence', 0.5) self.yolo_model_path = config.get('yolo_path', 'yolo26n.pt') self.state_classifier = self._init_state_classifier() self.face_landmarks = { 'left_eye': [33, 7, 163, 144, 145, 153, 154, 155, 133], 'right_eye': [362, 382, 381, 380, 374, 373, 390, 249, 263], 'mouth': [61, 291, 0, 17, 13, 14, 87, 178], 'head_pose_ref': [1, 168, 197, 5, 4], } def detect_and_analyze(self, frame: np.ndarray) -> Dict: """ 完整视觉分析流水线 Args: frame: RGB 图像, shape=(H, W, 3) Returns: analysis: 检测结果和状态评估 """ detections = self._yolo_detect(frame) if detections['face'] is None: return { 'face_detected': False, 'state': 'unknown', 'confidence': 0.0, } landmarks = self._extract_landmarks(frame, detections['face']) features = self._compute_features(landmarks) state = self.state_classifier(features) return { 'face_detected': True, 'bbox': detections['face'], 'landmarks': landmarks, 'features': features, 'state': state['label'], 'confidence': state['confidence'], 'gaze_direction': features['gaze'], 'head_pose': features['head_pose'], 'eye_openness': features['ear'], 'mouth_state': features['mouth_open'], } def _compute_features(self, landmarks: np.ndarray) -> Dict: """从关键点计算面部特征""" left_ear = self._compute_ear(landmarks[self.face_landmarks['left_eye']]) right_ear = self._compute_ear(landmarks[self.face_landmarks['right_eye']]) mouth_points = landmarks[self.face_landmarks['mouth']] mar = self._compute_mar(mouth_points) head_pose = self._estimate_head_pose( landmarks[self.face_landmarks['head_pose_ref']] ) gaze = self._estimate_gaze( landmarks[self.face_landmarks['left_eye']], landmarks[self.face_landmarks['right_eye']], head_pose, ) return { 'ear': (left_ear + right_ear) / 2, 'ear_left': left_ear, 'ear_right': right_ear, 'mar': mar, 'head_pose': head_pose, 'gaze': gaze, 'mouth_open': mar > 0.5, } def _compute_ear(self, eye_points: np.ndarray) -> float: """ 眼睛纵横比 (Eye Aspect Ratio) EAR = (|p2-p6| + |p3-p5|) / (2 * |p1-p4|) """ vertical_1 = np.linalg.norm(eye_points[1] - eye_points[5]) vertical_2 = np.linalg.norm(eye_points[2] - eye_points[4]) horizontal = np.linalg.norm(eye_points[0] - eye_points[3]) if horizontal == 0: return 0 return (vertical_1 + vertical_2) / (2.0 * horizontal) def _compute_mar(self, mouth_points: np.ndarray) -> float: """嘴部纵横比 (Mouth Aspect Ratio)""" vertical = np.linalg.norm(mouth_points[2] - mouth_points[3]) horizontal = np.linalg.norm(mouth_points[0] - mouth_points[1]) if horizontal == 0: return 0 return vertical / horizontal def _estimate_head_pose(self, ref_points: np.ndarray) -> Tuple[float, float, float]: """ 头部姿态估计 (Pitch, Yaw, Roll) Returns: (pitch, yaw, roll) in degrees """ pitch = np.arctan2( ref_points[2][1] - ref_points[0][1], ref_points[2][2] - ref_points[0][2] ) * 180 / np.pi yaw = np.arctan2( ref_points[1][0] - ref_points[0][0], ref_points[1][2] - ref_points[0][2] ) * 180 / np.pi roll = np.arctan2( ref_points[1][1] - ref_points[0][1], ref_points[1][0] - ref_points[0][0] ) * 180 / np.pi return (pitch, yaw, roll) def _estimate_gaze(self, left_eye, right_eye, head_pose): """简化视线方向估计""" yaw = head_pose[1] pitch = head_pose[0] return {'yaw': yaw, 'pitch': pitch, 'direction': self._gaze_zone(yaw, pitch)} def _gaze_zone(self, yaw, pitch): if abs(yaw) < 15 and abs(pitch) < 15: return 'forward' elif yaw > 15: return 'right' elif yaw < -15: return 'left' elif pitch > 15: return 'down' else: return 'up' def _init_state_classifier(self): """初始化状态分类器""" class StateClassifier: def __call__(self, features): ear = features['ear'] mar = features['mar'] gaze = features['gaze'] head_pose = features['head_pose'] if ear < 0.2: return {'label': 'drowsy', 'confidence': 0.85} elif gaze['direction'] != 'forward': return {'label': 'distracted', 'confidence': 0.75} elif mar > 0.5: return {'label': 'yawning', 'confidence': 0.70} elif abs(head_pose[1]) > 25: return {'label': 'distracted', 'confidence': 0.65} else: return {'label': 'normal', 'confidence': 0.90} return StateClassifier() def _yolo_detect(self, frame): """YOLO26 检测(模拟接口)""" return { 'face': [100, 100, 300, 400], 'body': [50, 50, 400, 600], }
if __name__ == "__main__": module = RMDDVisualModule() frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = module.detect_and_analyze(frame) print("=== RMDD 视觉模块测试 ===") print(f"面部检测: {result['face_detected']}") print(f"状态: {result.get('state', 'N/A')}") print(f"置信度: {result.get('confidence', 0):.2%}") print(f"EAR: {result.get('eye_openness', 0):.3f}") print(f"头部姿态: {result.get('head_pose', 'N/A')}") print(f"视线方向: {result.get('gaze_direction', 'N/A')}")
|