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
| """ 认知分心特征分析 """
import numpy as np from dataclasses import dataclass from typing import List, Tuple from collections import deque
@dataclass class GazeMetrics: """眼动指标""" entropy: float regularity: float micro_saccade_rate: float fixation_duration: float saccade_amplitude: float
class CognitiveDistractionDetector: """ 认知分心检测器 检测指标: 1. 眼动熵(Gaze Entropy) 2. 眼动规律性(Gaze Regularity) 3. 微扫视特征 4. 注视模式变化 """ def __init__(self, window_size: int = 300, entropy_threshold: float = 0.7, regularity_threshold: float = 0.5): """ 初始化检测器 Args: window_size: 分析窗口大小 entropy_threshold: 熵阈值 regularity_threshold: 规律性阈值 """ self.window_size = window_size self.entropy_threshold = entropy_threshold self.regularity_threshold = regularity_threshold self.gaze_history = deque(maxlen=window_size) self.fixation_history = deque(maxlen=50) def update(self, gaze_x: float, gaze_y: float, timestamp: float) -> Tuple[bool, GazeMetrics]: """ 更新检测状态 Args: gaze_x: 视线X坐标(归一化0-1) gaze_y: 视线Y坐标(归一化0-1) timestamp: 时间戳 Returns: (is_distracted, metrics) """ self.gaze_history.append((gaze_x, gaze_y, timestamp)) if len(self.gaze_history) < self.window_size // 2: return False, GazeMetrics(0, 0, 0, 0, 0) metrics = self._compute_metrics() is_distracted = ( metrics.entropy > self.entropy_threshold or metrics.regularity < self.regularity_threshold ) return is_distracted, metrics def _compute_metrics(self) -> GazeMetrics: """计算眼动指标""" gaze_array = np.array(list(self.gaze_history)) x = gaze_array[:, 0] y = gaze_array[:, 1] entropy = self._compute_entropy(x, y) regularity = self._compute_regularity(x, y) micro_saccade_rate = self._compute_micro_saccade_rate(x, y) fixation_duration = self._compute_fixation_duration(x, y) saccade_amplitude = self._compute_saccade_amplitude(x, y) return GazeMetrics( entropy=entropy, regularity=regularity, micro_saccade_rate=micro_saccade_rate, fixation_duration=fixation_duration, saccade_amplitude=saccade_amplitude ) def _compute_entropy(self, x: np.ndarray, y: np.ndarray) -> float: """ 计算眼动熵 高熵表示视线分散(认知分心) 低熵表示视线集中(正常驾驶) """ grid_size = 10 x_bins = np.digitize(x, np.linspace(0, 1, grid_size)) y_bins = np.digitize(y, np.linspace(0, 1, grid_size)) hist, _, _ = np.histogram2d(x_bins, y_bins, bins=grid_size) prob = hist / hist.sum() prob_flat = prob.flatten() prob_flat = prob_flat[prob_flat > 0] entropy = -np.sum(prob_flat * np.log2(prob_flat)) max_entropy = np.log2(grid_size * grid_size) normalized_entropy = entropy / max_entropy return normalized_entropy def _compute_regularity(self, x: np.ndarray, y: np.ndarray) -> float: """ 计算眼动规律性 使用自相关分析 高规律性 = 正常驾驶(扫视模式规律) 低规律性 = 认知分心(扫视模式混乱) """ x_centered = x - np.mean(x) y_centered = y - np.mean(y) lag = 10 if len(x) < lag * 2: return 0.5 x_autocorr = np.corrcoef(x_centered[:-lag], x_centered[lag:])[0, 1] y_autocorr = np.corrcoef(y_centered[:-lag], y_centered[lag:])[0, 1] regularity = (abs(x_autocorr) + abs(y_autocorr)) / 2 regularity = max(0, min(1, regularity)) return regularity def _compute_micro_saccade_rate(self, x: np.ndarray, y: np.ndarray) -> float: """计算微扫视频率""" dx = np.diff(x) dy = np.diff(y) velocity = np.sqrt(dx**2 + dy**2) micro_saccade_threshold = 0.01 micro_saccades = np.sum(velocity > micro_saccade_threshold) duration = len(x) / 30 rate = micro_saccades / duration return rate def _compute_fixation_duration(self, x: np.ndarray, y: np.ndarray) -> float: """计算平均注视持续时间""" velocity = np.sqrt(np.diff(x)**2 + np.diff(y)**2) fixation_threshold = 0.005 fixation_durations = [] current_duration = 1 for v in velocity: if v < fixation_threshold: current_duration += 1 else: if current_duration > 3: fixation_durations.append(current_duration / 30) current_duration = 1 if len(fixation_durations) == 0: return 0.0 return np.mean(fixation_durations) def _compute_saccade_amplitude(self, x: np.ndarray, y: np.ndarray) -> float: """计算平均扫视幅度""" velocity = np.sqrt(np.diff(x)**2 + np.diff(y)**2) saccade_threshold = 0.01 saccade_amplitudes = velocity[velocity > saccade_threshold] if len(saccade_amplitudes) == 0: return 0.0 return np.mean(saccade_amplitudes)
if __name__ == "__main__": detector = CognitiveDistractionDetector() print("=== 认知分心检测测试 ===") print("\n[场景1:正常驾驶]") np.random.seed(42) for i in range(300): t = i / 30 x = 0.5 + 0.1 * np.sin(2 * np.pi * 0.3 * t) + np.random.randn() * 0.02 y = 0.5 + 0.05 * np.sin(2 * np.pi * 0.2 * t) + np.random.randn() * 0.02 x = np.clip(x, 0, 1) y = np.clip(y, 0, 1) is_distracted, metrics = detector.update(x, y, t) if i == 299: print(f" 眼动熵: {metrics.entropy:.3f}") print(f" 规律性: {metrics.regularity:.3f}") print(f" 认知分心: {is_distracted}") print("\n[场景2:认知分心]") detector = CognitiveDistractionDetector() for i in range(300): t = i / 30 x = np.random.rand() y = np.random.rand() is_distracted, metrics = detector.update(x, y, t) if i == 299: print(f" 眼动熵: {metrics.entropy:.3f}") print(f" 规律性: {metrics.regularity:.3f}") print(f" 认知分心: {is_distracted}")
|