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
| import numpy as np from typing import List, Tuple, Optional from dataclasses import dataclass from enum import Enum from collections import deque
class CognitiveState(Enum): """认知状态""" NORMAL = "normal" LOW_DISTRACTION = "low" HIGH_DISTRACTION = "high" TUNNEL_EFFECT = "tunnel" UNKNOWN = "unknown"
@dataclass class CognitiveEvent: """认知分心事件""" timestamp: float state: CognitiveState prc: float h_dispersion: float v_dispersion: float pupil_diameter: float confidence: float
class CognitiveDistractionDetector: """ 认知分心检测器 基于多指标融合的认知分心检测: 1. Percent Road Center (PRC) 2. 注视分散(水平/垂直) 3. 瞳孔直径 4. 时序模式分析 检测逻辑: - 正常状态:PRC 稳定,分散度适中 - 隧道效应(心算中):PRC↑,分散度↓ - 恢复性扫视(心算间隙):PRC↓,分散度↑ - 认知分心:连续的异常模式 参考: - Victor et al. (2005): PRC and dispersion - Harbluk et al. (2007): Tunnel effect - Halin et al. (2025): Phasic patterns """ def __init__(self, fps: int = 30, window_sec: float = 30.0, prc_normal_range: Tuple[float, float] = (50, 80), h_disp_normal_range: Tuple[float, float] = (8, 20), v_disp_normal_range: Tuple[float, float] = (5, 12), pupil_normal_range: Tuple[float, float] = (3.5, 5.5)): """ 初始化认知分心检测器 Args: fps: 帧率 window_sec: 计算窗口(秒) prc_normal_range: PRC 正常范围(%) h_disp_normal_range: 水平分散正常范围(度) v_disp_normal_range: 垂直分散正常范围(度) pupil_normal_range: 瞳孔直径正常范围(mm) """ self.fps = fps self.window_size = int(window_sec * fps) self.prc_normal_range = prc_normal_range self.h_disp_normal_range = h_disp_normal_range self.v_disp_normal_range = v_disp_normal_range self.pupil_normal_range = pupil_normal_range self.prc_calculator = PercentRoadCenterCalculator(window_sec=window_sec) self.disp_calculator = GazeDispersionCalculator(window_sec=window_sec, fps=fps) self.gaze_history = deque(maxlen=self.window_size) self.prc_history = deque(maxlen=self.window_size) self.h_disp_history = deque(maxlen=self.window_size) self.v_disp_history = deque(maxlen=self.window_size) self.pupil_history = deque(maxlen=self.window_size) self.baseline_established = False self.baseline_prc = None self.baseline_h_disp = None self.baseline_v_disp = None self.baseline_pupil = None self.current_state = CognitiveState.UNKNOWN self.events: List[CognitiveEvent] = [] def update(self, gd: GazeData) -> Tuple[CognitiveState, Optional[CognitiveEvent]]: """ 更新检测器,返回当前认知状态 Args: gd: 注视数据 Returns: cognitive_state: 当前认知状态 event: 新事件(如果有状态变化) """ self.gaze_history.append(gd) disp_metrics = self.disp_calculator.update(gd) prc = self.prc_calculator.calculate(list(self.gaze_history)) self.prc_history.append(prc) self.h_disp_history.append(disp_metrics.h_dispersion) self.v_disp_history.append(disp_metrics.v_dispersion) self.pupil_history.append(gd.pupil_diameter) if not self.baseline_established and len(self.gaze_history) >= self.window_size: self._establish_baseline() prev_state = self.current_state self.current_state = self._detect_state(prc, disp_metrics, gd.pupil_diameter) event = None if self.current_state != prev_state and self.current_state != CognitiveState.NORMAL: event = CognitiveEvent( timestamp=gd.timestamp, state=self.current_state, prc=prc, h_dispersion=disp_metrics.h_dispersion, v_dispersion=disp_metrics.v_dispersion, pupil_diameter=gd.pupil_diameter, confidence=self._calculate_confidence() ) self.events.append(event) return self.current_state, event def _establish_baseline(self): """建立基线""" self.baseline_prc = np.mean(list(self.prc_history)) self.baseline_h_disp = np.mean(list(self.h_disp_history)) self.baseline_v_disp = np.mean(list(self.v_disp_history)) self.baseline_pupil = np.mean(list(self.pupil_history)) self.baseline_established = True def _detect_state(self, prc: float, disp_metrics: DispersionMetrics, pupil: float) -> CognitiveState: """ 检测认知状态 Args: prc: Percent Road Center disp_metrics: 注视分散指标 pupil: 瞳孔直径 Returns: CognitiveState 枚举值 """ if not self.baseline_established: return CognitiveState.UNKNOWN h_disp = disp_metrics.h_dispersion v_disp = disp_metrics.v_dispersion prc_ratio = prc / self.baseline_prc if self.baseline_prc > 0 else 1.0 h_disp_ratio = h_disp / self.baseline_h_disp if self.baseline_h_disp > 0 else 1.0 v_disp_ratio = v_disp / self.baseline_v_disp if self.baseline_v_disp > 0 else 1.0 pupil_ratio = pupil / self.baseline_pupil if self.baseline_pupil > 0 else 1.0 if prc_ratio > 1.3 and h_disp_ratio < 0.7 and v_disp_ratio < 0.8: return CognitiveState.TUNNEL_EFFECT if prc_ratio < 0.7 and v_disp_ratio > 1.3: if pupil_ratio > 1.2: return CognitiveState.HIGH_DISTRACTION else: return CognitiveState.LOW_DISTRACTION abnormal_count = 0 if not (self.prc_normal_range[0] <= prc <= self.prc_normal_range[1]): abnormal_count += 1 if not (self.h_disp_normal_range[0] <= h_disp <= self.h_disp_normal_range[1]): abnormal_count += 1 if not (self.v_disp_normal_range[0] <= v_disp <= self.v_disp_normal_range[1]): abnormal_count += 1 if not (self.pupil_normal_range[0] <= pupil <= self.pupil_normal_range[1]): abnormal_count += 1 if abnormal_count >= 3: return CognitiveState.HIGH_DISTRACTION elif abnormal_count >= 2: return CognitiveState.LOW_DISTRACTION return CognitiveState.NORMAL def _calculate_confidence(self) -> float: """计算置信度""" data_score = min(len(self.gaze_history) / self.window_size, 1.0) if len(self.prc_history) > 10: prc_std = np.std(list(self.prc_history)[-100:]) consistency_score = max(0, 1 - prc_std / 20) else: consistency_score = 0.5 return (data_score * 0.5 + consistency_score * 0.5) def get_statistics(self) -> dict: """获取统计信息""" return { 'current_state': self.current_state.value, 'baseline_established': self.baseline_established, 'baseline_prc': self.baseline_prc, 'baseline_h_disp': self.baseline_h_disp, 'baseline_v_disp': self.baseline_v_disp, 'baseline_pupil': self.baseline_pupil, 'current_prc': list(self.prc_history)[-1] if self.prc_history else 0, 'current_h_disp': list(self.h_disp_history)[-1] if self.h_disp_history else 0, 'current_v_disp': list(self.v_disp_history)[-1] if self.v_disp_history else 0, 'event_count': len(self.events) }
if __name__ == "__main__": import random detector = CognitiveDistractionDetector(fps=30, window_sec=30.0) print("=" * 60) print("认知分心检测测试") print("=" * 60) for i in range(2700): timestamp = i / 30.0 if i < 900: h_angle = random.gauss(0, 12) v_angle = random.gauss(0, 8) pupil = random.gauss(4.5, 0.3) elif i < 1800: h_angle = random.gauss(0, 6) v_angle = random.gauss(0, 4) pupil = random.gauss(5.5, 0.4) else: h_angle = random.gauss(0, 15) v_angle = random.gauss(0, 10) pupil = random.gauss(4.8, 0.3) gd = GazeData( timestamp=timestamp, h_angle=h_angle, v_angle=v_angle, pupil_diameter=pupil, confidence=0.9 ) state, event = detector.update(gd) if event: print(f"[{timestamp:.1f}s] 状态变化: {event.state.value}, " f"PRC={event.prc:.1f}%, " f"H_disp={event.h_dispersion:.1f}°, " f"V_disp={event.v_dispersion:.1f}°, " f"Pupil={event.pupil_diameter:.2f}mm") if i > 0 and i % 900 == 0: stats = detector.get_statistics() print(f"\n--- {int(timestamp)}秒统计 ---") print(f"当前状态: {stats['current_state']}") print(f"基线 PRC: {stats['baseline_prc']:.1f}%") print(f"当前 PRC: {stats['current_prc']:.1f}%") print(f"事件数: {stats['event_count']}\n") print("\n" + "=" * 60) print("最终统计:") stats = detector.get_statistics() for k, v in stats.items(): print(f" {k}: {v}") print("=" * 60)
|