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
| import numpy as np from dataclasses import dataclass from typing import Optional, Tuple from collections import deque import warnings
@dataclass class CognitiveDistractionConfig: """认知分心检测配置""" window_size_sec: float = 30.0 fps: int = 25 prc_threshold_low: float = 60.0 prc_threshold_high: float = 85.0 h_dispersion_threshold: float = 8.0 v_dispersion_threshold: float = 5.0 sge_threshold: float = 3.5 gte_threshold: float = 2.8 baseline_update_rate: float = 0.01 baseline_window_sec: float = 300.0 distraction_duration_threshold: float = 20.0 warning_cooldown_sec: float = 60.0
class CognitiveDistractionDetector: """ 认知分心检测器 基于 Gaze Entropy + PRC + Dispersion 多指标融合 Reference: - Halin et al. (2025) AutomotiveUI - "Gaze-Based Indicators of Driver Cognitive Distraction" - Victor et al. (2005) - "Sensitivity of eye-movement measures" - Pillai et al. (2022) - "Eye-Gaze Metrics for Cognitive Load" """ def __init__(self, config: Optional[CognitiveDistractionConfig] = None): self.config = config or CognitiveDistractionConfig() window_size = int(self.config.window_size_sec * self.config.fps) self.gaze_buffer = deque(maxlen=window_size) self.timestamp_buffer = deque(maxlen=window_size) self.baseline_window = int(self.config.baseline_window_sec * self.config.fps) self.baseline_gaze = deque(maxlen=self.baseline_window) self.baseline_stats = { 'prc_mean': 75.0, 'prc_std': 10.0, 'h_disp_mean': 5.0, 'v_disp_mean': 3.0, 'sge_mean': 3.0, 'gte_mean': 2.5 } self.distraction_start_time: Optional[float] = None self.last_warning_time: Optional[float] = None self.current_state = "normal" def update( self, gaze_angle: Tuple[float, float], timestamp: float ) -> dict: """ 更新眼动数据并检测认知分心 Args: gaze_angle: 当前视线角度 (horizontal, vertical),单位:度 timestamp: 当前时间戳(秒) Returns: result: 检测结果字典 Example: >>> detector = CognitiveDistractionDetector() >>> for i in range(1000): ... angle = (np.random.randn() * 5, np.random.randn() * 3) ... result = detector.update(angle, i / 25.0) ... if result['is_distracted']: ... print(f"检测到认知分心: {result['confidence']:.2f}") """ self.gaze_buffer.append(gaze_angle) self.timestamp_buffer.append(timestamp) self.baseline_gaze.append(gaze_angle) if len(self.gaze_buffer) < self.config.fps * 5: return self._create_result(False, 0.0, "数据不足") gaze_array = np.array(list(self.gaze_buffer)) prc = calculate_percent_road_center(gaze_array) h_disp, v_disp = calculate_gaze_dispersion(gaze_array) sge = calculate_stationary_gaze_entropy( self._normalize_angles(gaze_array), grid_size=(8, 6) ) gte = calculate_gaze_transition_entropy( self._normalize_angles(gaze_array), grid_size=(8, 6) ) self._update_baseline() is_distracted, confidence, indicators = self._detect_distraction( prc, h_disp, v_disp, sge, gte ) self._update_state(is_distracted, timestamp) should_warn = self._should_warn(is_distracted, timestamp) return self._create_result( is_distracted=is_distracted, confidence=confidence, state=self.current_state, indicators=indicators, should_warn=should_warn, prc=prc, h_disp=h_disp, v_disp=v_disp, sge=sge, gte=gte ) def _normalize_angles(self, angles: np.ndarray) -> np.ndarray: """归一化角度到 [0, 1]""" normalized = np.zeros_like(angles) normalized[:, 0] = (angles[:, 0] + 50) / 100 normalized[:, 1] = (angles[:, 1] + 30) / 60 return np.clip(normalized, 0, 1) def _update_baseline(self): """更新个体基线统计""" if len(self.baseline_gaze) < self.config.fps * 60: return gaze_array = np.array(list(self.baseline_gaze)) prc = calculate_percent_road_center(gaze_array) h_disp, v_disp = calculate_gaze_dispersion(gaze_array) sge = calculate_stationary_gaze_entropy( self._normalize_angles(gaze_array), grid_size=(8, 6) ) gte = calculate_gaze_transition_entropy( self._normalize_angles(gaze_array), grid_size=(8, 6) ) alpha = self.config.baseline_update_rate self.baseline_stats['prc_mean'] = ( (1 - alpha) * self.baseline_stats['prc_mean'] + alpha * prc ) self.baseline_stats['h_disp_mean'] = ( (1 - alpha) * self.baseline_stats['h_disp_mean'] + alpha * h_disp ) self.baseline_stats['v_disp_mean'] = ( (1 - alpha) * self.baseline_stats['v_disp_mean'] + alpha * v_disp ) self.baseline_stats['sge_mean'] = ( (1 - alpha) * self.baseline_stats['sge_mean'] + alpha * sge ) self.baseline_stats['gte_mean'] = ( (1 - alpha) * self.baseline_stats['gte_mean'] + alpha * gte ) def _detect_distraction( self, prc: float, h_disp: float, v_disp: float, sge: float, gte: float ) -> Tuple[bool, float, dict]: """ 多指标融合判断认知分心 Returns: is_distracted: 是否分心 confidence: 置信度 [0, 1] indicators: 各指标状态 """ indicators = {} scores = [] prc_zscore = (prc - self.baseline_stats['prc_mean']) / max(self.baseline_stats['prc_std'], 1.0) if prc < self.baseline_stats['prc_mean'] - 2 * self.baseline_stats['prc_std']: indicators['prc'] = 'low' scores.append(1.0) elif prc < self.baseline_stats['prc_mean'] - self.baseline_stats['prc_std']: indicators['prc'] = 'moderate_low' scores.append(0.5) else: indicators['prc'] = 'normal' scores.append(0.0) if v_disp > self.baseline_stats['v_disp_mean'] * 1.5: indicators['v_disp'] = 'high' scores.append(1.0) elif v_disp > self.baseline_stats['v_disp_mean'] * 1.2: indicators['v_disp'] = 'moderate_high' scores.append(0.5) else: indicators['v_disp'] = 'normal' scores.append(0.0) if sge > self.baseline_stats['sge_mean'] * 1.3: indicators['sge'] = 'high' scores.append(1.0) elif sge > self.baseline_stats['sge_mean'] * 1.15: indicators['sge'] = 'moderate_high' scores.append(0.5) else: indicators['sge'] = 'normal' scores.append(0.0) if gte > self.baseline_stats['gte_mean'] * 1.3: indicators['gte'] = 'high' scores.append(1.0) elif gte > self.baseline_stats['gte_mean'] * 1.15: indicators['gte'] = 'moderate_high' scores.append(0.5) else: indicators['gte'] = 'normal' scores.append(0.0) confidence = np.mean(scores) is_distracted = confidence >= 0.5 return is_distracted, confidence, indicators def _update_state(self, is_distracted: bool, timestamp: float): """更新状态机""" if is_distracted: if self.current_state == "normal": self.current_state = "potential_distraction" self.distraction_start_time = timestamp elif self.current_state == "potential_distraction": if (self.distraction_start_time is not None and timestamp - self.distraction_start_time > self.config.distraction_duration_threshold): self.current_state = "confirmed_distraction" else: if self.current_state in ["potential_distraction", "confirmed_distraction"]: self.current_state = "recovering" self.distraction_start_time = None elif self.current_state == "recovering": self.current_state = "normal" def _should_warn(self, is_distracted: bool, timestamp: float) -> bool: """判断是否应该发出警告""" if self.current_state != "confirmed_distraction": return False if self.last_warning_time is not None: if timestamp - self.last_warning_time < self.config.warning_cooldown_sec: return False self.last_warning_time = timestamp return True def _create_result(self, is_distracted: bool, confidence: float, state: str = "", indicators: dict = None, should_warn: bool = False, **kwargs) -> dict: """创建检测结果""" result = { 'is_distracted': is_distracted, 'confidence': confidence, 'state': state or self.current_state, 'indicators': indicators or {}, 'should_warn': should_warn, 'baseline': self.baseline_stats.copy() } result.update(kwargs) return result
if __name__ == "__main__": import time config = CognitiveDistractionConfig( window_size_sec=30.0, fps=25 ) detector = CognitiveDistractionDetector(config) print("模拟正常驾驶...") for i in range(500): if i % 100 < 90: angle = (np.random.randn() * 3, np.random.randn() * 2) else: angle = (np.random.choice([-20, 20]) + np.random.randn() * 2, np.random.randn() * 2) result = detector.update(angle, i / 25.0) print(f"正常驾驶状态: {result['state']}, PRC: {result.get('prc', 0):.1f}%") print() print("模拟认知分心...") for i in range(1000): angle = ( np.random.randn() * 8, np.random.randn() * 6 ) result = detector.update(angle, (500 + i) / 25.0) if result['is_distracted']: print(f"[{i/25.0:.1f}s] 检测到认知分心! 置信度: {result['confidence']:.2f}") print(f" 指标: PRC={result.get('prc', 0):.1f}%, " f"V_Disp={result.get('v_disp', 0):.2f}°, " f"SGE={result.get('sge', 0):.2f}") if result['should_warn']: print(f" ⚠️ 发出认知分心警告!") break print(f"\n最终状态: {result['state']}") print(f"基线统计: PRC={result['baseline']['prc_mean']:.1f}%, " f"V_Disp={result['baseline']['v_disp_mean']:.2f}°")
|