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
| """ LAIA 数据集:驾驶员注意力图生成与异常检测 论文复现:从眼动数据生成注意力热力图,检测注意力异常
依赖: pip install scipy numpy opencv-python matplotlib tobii-research
数据集: https://cloningdcb.org/ """
import numpy as np import cv2 from scipy.ndimage import gaussian_filter from typing import Tuple, List, Optional import json
class LAIAAttentionMap: """ LAIA 注意力图生成器 将 Tobii Glasses 3 的 100Hz 眼动数据 映射到 CARLA RGB 图像上,生成注意力热力图 """ def __init__(self, image_width: int = 1920, image_height: int = 1080, gaze_fps: int = 100, scene_fps: int = 25, sigma: int = 50): """ Args: image_width: 场景相机图像宽度 image_height: 场景相机图像高度 gaze_fps: 眼动仪采样率 (Hz) scene_fps: 场景相机帧率 (fps) sigma: 高斯模糊核大小 (像素) """ self.w = image_width self.h = image_height self.gaze_fps = gaze_fps self.scene_fps = scene_fps self.sigma = sigma self.gaze_per_frame = gaze_fps // scene_fps def load_gaze_data(self, gaze_file: str) -> np.ndarray: """ 加载 Tobii Glasses 3 导出的眼动数据 Args: gaze_file: JSON 格式眼动文件路径 Returns: gaze_data: shape=(N, 4), columns=[timestamp, x, y, pupil_diameter] """ with open(gaze_file, 'r') as f: raw = json.load(f) gazes = [] for g in raw['gaze_entries']: x = g['gaze_point_x'] * self.w y = g['gaze_point_y'] * self.h ts = g['timestamp'] pupil = g.get('pupil_diameter_mm', 0) gazes.append([ts, x, y, pupil]) return np.array(gazes) def generate_heatmap(self, gaze_points: np.ndarray, duration_frames: int = 1) -> np.ndarray: """ 生成单帧注意力热力图 Args: gaze_points: shape=(M, 2), 眼动 (x, y) 坐标 duration_frames: 持续帧数 Returns: heatmap: shape=(H, W), 归一化注意力分布 """ heatmap = np.zeros((self.h, self.w), dtype=np.float32) for x, y in gaze_points: xi, yi = int(np.clip(x, 0, self.w - 1)), int(np.clip(y, 0, self.h - 1)) if 0 <= xi < self.w and 0 <= yi < self.h: heatmap[yi, xi] += 1.0 heatmap = gaussian_filter(heatmap, sigma=self.sigma) total = heatmap.sum() if total > 0: heatmap /= total return heatmap def generate_temporal_attention(self, gaze_data: np.ndarray, frame_idx: int) -> np.ndarray: """ 为指定场景帧生成注意力图 Args: gaze_data: 完整眼动序列 frame_idx: 场景帧索引 Returns: heatmap: 该帧的注意力分布 """ start_idx = frame_idx * self.gaze_per_frame end_idx = start_idx + self.gaze_per_frame frame_gazes = gaze_data[start_idx:end_idx, 1:3] return self.generate_heatmap(frame_gazes) def compute_attention_entropy(self, heatmap: np.ndarray) -> float: """ 计算注意力熵——衡量注意力分散程度 高熵 = 注意力分散(分心状态) 低熵 = 注意力集中(专注状态) Args: heatmap: 注意力热力图 Returns: entropy: 注意力熵值 (bits) """ p = heatmap[heatmap > 0] entropy = -np.sum(p * np.log2(p)) return float(entropy) def detect_attention_anomaly(self, gaze_data: np.ndarray, roi: Tuple[int, int, int, int] = None, threshold: float = 0.3) -> List[dict]: """ 检测注意力异常事件 判断标准:注视点落在 ROI(如前方道路)外的比例 Args: gaze_data: 眼动数据 roi: 感兴趣区域 (x1, y1, x2, y2),默认为道路区域 threshold: 异常比例阈值 Returns: anomalies: 异常事件列表 """ if roi is None: roi = (0, int(self.h * 0.4), self.w, self.h) x1, y1, x2, y2 = roi anomalies = [] total_frames = len(gaze_data) // self.gaze_per_frame for frame in range(total_frames): start = frame * self.gaze_per_frame end = start + self.gaze_per_frame frame_gazes = gaze_data[start:end, 1:3] outside_count = 0 for x, y in frame_gazes: if not (x1 <= x <= x2 and y1 <= y <= y2): outside_count += 1 outside_ratio = outside_count / len(frame_gazes) if outside_ratio > threshold: anomalies.append({ 'frame': frame, 'timestamp': gaze_data[start, 0], 'outside_ratio': float(outside_ratio), 'avg_pupil': float(np.mean(gaze_data[start:end, 3])), 'type': 'attention_off_road' }) return anomalies
class LAIADriverModel: """ 基于 LAIA 数据集的驾驶员注意力建模 对比人类注意力与端到端 AI 模型的注意力分布 """ def __init__(self, attention_map: LAIAAttentionMap): self.am = attention_map self.baseline_entropy = None def build_baseline(self, normal_gaze_data: np.ndarray) -> float: """ 建立正常驾驶的注意力基线 Args: normal_gaze_data: 正常驾驶段眼动数据 Returns: baseline_entropy: 基线注意力熵 """ total_frames = len(normal_gaze_data) // self.am.gaze_per_frame entropies = [] for f in range(total_frames): hm = self.am.generate_temporal_attention(normal_gaze_data, f) entropies.append(self.am.compute_attention_entropy(hm)) self.baseline_entropy = float(np.mean(entropies)) return self.baseline_entropy def detect_distraction(self, gaze_data: np.ndarray, window_sec: float = 3.0) -> List[dict]: """ 基于注意力熵偏差检测分心 Args: gaze_data: 眼动数据 window_sec: 滑动窗口(秒) Returns: distraction_events: 分心事件列表 """ if self.baseline_entropy is None: raise ValueError("需先建立基线") window_frames = int(window_sec * self.am.scene_fps) total_frames = len(gaze_data) // self.am.gaze_per_frame events = [] for start in range(0, total_frames - window_frames, window_frames // 2): end = min(start + window_frames, total_frames) entropies = [] for f in range(start, end): hm = self.am.generate_temporal_attention(gaze_data, f) entropies.append(self.am.compute_attention_entropy(hm)) avg_entropy = np.mean(entropies) deviation = avg_entropy - self.baseline_entropy if deviation > 0.5: events.append({ 'start_frame': start, 'end_frame': end, 'avg_entropy': float(avg_entropy), 'baseline': self.baseline_entropy, 'deviation': float(deviation), 'severity': 'high' if deviation > 1.0 else 'medium' }) return events
if __name__ == "__main__": import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt am = LAIAAttentionMap( image_width=1920, image_height=1080, gaze_fps=100, scene_fps=25, sigma=50 ) np.random.seed(42) n_samples = 100 * 30 normal_x = np.random.normal(960, 150, n_samples) normal_y = np.random.normal(700, 100, n_samples) normal_pupil = np.random.normal(4.0, 0.3, n_samples) timestamps = np.arange(n_samples) / 100.0 normal_gaze = np.column_stack([timestamps, normal_x, normal_y, normal_pupil]) heatmap_normal = am.generate_temporal_attention(normal_gaze, frame_idx=50) entropy_normal = am.compute_attention_entropy(heatmap_normal) print(f"正常驾驶 - 注意力熵: {entropy_normal:.2f} bits") distracted_x = np.concatenate([ np.random.normal(1500, 200, n_samples // 3), np.random.normal(1300, 300, n_samples // 3), np.random.normal(960, 400, n_samples - 2 * (n_samples // 3)) ]) distracted_y = np.concatenate([ np.random.normal(500, 150, n_samples // 3), np.random.normal(600, 200, n_samples // 3), np.random.normal(650, 250, n_samples - 2 * (n_samples // 3)) ]) distracted_pupil = np.random.normal(3.8, 0.5, n_samples) distracted_gaze = np.column_stack([timestamps, distracted_x, distracted_y, distracted_pupil]) heatmap_distracted = am.generate_temporal_attention(distracted_gaze, frame_idx=50) entropy_distracted = am.compute_attention_entropy(heatmap_distracted) print(f"分心驾驶 - 注意力熵: {entropy_distracted:.2f} bits") print(f"熵偏差: {entropy_distracted - entropy_normal:.2f} bits") anomalies = am.detect_attention_anomaly(distracted_gaze, threshold=0.4) print(f"\n检测到 {len(anomalies)} 个异常帧:") for a in anomalies[:5]: print(f" 帧 {a['frame']}: 视线偏离比例 {a['outside_ratio']:.1%}") model = LAIADriverModel(am) baseline = model.build_baseline(normal_gaze) print(f"\n基线注意力熵: {baseline:.2f} bits") distraction_events = model.detect_distraction(distracted_gaze, window_sec=3.0) print(f"检测到 {len(distraction_events)} 个分心事件:") for e in distraction_events[:3]: print(f" 帧 {e['start_frame']}-{e['end_frame']}: " f"熵={e['avg_entropy']:.2f}, 偏差={e['deviation']:.2f}, " f"严重度={e['severity']}") fig, axes = plt.subplots(1, 2, figsize=(16, 6)) axes[0].imshow(heatmap_normal, cmap='jet', alpha=0.7) axes[0].set_title(f'Normal Driving (Entropy={entropy_normal:.2f})') axes[0].axis('off') axes[1].imshow(heatmap_distracted, cmap='jet', alpha=0.7) axes[1].set_title(f'Distracted Driving (Entropy={entropy_distracted:.2f})') axes[1].axis('off') plt.tight_layout() plt.savefig('laia_attention_comparison.png', dpi=150) print("\n可视化已保存: laia_attention_comparison.png")
|