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
| """ Seeing Machines 酒驾损伤检测算法
基于眼动特征的酒精损伤检测 """
import numpy as np from dataclasses import dataclass from typing import List, Dict, Tuple from collections import deque
@dataclass class EyeFeatures: """眼动特征""" ear_left: float ear_right: float pupil_x_left: float pupil_y_left: float pupil_x_right: float pupil_y_right: float gaze_x: float gaze_y: float gaze_z: float blink_state: bool timestamp: float
@dataclass class ImpairmentState: """损伤状态""" bac_estimate: float impairment_level: str confidence: float features_used: List[str]
class AlcoholImpairmentDetector: """ 酒精损伤检测器 基于眼动特征实时估计 BAC """ def __init__(self, config: dict = None): self.config = config or {} self.history_length = self.config.get('history_length', 300) self.ear_history = deque(maxlen=self.history_length) self.blink_history = deque(maxlen=self.history_length) self.gaze_history = deque(maxlen=self.history_length) self.saccade_history = deque(maxlen=50) self.ear_baseline = 0.3 self.ear_droop_threshold = 0.85 self.blink_rate_normal = (10, 20) self.saccade_latency_normal = 0.2 self.analysis_window = 5.0 def update(self, features: EyeFeatures) -> ImpairmentState: """ 更新特征并检测损伤 Args: features: 当前帧眼动特征 Returns: 损伤状态估计 """ avg_ear = (features.ear_left + features.ear_right) / 2 self.ear_history.append(avg_ear) self.blink_history.append(features.blink_state) self.gaze_history.append((features.gaze_x, features.gaze_y, features.gaze_z)) self._detect_saccade(features) if len(self.ear_history) < 90: return ImpairmentState( bac_estimate=0.0, impairment_level='normal', confidence=0.0, features_used=[] ) indicators = self._extract_indicators() bac_estimate, confidence = self._estimate_bac(indicators) if bac_estimate < 0.05: level = 'normal' elif bac_estimate < 0.08: level = 'mild' else: level = 'severe' return ImpairmentState( bac_estimate=bac_estimate, impairment_level=level, confidence=confidence, features_used=list(indicators.keys()) ) def _detect_saccade(self, features: EyeFeatures): """ 检测扫视事件 扫视特征: - 速度 > 200°/s - 幅度 > 2° - 持续时间 < 100ms """ if len(self.gaze_history) < 2: return prev_gaze = self.gaze_history[-2] curr_gaze = (features.gaze_x, features.gaze_y, features.gaze_z) angle_change = self._calculate_gaze_angle_change(prev_gaze, curr_gaze) dt = 1.0 / 30 if angle_change > 2.0: velocity = angle_change / dt if velocity > 200: self.saccade_history.append({ 'amplitude': angle_change, 'velocity': velocity, 'timestamp': features.timestamp }) def _calculate_gaze_angle_change( self, gaze1: Tuple[float, float, float], gaze2: Tuple[float, float, float] ) -> float: """ 计算视线角度变化 """ dot = np.dot(gaze1, gaze2) dot = np.clip(dot, -1.0, 1.0) angle = np.arccos(dot) * 180 / np.pi return angle def _extract_indicators(self) -> Dict[str, float]: """ 提取损伤指标 """ indicators = {} recent_ear = list(self.ear_history)[-150:] avg_ear = np.mean(recent_ear) ear_droop = self.ear_baseline - avg_ear indicators['ear_droop'] = ear_droop droop_frames = np.sum(np.array(recent_ear) < self.ear_baseline * self.ear_droop_threshold) droop_ratio = droop_frames / len(recent_ear) indicators['droop_ratio'] = droop_ratio blink_events = np.diff(self.blink_history.astype(int)) blink_count = np.sum(blink_events == 1) blink_rate = blink_count / (len(self.blink_history) / 30) * 60 indicators['blink_rate'] = blink_rate normal_low, normal_high = self.blink_rate_normal if blink_rate < normal_low: blink_abnormality = (normal_low - blink_rate) / normal_low elif blink_rate > normal_high: blink_abnormality = (blink_rate - normal_high) / normal_high else: blink_abnormality = 0 indicators['blink_abnormality'] = blink_abnormality if len(self.saccade_history) >= 3: saccades = list(self.saccade_history)[-10:] avg_saccade_velocity = np.mean([s['velocity'] for s in saccades]) avg_saccade_amplitude = np.mean([s['amplitude'] for s in saccades]) velocity_deficit = max(0, (300 - avg_saccade_velocity) / 300) indicators['saccade_velocity_deficit'] = velocity_deficit indicators['saccade_amplitude'] = avg_saccade_amplitude else: indicators['saccade_velocity_deficit'] = 0 indicators['saccade_amplitude'] = 0 gaze_array = np.array(list(self.gaze_history)[-150:]) gaze_variance = np.var(gaze_array, axis=0).mean() indicators['gaze_variance'] = gaze_variance return indicators def _estimate_bac(self, indicators: Dict[str, float]) -> Tuple[float, float]: """ 估计 BAC 值 基于多指标加权回归 Returns: (bac_estimate, confidence) """ weights = { 'ear_droop': 0.15, 'droop_ratio': 0.25, 'blink_abnormality': 0.15, 'saccade_velocity_deficit': 0.25, 'gaze_variance': 0.20 } score = 0 total_weight = 0 for key, weight in weights.items(): if key in indicators: score += indicators[key] * weight total_weight += weight if total_weight > 0: score = score / total_weight else: score = 0 bac_estimate = score * 0.15 bac_estimate = np.clip(bac_estimate, 0.0, 0.20) confidence = min(1.0, total_weight / sum(weights.values())) return bac_estimate, confidence
if __name__ == "__main__": detector = AlcoholImpairmentDetector() np.random.seed(42) timestamps = np.linspace(0, 10, 300) normal_ear = 0.3 + np.random.normal(0, 0.02, 300) normal_gaze = np.random.randn(300, 3) * 0.1 normal_gaze = normal_gaze / np.linalg.norm(normal_gaze, axis=1, keepdims=True) impaired_ear = 0.25 + np.random.normal(0, 0.03, 300) impaired_gaze = np.random.randn(300, 3) * 0.2 impaired_gaze = impaired_gaze / np.linalg.norm(impaired_gaze, axis=1, keepdims=True) print("正常状态测试:") for i, t in enumerate(timestamps[:150]): features = EyeFeatures( ear_left=normal_ear[i], ear_right=normal_ear[i], pupil_x_left=0.5, pupil_y_left=0.5, pupil_x_right=0.5, pupil_y_right=0.5, gaze_x=normal_gaze[i, 0], gaze_y=normal_gaze[i, 1], gaze_z=normal_gaze[i, 2], blink_state=np.random.random() < 0.03, timestamp=t ) state = detector.update(features) print(f" BAC 估计: {state.bac_estimate:.3f}") print(f" 损伤等级: {state.impairment_level}") print(f" 置信度: {state.confidence:.2f}") print("\n酒精损伤状态测试:") detector2 = AlcoholImpairmentDetector() for i, t in enumerate(timestamps[:150]): features = EyeFeatures( ear_left=impaired_ear[i], ear_right=impaired_ear[i], pupil_x_left=0.5, pupil_y_left=0.5, pupil_x_right=0.5, pupil_y_right=0.5, gaze_x=impaired_gaze[i, 0], gaze_y=impaired_gaze[i, 1], gaze_z=impaired_gaze[i, 2], blink_state=np.random.random() < 0.05, timestamp=t ) state = detector2.update(features) print(f" BAC 估计: {state.bac_estimate:.3f}") print(f" 损伤等级: {state.impairment_level}") print(f" 置信度: {state.confidence:.2f}")
|