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
| import numpy as np from typing import Dict, List
class AlcoholImpairmentDetector: """ 酒精损伤视觉检测 研究依据: - 酒精导致眼动平滑度下降 - 扫视(Saccade)峰值速度降低 - 眨眼频率和模式改变 - 瞳孔对光反射延迟 """ def __init__(self): self.thresholds = { 'saccade_velocity': 300, 'saccade_latency': 250, 'blink_rate': 25, 'blink_duration': 300, 'pupil_response_delay': 600, 'gaze_instability': 5, } def extract_eye_features(self, gaze_data: np.ndarray) -> Dict: """ 提取眼动特征 Args: gaze_data: (N, 4) 时间序列 [timestamp, x, y, pupil_diameter] Returns: features: 眼动特征字典 """ timestamps = gaze_data[:, 0] gaze_x = gaze_data[:, 1] gaze_y = gaze_data[:, 2] pupil = gaze_data[:, 3] features = {} saccades = self._detect_saccades(gaze_x, gaze_y, timestamps) if len(saccades) > 0: features['saccade_velocity'] = np.mean([s['velocity'] for s in saccades]) features['saccade_latency'] = np.mean([s['latency'] for s in saccades]) else: features['saccade_velocity'] = 400 features['saccade_latency'] = 180 blinks = self._detect_blinks(pupil, timestamps) if len(blinks) > 0: blink_intervals = np.diff([b['start'] for b in blinks]) features['blink_rate'] = 60000 / np.mean(blink_intervals) features['blink_duration'] = np.mean([b['duration'] for b in blinks]) else: features['blink_rate'] = 12 features['blink_duration'] = 150 features['gaze_instability'] = self._calculate_gaze_instability(gaze_x, gaze_y) features['pupil_response_delay'] = 400 return features def _detect_saccades(self, gaze_x, gaze_y, timestamps, velocity_threshold=30) -> List[Dict]: """ 检测扫视事件 Args: gaze_x, gaze_y: 视线坐标序列 timestamps: 时间戳 velocity_threshold: 速度阈值 °/s Returns: saccades: 扫视事件列表 """ dt = np.diff(timestamps) / 1000 dx = np.diff(gaze_x) dy = np.diff(gaze_y) velocity = np.sqrt(dx**2 + dy**2) / dt saccades = [] in_saccade = False saccade_start = 0 for i, v in enumerate(velocity): if v > velocity_threshold and not in_saccade: in_saccade = True saccade_start = i elif v < velocity_threshold and in_saccade: in_saccade = False saccade_end = i saccade = { 'start_time': timestamps[saccade_start], 'end_time': timestamps[saccade_end], 'velocity': np.max(velocity[saccade_start:saccade_end]), 'amplitude': np.sqrt( (gaze_x[saccade_end] - gaze_x[saccade_start])**2 + (gaze_y[saccade_end] - gaze_y[saccade_start])**2 ), 'latency': 200 } saccades.append(saccade) return saccades def _detect_blinks(self, pupil, timestamps, closure_threshold=0.3) -> List[Dict]: """ 检测眨眼事件 Args: pupil: 瞳孔直径序列 timestamps: 时间戳 closure_threshold: 闭眼阈值(相对于基线) Returns: blinks: 眨眼事件列表 """ baseline = np.median(pupil) closed = pupil < baseline * closure_threshold blinks = [] in_blink = False blink_start = 0 for i, c in enumerate(closed): if c and not in_blink: in_blink = True blink_start = i elif not c and in_blink: in_blink = False blink = { 'start': timestamps[blink_start], 'end': timestamps[i], 'duration': timestamps[i] - timestamps[blink_start] } blinks.append(blink) return blinks def _calculate_gaze_instability(self, gaze_x, gaze_y, window_sec=5, fps=30) -> float: """ 计算视线不稳定性 醉酒驾驶员视线抖动增加 """ window = int(window_sec * fps) instabilities = [] for i in range(len(gaze_x) - window): x_window = gaze_x[i:i+window] y_window = gaze_y[i:i+window] instability = np.sqrt(np.std(x_window)**2 + np.std(y_window)**2) instabilities.append(instability) return np.mean(instabilities) if instabilities else 2.0 def assess_impairment(self, features: Dict) -> Dict: """ 评估酒精损伤程度 Args: features: 眼动特征字典 Returns: assessment: { 'impairment_level': 'none/mild/moderate/severe', 'confidence': float, 'estimated_bac': float, 'warning': str } """ deviations = [] if features.get('saccade_velocity', 400) < self.thresholds['saccade_velocity']: deviations.append(('saccade_velocity', (self.thresholds['saccade_velocity'] - features['saccade_velocity']) / 400)) if features.get('blink_rate', 12) > self.thresholds['blink_rate']: deviations.append(('blink_rate', (features['blink_rate'] - 15) / 15)) if features.get('blink_duration', 150) > self.thresholds['blink_duration']: deviations.append(('blink_duration', (features['blink_duration'] - 150) / 150)) if features.get('gaze_instability', 2) > self.thresholds['gaze_instability']: deviations.append(('gaze_instability', (features['gaze_instability'] - 3) / 3)) if len(deviations) == 0: return { 'impairment_level': 'none', 'confidence': 0.9, 'estimated_bac': 0.0, 'warning': None } avg_deviation = np.mean([d[1] for d in deviations]) if avg_deviation < 0.2: impairment = 'none' estimated_bac = 0.02 elif avg_deviation < 0.4: impairment = 'mild' estimated_bac = 0.05 elif avg_deviation < 0.6: impairment = 'moderate' estimated_bac = 0.10 else: impairment = 'severe' estimated_bac = 0.15 return { 'impairment_level': impairment, 'confidence': min(0.95, 0.6 + avg_deviation), 'estimated_bac': estimated_bac, 'warning': f"检测到酒精损伤特征,估计BAC: {estimated_bac:.2f} g/dL" }
class DMSAlcoholDetection: """ DMS酒精检测完整流程 集成到现有DMS系统: 1. 实时眼动追踪 2. 特征提取 3. 酒精损伤评估 4. 警告输出 """ def __init__(self): self.detector = AlcoholImpairmentDetector() self.gaze_buffer = [] self.buffer_size = 300 def process_frame(self, frame_data: Dict) -> Dict: """ 处理单帧数据 Args: frame_data: { 'timestamp': float, 'gaze_x': float, 'gaze_y': float, 'pupil_diameter': float, 'eye_openness': float } Returns: result: 检测结果 """ self.gaze_buffer.append([ frame_data['timestamp'], frame_data['gaze_x'], frame_data['gaze_y'], frame_data['pupil_diameter'] ]) if len(self.gaze_buffer) > self.buffer_size: self.gaze_buffer.pop(0) if len(self.gaze_buffer) < self.buffer_size // 2: return { 'status': 'collecting', 'impairment_level': 'unknown' } gaze_array = np.array(self.gaze_buffer) features = self.detector.extract_eye_features(gaze_array) assessment = self.detector.assess_impairment(features) return { 'status': 'active', 'features': features, **assessment }
if __name__ == "__main__": np.random.seed(42) timestamps = np.linspace(0, 10000, 300) normal_gaze_x = 0.5 + 0.02 * np.random.randn(300) normal_gaze_y = 0.5 + 0.02 * np.random.randn(300) normal_pupil = 4.0 + 0.1 * np.random.randn(300) drunk_gaze_x = 0.5 + 0.08 * np.random.randn(300) drunk_gaze_y = 0.5 + 0.08 * np.random.randn(300) drunk_pupil = 4.0 + 0.2 * np.random.randn(300) for i in range(10, 290, 15): drunk_pupil[i:i+8] = 0.5 for i in range(10, 290, 30): normal_pupil[i:i+5] = 0.5 detector = AlcoholImpairmentDetector() print("=" * 60) print("正常驾驶员检测") print("=" * 60) normal_data = np.column_stack([timestamps, normal_gaze_x, normal_gaze_y, normal_pupil]) normal_features = detector.extract_eye_features(normal_data) normal_assessment = detector.assess_impairment(normal_features) print(f"特征: {normal_features}") print(f"评估: {normal_assessment}") print("\n" + "=" * 60) print("醉酒驾驶员检测") print("=" * 60) drunk_data = np.column_stack([timestamps, drunk_gaze_x, drunk_gaze_y, drunk_pupil]) drunk_features = detector.extract_eye_features(drunk_data) drunk_assessment = detector.assess_impairment(drunk_features) print(f"特征: {drunk_features}") print(f"评估: {drunk_assessment}")
|