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
| import numpy as np import cv2 import torch import torch.nn as nn from typing import Dict, Tuple, Optional
class RobustEyeTracker: """ 鲁棒眼动追踪器 处理墨镜、口罩、遮挡等场景 """ def __init__(self, config: dict): self.eye_tracker = StandardEyeTracker() self.sunglasses_detector = SunglassesDetector() self.occluded_eye_estimator = OccludedEyeEstimator() self.multi_modal_fusion = MultiModalFusion() self.ir_mode = config.get('ir_mode', True) self.use_head_pose = config.get('use_head_pose', True) def track(self, rgb_image: np.ndarray, ir_image: np.ndarray = None, head_pose: Tuple[float, float, float] = None) -> Dict: """ 鲁棒眼动追踪 Args: rgb_image: RGB图像 ir_image: 红外图像(可选) head_pose: 头部姿态(可选) Returns: result: { 'gaze_direction': Tuple[float, float], 'eye_closure': float, 'blink_rate': float, 'confidence': float, 'method': str # 使用的方法 } """ occlusion_type = self._detect_occlusion(rgb_image, ir_image) if occlusion_type == 'SUNGLASSES': if self.ir_mode and ir_image is not None: result = self._track_with_ir(ir_image) result['method'] = 'IR_PENETRATION' else: result = self._estimate_from_head_pose(head_pose) result['method'] = 'HEAD_POSE_ESTIMATION' elif occlusion_type == 'MASK': result = self.eye_tracker.track(rgb_image) result['method'] = 'STANDARD' elif occlusion_type == 'PARTIAL_OCCLUSION': result = self.occluded_eye_estimator.estimate(rgb_image) result['method'] = 'OCCLUSION_ROBUST' else: result = self.eye_tracker.track(rgb_image) result['method'] = 'STANDARD' if head_pose is not None: result = self.multi_modal_fusion.fuse( eye_result=result, head_pose=head_pose ) return result def _detect_occlusion(self, rgb_image: np.ndarray, ir_image: np.ndarray = None) -> str: """ 检测遮挡类型 Returns: occlusion_type: 'NONE', 'SUNGLASSES', 'MASK', 'PARTIAL_OCCLUSION' """ is_sunglasses = self.sunglasses_detector.detect(rgb_image) if is_sunglasses: return 'SUNGLASSES' is_mask = self._detect_mask(rgb_image) if is_mask: return 'MASK' is_partial = self._detect_partial_occlusion(rgb_image) if is_partial: return 'PARTIAL_OCCLUSION' return 'NONE' def _track_with_ir(self, ir_image: np.ndarray) -> Dict: """ 使用红外图像追踪 940nm红外光可穿透部分墨镜 """ enhanced_ir = self._enhance_ir_image(ir_image) result = self.eye_tracker.track(enhanced_ir) result['confidence'] *= 0.8 return result def _enhance_ir_image(self, ir_image: np.ndarray) -> np.ndarray: """ 增强红外图像 1. 对比度增强 2. 去噪 3. 直方图均衡化 """ ir_normalized = cv2.normalize( ir_image, None, 0, 255, cv2.NORM_MINMAX ) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) ir_enhanced = clahe.apply(ir_normalized.astype(np.uint8)) ir_denoised = cv2.fastNlMeansDenoising(ir_enhanced, None, 10, 7, 21) return ir_denoised def _estimate_from_head_pose(self, head_pose: Tuple[float, float, float]) -> Dict: """ 从头部姿态估计视线 当眼睛不可见时,使用头部姿态作为替代 """ yaw, pitch, roll = head_pose gaze_yaw = yaw * 0.8 gaze_pitch = pitch * 0.8 return { 'gaze_direction': (gaze_yaw, gaze_pitch), 'eye_closure': 0.5, 'blink_rate': 15.0, 'confidence': 0.5, 'method': 'HEAD_POSE_ESTIMATION' } def _detect_mask(self, image: np.ndarray) -> bool: """检测口罩""" pass def _detect_partial_occlusion(self, image: np.ndarray) -> bool: """检测部分遮挡""" pass
class SunglassesDetector(nn.Module): """ 墨镜检测器 """ def __init__(self): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 32, 3, 2, 1), nn.ReLU(), nn.Conv2d(32, 64, 3, 2, 1), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.classifier = nn.Sequential( nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 2) ) def forward(self, x: torch.Tensor) -> torch.Tensor: features = self.features(x) features = features.view(features.size(0), -1) return self.classifier(features) def detect(self, image: np.ndarray) -> bool: """检测是否佩戴墨镜""" self.eval() with torch.no_grad(): input_tensor = self._preprocess(image) output = self.forward(input_tensor) is_sunglasses = torch.argmax(output, dim=1).item() == 1 return is_sunglasses def _preprocess(self, image: np.ndarray) -> torch.Tensor: """预处理图像""" image = cv2.resize(image, (64, 64)) image = image.astype(np.float32) / 255.0 tensor = torch.from_numpy(image).permute(2, 0, 1).unsqueeze(0) return tensor
class OccludedEyeEstimator(nn.Module): """ 部分遮挡眼睛估计器 使用可见部分估计完整眼睛状态 """ def __init__(self): super().__init__() self.encoder = nn.Sequential( nn.Conv2d(3, 64, 3, 2, 1), nn.ReLU(), nn.Conv2d(64, 128, 3, 2, 1), nn.ReLU(), nn.Conv2d(128, 256, 3, 2, 1), nn.ReLU() ) self.uncertainty_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(256, 1), nn.Sigmoid() ) self.eye_state_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 4) ) def forward(self, x: torch.Tensor) -> Dict: features = self.encoder(x) uncertainty = self.uncertainty_head(features) eye_state = self.eye_state_head(features) return { 'uncertainty': uncertainty, 'eye_closure': torch.sigmoid(eye_state[:, 0:1]), 'gaze': eye_state[:, 1:3], 'blink': torch.sigmoid(eye_state[:, 3:4]) }
class MultiModalFusion(nn.Module): """ 多模态融合 融合眼动追踪结果与头部姿态 """ def __init__(self): super().__init__() self.weight_net = nn.Sequential( nn.Linear(6, 32), nn.ReLU(), nn.Linear(32, 2), nn.Softmax(dim=1) ) def fuse(self, eye_result: Dict, head_pose: Tuple[float, float, float]) -> Dict: """ 融合眼动追踪和头部姿态 """ eye_gaze = eye_result['gaze_direction'] eye_conf = eye_result['confidence'] head_yaw, head_pitch, head_roll = head_pose features = torch.tensor([[ eye_gaze[0], eye_gaze[1], head_yaw, head_pitch, head_roll, eye_conf ]], dtype=torch.float32) weights = self.weight_net(features)[0] fused_gaze_yaw = weights[0] * eye_gaze[0] + weights[1] * head_yaw * 0.8 fused_gaze_pitch = weights[0] * eye_gaze[1] + weights[1] * head_pitch * 0.8 return { 'gaze_direction': (float(fused_gaze_yaw), float(fused_gaze_pitch)), 'eye_closure': eye_result['eye_closure'], 'blink_rate': eye_result['blink_rate'], 'confidence': float(max(weights[0] * eye_conf, weights[1] * 0.5)), 'method': 'MULTIMODAL_FUSION' }
class StandardEyeTracker(nn.Module): """ 标准眼动追踪模型 """ def __init__(self): super().__init__() pass def track(self, image: np.ndarray) -> Dict: """标准眼动追踪""" return { 'gaze_direction': (0.0, 0.0), 'eye_closure': 0.2, 'blink_rate': 15.0, 'confidence': 0.9 }
if __name__ == "__main__": config = { 'ir_mode': True, 'use_head_pose': True } tracker = RobustEyeTracker(config) rgb_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) ir_image = np.random.randint(0, 255, (480, 640), dtype=np.uint8) head_pose = (10.0, 5.0, 0.0) result = tracker.track(rgb_image, ir_image, head_pose) print("眼动追踪结果:") print(f" 视线方向: {result['gaze_direction']}") print(f" 眼睛闭合度: {result['eye_closure']:.2f}") print(f" 置信度: {result['confidence']:.2f}") print(f" 使用方法: {result['method']}")
|