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
| """ GazeTrack: 高精度眼动追踪管道 论文复现: arXiv:2511.22607
包含: 1. U-ResAtt 瞳孔分割模型 2. 椭圆拟合误差 (EFE) 正则化 3. CoordTransNet 坐标变换 4. GVnet 注视向量生成
依赖: pip install torch torchvision numpy opencv-python matplotlib scipy """
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from scipy.optimize import curve_fit import cv2 from typing import Tuple, Optional import math
class ResidualBlock(nn.Module): """残差块 + 注意力""" def __init__(self, in_ch: int, out_ch: int): super().__init__() self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1) self.bn1 = nn.BatchNorm2d(out_ch) self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1) self.bn2 = nn.BatchNorm2d(out_ch) self.attention = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(out_ch, max(out_ch // 16, 1), 1), nn.ReLU(), nn.Conv2d(max(out_ch // 16, 1), out_ch, 1), nn.Sigmoid() ) self.skip = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity() def forward(self, x): identity = self.skip(x) out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) att = self.attention(out) out = out * att return F.relu(out + identity)
class UResAtt(nn.Module): """ U-ResAtt: U-Net + 残差 + 注意力的瞳孔分割模型 输入: 眼部图像 (B, 3, H, W) 输出: 瞳孔二值掩码 (B, 1, H, W) """ def __init__(self, in_channels: int = 3, base_ch: int = 32): super().__init__() self.enc1 = nn.Sequential( ResidualBlock(in_channels, base_ch), ResidualBlock(base_ch, base_ch), ) self.enc2 = nn.Sequential( ResidualBlock(base_ch, base_ch * 2), ResidualBlock(base_ch * 2, base_ch * 2), ) self.enc3 = nn.Sequential( ResidualBlock(base_ch * 2, base_ch * 4), ResidualBlock(base_ch * 4, base_ch * 4), ) self.bottleneck = nn.Sequential( ResidualBlock(base_ch * 4, base_ch * 8), ResidualBlock(base_ch * 8, base_ch * 8), ) self.up3 = nn.ConvTranspose2d(base_ch * 8, base_ch * 4, 2, stride=2) self.dec3 = nn.Sequential( ResidualBlock(base_ch * 8, base_ch * 4), ResidualBlock(base_ch * 4, base_ch * 4), ) self.up2 = nn.ConvTranspose2d(base_ch * 4, base_ch * 2, 2, stride=2) self.dec2 = nn.Sequential( ResidualBlock(base_ch * 4, base_ch * 2), ResidualBlock(base_ch * 2, base_ch * 2), ) self.up1 = nn.ConvTranspose2d(base_ch * 2, base_ch, 2, stride=2) self.dec1 = nn.Sequential( ResidualBlock(base_ch * 2, base_ch), ResidualBlock(base_ch, base_ch), ) self.pool = nn.MaxPool2d(2) self.final = nn.Conv2d(base_ch, 1, 1) def forward(self, x): e1 = self.enc1(x) e2 = self.enc2(self.pool(e1)) e3 = self.enc3(self.pool(e2)) b = self.bottleneck(self.pool(e3)) d3 = self.up3(b) d3 = self.dec3(torch.cat([d3, e3], dim=1)) d2 = self.up2(d3) d2 = self.dec2(torch.cat([d2, e2], dim=1)) d1 = self.up1(d2) d1 = self.dec1(torch.cat([d1, e1], dim=1)) out = torch.sigmoid(self.final(d1)) return out
class EllipseFitError(nn.Module): """ 椭圆拟合误差 (EFE) 正则化 约束瞳孔分割边界为椭圆形状 """ def __init__(self, alpha: float = 1.0, beta: float = 0.3): """ Args: alpha: BCE 损失权重 beta: EFE 正则化权重 """ super().__init__() self.alpha = alpha self.beta = beta self.bce = nn.BCELoss() def forward(self, pred_mask: torch.Tensor, gt_mask: torch.Tensor, gt_ellipse: Optional[Tuple] = None) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ 计算总损失 = α·BCE + β·EFE Args: pred_mask: 预测掩码 (B, 1, H, W) gt_mask: 真值掩码 (B, 1, H, W) gt_ellipse: 真值椭圆参数 (cx, cy, a, b, theta) Returns: total_loss, bce_loss, efe_loss """ bce_loss = self.bce(pred_mask, gt_mask) if gt_ellipse is None: return self.alpha * bce_loss, bce_loss, torch.tensor(0.0) efe_loss = self._compute_efe(pred_mask, gt_ellipse) total = self.alpha * bce_loss + self.beta * efe_loss return total, bce_loss, efe_loss def _compute_efe(self, pred_mask: torch.Tensor, ellipses: list) -> torch.Tensor: """ 计算椭圆拟合误差 对预测掩码边界点,计算到 GT 椭圆的最近距离 """ batch_size = pred_mask.shape[0] total_efe = torch.zeros(batch_size, device=pred_mask.device) for b in range(batch_size): mask = pred_mask[b, 0].detach().cpu().numpy() contours, _ = cv2.findContours( (mask > 0.5).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) if len(contours) == 0 or len(contours[0]) < 5: continue ellipse = cv2.fitEllipse(contours[0]) if gt_ellipse_params := (ellipses[b] if b < len(ellipses) else None): cx1, cy1, a1, b1, t1 = ellipse cx2, cy2, a2, b2, t2 = gt_ellipse_params dist = math.sqrt((cx1-cx2)**2 + (cy1-cy2)**2) size_err = abs(a1-a2) + abs(b1-b2) angle_err = abs(t1 - t2) total_efe[b] = (dist + size_err + angle_err) / 100.0 return total_efe.mean()
class CoordTransNet(nn.Module): """ 坐标变换网络: 将多角度注视数据统一到标准空间 方法: 类似纸张展开的图像变形 + 线性插值 """ def __init__(self, input_dim: int = 2, hidden_dim: int = 64, output_dim: int = 2): super().__init__() self.transform = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, output_dim), ) def forward(self, gaze_point: torch.Tensor, angle: torch.Tensor) -> torch.Tensor: """ Args: gaze_point: (B, 2) 原始注视点 angle: (B,) 采集角度 Returns: transformed: (B, 2) 标准空间注视点 """ angle_rad = angle * math.pi / 180.0 cos_a = torch.cos(angle_rad).unsqueeze(1) sin_a = torch.sin(angle_rad).unsqueeze(1) x = torch.cat([gaze_point, cos_a, sin_a], dim=1) return self.transform(x)
class GazeTrackPipeline: """ GazeTrack 完整管道 端到端: 眼部图像 → 瞳孔分割 → 椭圆拟合 → 注视向量 """ def __init__(self, device: str = 'cpu'): self.device = device self.segmenter = UResAtt(in_channels=3, base_ch=32).to(device) self.loss_fn = EllipseFitError(alpha=1.0, beta=0.3) self.coord_transform = CoordTransNet().to(device) def predict_gaze(self, eye_image: np.ndarray) -> dict: """ 端到端注视估计 Args: eye_image: (H, W, 3) 眼部图像 Returns: results: 瞳孔掩码、中心、注视向量 """ img_tensor = torch.from_numpy(eye_image).float().permute(2, 0, 1).unsqueeze(0) / 255.0 img_tensor = img_tensor.to(self.device) with torch.no_grad(): mask = self.segmenter(img_tensor) mask_np = mask[0, 0].cpu().numpy() contours, _ = cv2.findContours( (mask_np > 0.5).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) if len(contours) == 0 or len(contours[0]) < 5: return {'success': False, 'reason': 'no_pupil_detected'} ellipse = cv2.fitEllipse(contours[0]) cx, cy = ellipse[0] a, b = ellipse[1] angle = ellipse[2] h, w = eye_image.shape[:2] gaze_x = (cx - w / 2) / (w / 2) gaze_y = (cy - h / 2) / (h / 2) ratio = b / a if a > 0 else 1.0 gaze_pitch = math.degrees(math.acos(np.clip(ratio, 0, 1))) - 90 return { 'success': True, 'pupil_center': (float(cx), float(cy)), 'ellipse_params': { 'cx': float(cx), 'cy': float(cy), 'a': float(a), 'b': float(b), 'angle': float(angle) }, 'gaze_x': float(gaze_x), 'gaze_y': float(gaze_y), 'gaze_pitch': float(gaze_pitch), 'gaze_yaw': float(math.degrees(math.atan2(gaze_x, 1.0))), 'mask': mask_np, }
if __name__ == "__main__": print("=" * 60) print("GazeTrack 高精度眼动追踪测试") print("论文: arXiv:2511.22607") print("=" * 60) device = 'cpu' pipeline = GazeTrackPipeline(device=device) np.random.seed(42) img = np.zeros((128, 128, 3), dtype=np.uint8) img[:] = 30 cv2.ellipse(img, (64, 64), (12, 8), 15, 0, 360, (200, 200, 200), -1) cv2.circle(img, (60, 60), 2, (255, 255, 255), -1) noise = np.random.normal(0, 10, img.shape).astype(np.uint8) img = np.clip(img.astype(int) + noise, 0, 255).astype(np.uint8) result = pipeline.predict_gaze(img) if result['success']: print(f"\n瞳孔中心: ({result['pupil_center'][0]:.1f}, {result['pupil_center'][1]:.1f})") print(f"椭圆参数: a={result['ellipse_params']['a']:.1f}, " f"b={result['ellipse_params']['b']:.1f}, " f"angle={result['ellipse_params']['angle']:.1f}°") print(f"注视向量: x={result['gaze_x']:.3f}, y={result['gaze_y']:.3f}") print(f"视线角度: pitch={result['gaze_pitch']:.1f}°, yaw={result['gaze_yaw']:.1f}°") else: print(f"检测失败: {result.get('reason', 'unknown')}") print(f"\n=== 模型参数量 ===") total_params = sum(p.numel() for p in pipeline.segmenter.parameters()) print(f"U-ResAtt 分割模型: {total_params:,} ({total_params/1e6:.2f}M)") total_coord = sum(p.numel() for p in pipeline.coord_transform.parameters()) print(f"CoordTransNet: {total_coord:,} ({total_coord/1e6:.4f}M)") print(f"\n=== 损失函数测试 ===") pred_mask = torch.sigmoid(torch.randn(2, 1, 64, 64)) gt_mask = torch.zeros(2, 1, 64, 64) for b in range(2): mask = np.zeros((64, 64), dtype=np.uint8) cv2.ellipse(mask, (32, 32), (10, 7), 20, 0, 360, 1, -1) gt_mask[b, 0] = torch.from_numpy(mask).float() total_loss, bce_loss, efe_loss = pipeline.loss_fn(pred_mask, gt_mask) print(f"总损失: {total_loss.item():.4f}") print(f"BCE 损失: {bce_loss.item():.4f}") print(f"EFE 正则化: {efe_loss.item():.4f}") print(f"\n=== 性能对比 (论文数据) ===") print(f"{'方法':<20s} {'角度误差(°)':<15s} {'计算复杂度':<15s}") print(f"{'GazeTrack (本文)':<20s} {'降低':<15s} {'更低':<15s}") print(f"{'NVIDIA NVGaze':<20s} {'2.06±0.44':<15s} {'中':<15s}") print(f"{'MPIIGaze':<20s} {'4.5-6.0':<15s} {'低':<15s}") print(f"{'ETH-XGaze':<20s} {'3.0-5.0':<15s} {'中':<15s}")
|