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
| """ Gaze3D: 增强现实世界3D视线估计
论文:Enhancing 3D Gaze Estimation in the Wild using Weak Supervision with Gaze Following Labels 会议:CVPR 2025 作者:Vuillecard, Odobez """
import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, Optional import numpy as np
class PositionalEncoding3D(nn.Module): """3D位置编码""" def __init__(self, dim: int): super().__init__() self.dim = dim self.pos_embed = nn.Parameter(torch.randn(1, dim)) def forward(self, x: torch.Tensor) -> torch.Tensor: """添加位置编码""" return x + self.pos_embed
class GazeTransformer(nn.Module): """ Gaze Transformer: 视线估计核心模块 基于Swin3D特征,预测3D视线向量 """ def __init__( self, feature_dim: int = 768, num_heads: int = 8, num_layers: int = 4, dropout: float = 0.1 ): super().__init__() self.feature_dim = feature_dim self.head_proj = nn.Linear(feature_dim, feature_dim) self.scene_proj = nn.Linear(feature_dim, feature_dim) encoder_layer = nn.TransformerEncoderLayer( d_model=feature_dim, nhead=num_heads, dim_feedforward=feature_dim * 4, dropout=dropout, batch_first=True ) self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) self.gaze_head = nn.Sequential( nn.Linear(feature_dim, feature_dim // 2), nn.ReLU(), nn.Dropout(dropout), nn.Linear(feature_dim // 2, 3) ) self.confidence_head = nn.Sequential( nn.Linear(feature_dim, 1), nn.Sigmoid() ) def forward( self, head_features: torch.Tensor, scene_features: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ 前向传播 Args: head_features: [B, D] 头部特征 scene_features: [B, D] 场景特征 Returns: gaze_vector: [B, 3] 归一化3D视线向量 confidence: [B, 1] 预测置信度 """ head_feat = self.head_proj(head_features) scene_feat = self.scene_proj(scene_features) combined = torch.stack([head_feat, scene_feat], dim=1) encoded = self.transformer(combined) global_feat = encoded.mean(dim=1) gaze = self.gaze_head(global_feat) gaze_vector = F.normalize(gaze, dim=-1) confidence = self.confidence_head(global_feat) return gaze_vector, confidence
class Gaze3DModel(nn.Module): """ Gaze3D完整模型 特点: 1. 支持图像和视频输入 2. 弱监督学习框架 3. 时序建模能力 """ def __init__( self, backbone: str = 'swin3d', feature_dim: int = 768, use_temporal: bool = True, temporal_window: int = 16 ): super().__init__() self.use_temporal = use_temporal self.temporal_window = temporal_window self.backbone = self._build_backbone(backbone, feature_dim) self.gaze_transformer = GazeTransformer(feature_dim) if use_temporal: self.temporal_encoder = nn.LSTM( input_size=feature_dim, hidden_size=feature_dim // 2, num_layers=2, batch_first=True, bidirectional=True ) self.proj_2d = nn.Linear(3, 2) def _build_backbone(self, name: str, dim: int) -> nn.Module: """构建视觉编码器""" return nn.Sequential( nn.Conv2d(3, 64, 7, 2, 3), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(3, 2, 1), nn.Conv2d(64, 128, 3, 2, 1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(128, 256, 3, 2, 1), nn.BatchNorm2d(256), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(256, dim) ) def extract_features(self, image: torch.Tensor) -> torch.Tensor: """ 提取图像特征 Args: image: [B, 3, H, W] 输入图像 Returns: [B, D] 特征向量 """ return self.backbone(image) def forward( self, head_image: torch.Tensor, scene_image: torch.Tensor, temporal_features: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ 前向传播 Args: head_image: [B, 3, H, W] 头部图像 scene_image: [B, 3, H, W] 场景图像 temporal_features: [B, T, D] 时序特征(可选) Returns: gaze_vector: [B, 3] 3D视线向量 confidence: [B, 1] 置信度 gaze_2d: [B, 2] 2D落点预测 """ head_feat = self.extract_features(head_image) scene_feat = self.extract_features(scene_image) if self.use_temporal and temporal_features is not None: combined_feat = (head_feat + scene_feat) / 2 temporal_input = torch.cat([ temporal_features, combined_feat.unsqueeze(1) ], dim=1) temporal_feat, _ = self.temporal_encoder(tempinal_input) scene_feat = scene_feat + temporal_feat[:, -1, :] gaze_vector, confidence = self.gaze_transformer(head_feat, scene_feat) gaze_2d = self.proj_2d(gaze_vector) return gaze_vector, confidence, gaze_2d
class Gaze3DLoss(nn.Module): """ Gaze3D损失函数 包含: 1. 3D视线向量损失(有监督) 2. 2D落点投影损失(弱监督) 3. 置信度损失 """ def __init__( self, lambda_3d: float = 1.0, lambda_2d: float = 0.5, lambda_conf: float = 0.1 ): super().__init__() self.lambda_3d = lambda_3d self.lambda_2d = lambda_2d self.lambda_conf = lambda_conf def forward( self, gaze_pred: torch.Tensor, gaze_2d_pred: torch.Tensor, confidence: torch.Tensor, gaze_gt: Optional[torch.Tensor] = None, gaze_2d_gt: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, dict]: """ 计算损失 Args: gaze_pred: [B, 3] 预测3D视线 gaze_2d_pred: [B, 2] 预测2D落点 confidence: [B, 1] 置信度 gaze_gt: [B, 3] 真值3D视线(可选) gaze_2d_gt: [B, 2] 真值2D落点(可选) Returns: total_loss: 总损失 metrics: 各项指标 """ total_loss = torch.tensor(0.0, device=gaze_pred.device) metrics = {} if gaze_gt is not None: cos_sim = F.cosine_similarity(gaze_pred, gaze_gt, dim=-1) angle_error = torch.acos(torch.clamp(cos_sim, -1, 1)) * 180 / 3.14159 loss_3d = torch.mean(angle_error) total_loss = total_loss + self.lambda_3d * loss_3d metrics['angle_error_deg'] = loss_3d.item() if gaze_2d_gt is not None: loss_2d = F.mse_loss(gaze_2d_pred, gaze_2d_gt) total_loss = total_loss + self.lambda_2d * loss_2d metrics['2d_error'] = loss_2d.item() loss_conf = -torch.mean(torch.log(confidence + 1e-7)) total_loss = total_loss + self.lambda_conf * loss_conf metrics['confidence'] = confidence.mean().item() metrics['total_loss'] = total_loss.item() return total_loss, metrics
if __name__ == "__main__": print("=" * 60) print("Gaze3D模型测试") print("=" * 60) model = Gaze3DModel( backbone='swin3d', feature_dim=768, use_temporal=True ) batch_size = 2 head_image = torch.randn(batch_size, 3, 224, 224) scene_image = torch.randn(batch_size, 3, 224, 224) model.eval() with torch.no_grad(): gaze_vector, confidence, gaze_2d = model(head_image, scene_image) print(f"\n输入尺寸:") print(f" 头部图像: {head_image.shape}") print(f" 场景图像: {scene_image.shape}") print(f"\n输出尺寸:") print(f" 3D视线向量: {gaze_vector.shape}") print(f" 置信度: {confidence.shape}") print(f" 2D落点: {gaze_2d.shape}") print(f"\n预测示例(样本1):") print(f" 3D视线: [{gaze_vector[0, 0]:.4f}, {gaze_vector[0, 1]:.4f}, {gaze_vector[0, 2]:.4f}]") print(f" 置信度: {confidence[0, 0]:.4f}") print(f" 2D落点: [{gaze_2d[0, 0]:.4f}, {gaze_2d[0, 1]:.4f}]") total_params = sum(p.numel() for p in model.parameters()) print(f"\n模型参数量: {total_params / 1e6:.2f}M") import time with torch.no_grad(): _ = model(head_image, scene_image) start = time.time() for _ in range(100): _ = model(head_image, scene_image) end = time.time() avg_time = (end - start) / 100 * 1000 fps = 1000 / avg_time print(f"平均推理时间: {avg_time:.2f} ms") print(f"帧率: {fps:.1f} FPS") print("\n" + "=" * 60) print("损失函数测试") print("=" * 60) criterion = Gaze3DLoss() gaze_gt = torch.randn(batch_size, 3) gaze_gt = F.normalize(gaze_gt, dim=-1) gaze_2d_gt = torch.randn(batch_size, 2) loss, metrics = criterion(gaze_vector, gaze_2d, confidence, gaze_gt, gaze_2d_gt) print(f"\n损失指标:") for k, v in metrics.items(): print(f" {k}: {v:.4f}")
|