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 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
| import numpy as np import torch import torch.nn as nn
class AlcoholImpairmentDetector(nn.Module): """ Smart Eye酒精损伤检测核心算法 输入模态: - 眼部追踪数据(眼动、注视、眨眼) - 面部关键点序列 - 头部姿态序列 输出: - 损伤评分(0-100) - 损伤类型(酒精/药物/疲劳) - 置信度 """ def __init__(self): super().__init__() self.eye_encoder = nn.Sequential( nn.Linear(12, 64), nn.ReLU(), nn.Linear(64, 128), nn.ReLU() ) self.face_encoder = nn.Sequential( nn.Linear(68*3, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU() ) self.head_encoder = nn.Sequential( nn.Linear(6, 64), nn.ReLU(), nn.Linear(64, 128), nn.ReLU() ) self.fusion = nn.Sequential( nn.Linear(128*3, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU() ) self.impairment_classifier = nn.Sequential( nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 4) ) self.impairment_score = nn.Sequential( nn.Linear(64, 16), nn.ReLU(), nn.Linear(16, 1) ) def forward(self, eye_features, face_landmarks, head_pose): """ Args: eye_features: (B, T, 12) 眼部特征序列 - 眼位(x,y,z) - 注视方向(x,y,z) - 眼睑开度(左,右) - 眨眼频率 - PERCLOS - 眼动熵 face_landmarks: (B, T, 68, 3) 面部关键点序列 head_pose: (B, T, 6) 头部姿态序列 - 旋转角(rx, ry, rz) - 变化率(dr_x, dr_y, dr_z) Returns: impairment_type: (B, 4) 损伤类型概率 impairment_score: (B, 1) 损伤评分(0-100) """ eye_feat = self.eye_encoder(eye_features) face_feat = self.face_encoder(face_landmarks.view(face_landmarks.size(0), -1)) head_feat = self.head_encoder(head_pose) fused = torch.cat([eye_feat, face_feat, head_feat], dim=-1) fused_feat = self.fusion(fused) impairment_type = self.impairment_classifier(fused_feat) impairment_score = self.impairment_score(fused_feat) return impairment_type, impairment_score
class AlcoholFeatureExtractor: """ 提取酒精损伤相关的眼部和面部特征 """ def extract_eye_features(self, eye_tracking_data): """ 从眼动追踪数据提取损伤特征 Args: eye_tracking_data: dict with keys - 'eye_position': (T, 3) - 'gaze_direction': (T, 3) - 'eye_openness': (T, 2) - 'blinks': list of blink events Returns: features: (T, 12) 眼部特征向量 """ T = len(eye_tracking_data['eye_position']) features = np.zeros((T, 12)) for t in range(T): features[t, 0:3] = eye_tracking_data['eye_position'][t] features[t, 3:6] = eye_tracking_data['gaze_direction'][t] features[t, 6:8] = eye_tracking_data['eye_openness'][t] features[t, 8] = self.compute_blink_rate( eye_tracking_data['blinks'], window=30, current_time=t ) features[t, 9] = self.compute_perclos( eye_tracking_data['eye_openness'][:t+1], fps=30 ) features[t, 10] = self.compute_eye_entropy( eye_tracking_data['gaze_direction'][:t+1] ) features[t, 11] = self.compute_fixation_stability( eye_tracking_data['gaze_direction'][t-10:t+1] if t >= 10 else eye_tracking_data['gaze_direction'][:t+1] ) return features def compute_eye_entropy(self, gaze_sequence): """ 计算眼动熵 熵值越高,眼动越无规律(酒精损伤信号) """ gaze_norm = gaze_sequence / np.linalg.norm(gaze_sequence, axis=1, keepdims=True) delta = gaze_norm[1:] - gaze_norm[:-1] if len(delta) > 10: entropy = self.approximate_entropy(delta) else: entropy = 0.0 return entropy def approximate_entropy(self, sequence, m=2, r=0.2): """ 近似熵计算 参数: - m: 嵌入维度 - r: 相似度阈值(相对于标准差) """ N = len(sequence) std = np.std(sequence) threshold = r * std patterns = [] for i in range(N - m + 1): patterns.append(sequence[i:i+m]) counts = [] for p in patterns: similar_count = 0 for q in patterns: if np.max(np.abs(p - q)) < threshold: similar_count += 1 counts.append(similar_count / len(patterns)) phi_m = np.mean(np.log(counts)) m += 1 patterns = [] for i in range(N - m + 1): patterns.append(sequence[i:i+m]) counts = [] for p in patterns: similar_count = 0 for q in patterns: if np.max(np.abs(p - q)) < threshold: similar_count += 1 counts.append(similar_count / len(patterns)) phi_m1 = np.mean(np.log(counts)) apen = phi_m - phi_m1 return apen def compute_fixation_stability(self, gaze_window): """ 计算注视稳定性 酒精损伤:稳定性下降,注视漂移 """ if len(gaze_window) < 5: return 1.0 variance = np.var(gaze_window, axis=0) stability = 1.0 / (1.0 + np.sum(variance)) return stability def compute_perclos(self, eye_openness, fps=30, window_sec=60): """ PERCLOS计算 眼睑开度 < 阈值视为闭眼 """ window_frames = int(window_sec * fps) if len(eye_openness) < window_frames: window_frames = len(eye_openness) threshold = 0.2 closed_frames = np.sum(eye_openness[-window_frames:] < threshold) perclos = closed_frames / window_frames return perclos def compute_blink_rate(self, blinks, window=30, current_time=0): """ 计算眨眼频率(每分钟) """ window_blinks = [b for b in blinks if current_time - window <= b['time'] <= current_time] rate = len(window_blinks) * 60 / window return rate
class FacialFeatureExtractor: """ 提取酒精损伤相关的面部特征 """ def extract_face_features(self, face_landmarks_sequence): """ 从面部关键点提取损伤特征 酒精损伤面部信号: - 肌肉松弛:嘴角下垂 - 表情迟缓:关键点位移减少 - 面部不对称:左右关键点差异 """ T = len(face_landmarks_sequence) features = np.zeros((T, 68, 3)) for t in range(T): landmarks = face_landmarks_sequence[t] features[t] = landmarks return features def compute_mouth_slackness(self, landmarks): """ 计算嘴角松弛度 酒精损伤:嘴角下垂,肌肉张力下降 """ mouth_left = landmarks[48] mouth_right = landmarks[54] mouth_height = (mouth_left[1] + mouth_right[1]) / 2 mouth_width = np.abs(mouth_right[0] - mouth_left[0]) slackness = (1.0 - mouth_height / 100) * (1.0 - mouth_width / 50) return slackness def compute_face_asymmetry(self, landmarks): """ 计算面部不对称度 酒精损伤:面部肌肉控制失衡,不对称增加 """ left_indices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] right_indices = [16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4] left_points = landmarks[left_indices] right_points = landmarks[right_indices] asymmetry = np.mean(np.abs(left_points - np.flip(right_points, axis=0))) return asymmetry
if __name__ == "__main__": detector = AlcoholImpairmentDetector() eye_extractor = AlcoholFeatureExtractor() face_extractor = FacialFeatureExtractor() eye_data_simulated = { 'eye_position': np.random.randn(90, 3) * 0.1, 'gaze_direction': np.random.randn(90, 3) * 0.2, 'eye_openness': np.random.uniform(0.6, 0.8, (90, 2)), 'blinks': [{'time': i} for i in range(0, 90, 15)] } face_landmarks_simulated = np.random.randn(90, 68, 3) * 0.05 head_pose_simulated = np.random.randn(90, 6) * 0.1 eye_features = eye_extractor.extract_eye_features(eye_data_simulated) face_features = face_extractor.extract_face_features(face_landmarks_simulated) eye_tensor = torch.FloatTensor(eye_features).unsqueeze(0) face_tensor = torch.FloatTensor(face_features).unsqueeze(0) head_tensor = torch.FloatTensor(head_pose_simulated).unsqueeze(0) impairment_type, impairment_score = detector(eye_tensor, face_tensor, head_tensor) print("="*60) print("Smart Eye酒精损伤检测结果") print("="*60) type_probs = impairment_type.squeeze().softmax(dim=0).tolist() types = ['正常', '酒精损伤', '药物损伤', '疲劳损伤'] for i, (type_name, prob) in enumerate(zip(types, type_probs)): print(f"{type_name}: {prob*100:.1f}%") score = impairment_score.squeeze().item() print(f"\n损伤评分: {score:.1f}/100") if type_probs[1] > 0.7 and score > 50: print("\n⚠️ Euro NCAP I-01触发:酒精损伤") print("二级警告 + 建议停止驾驶") print("="*60)
|