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
| import torch import torch.nn as nn from typing import Tuple
class GazeAnywhere(nn.Module): """ GazeAnywhere: 可提示视线目标估计模型 论文: CVPR 2026 架构: 冻结DINOv3 + 冻结文本编码器 + Transformer检测器 核心创新: 1. 自然语言提示指定目标人物 2. 端到端,无中间检测阶段 3. 同时解决定位+在帧判断+视线估计 """ def __init__(self, dino_model_name='dinov3_vitl14', text_embed_dim=768, hidden_dim=256, num_queries=100, num_decoder_layers=6): super().__init__() self.image_encoder = self._load_frozen_dino(dino_model_name) D_V = self.image_encoder.embed_dim self.text_encoder = self._load_frozen_text_encoder() D_T = text_embed_dim self.image_proj = nn.Linear(D_V, hidden_dim) self.text_proj = nn.Linear(D_T, hidden_dim) decoder_layer = nn.TransformerDecoderLayer( d_model=hidden_dim, nhead=8, dim_feedforward=hidden_dim * 4, dropout=0.1, batch_first=True ) self.transformer_decoder = nn.TransformerDecoder( decoder_layer, num_layers=num_decoder_layers ) self.queries = nn.Embedding(num_queries, hidden_dim) self.bbox_head = MLP(hidden_dim, hidden_dim, 4, 3) self.presence_head = nn.Linear(hidden_dim, 1) self.gaze_head = MLP(hidden_dim, hidden_dim, 2, 3) self.gaze_heatmap_head = nn.Linear(hidden_dim, 1) def _load_frozen_dino(self, name): """加载冻结的DINOv3模型""" model = torch.hub.load('facebookresearch/dinov3', name) for param in model.parameters(): param.requires_grad = False return model def _load_frozen_text_encoder(self): """加载冻结的文本编码器""" model = torch.hub.load('facebookresearch/dinov3', 'dinotxt_base') for param in model.parameters(): param.requires_grad = False return model def forward(self, image: torch.Tensor, text_prompt: str = None, visual_prompt: Tuple[float, float] = None) -> dict: """ 前向传播 Args: image: (B, 3, H, W) 输入图像 text_prompt: 文本提示字符串 visual_prompt: (x, y) 归一化坐标提示 Returns: dict: { 'bbox': (B, 4) 头部边界框, 'presence': (B, 1) 在画面内的概率, 'gaze_point': (B, 2) 视线落点, 'gaze_heatmap': (B, H//14, W//14) 视线热力图 } """ B = image.shape[0] with torch.no_grad(): visual_features = self.image_encoder(image) visual_features = self.image_proj(visual_features) if text_prompt is not None: with torch.no_grad(): text_features = self.text_encoder(text_prompt) text_features = self.text_proj(text_features) text_features = text_features.unsqueeze(1) elif visual_prompt is not None: coord_embed = self._coord_to_embed(visual_prompt, visual_features, image) text_features = coord_embed queries = self.queries.weight.unsqueeze(0).expand(B, -1, -1) memory = torch.cat([visual_features, text_features], dim=1) decoded = self.transformer_decoder(queries, memory) subject_feat = decoded[:, 0, :] bbox = self.bbox_head(subject_feat).sigmoid() presence = self.presence_head(subject_feat).sigmoid() gaze_point = self.gaze_head(subject_feat).sigmoid() heatmap_logits = self.gaze_heatmap_head(decoded) gaze_heatmap = heatmap_logits.sigmoid() return { 'bbox': bbox, 'presence': presence, 'gaze_point': gaze_point, 'gaze_heatmap': gaze_heatmap } def _coord_to_embed(self, coord, visual_features, image): """将坐标提示转换为embedding(通过位置编码)""" B, N, D = visual_features.shape H_patches = image.shape[2] // 14 W_patches = image.shape[3] // 14 x_idx = int(coord[0] * W_patches) y_idx = int(coord[1] * H_patches) token_idx = y_idx * W_patches + x_idx + 1 coord_embed = visual_features[:, token_idx:token_idx+1, :] return coord_embed
class MLP(nn.Module): """多层感知机""" def __init__(self, input_dim, hidden_dim, output_dim, num_layers): super().__init__() h = [hidden_dim] * (num_layers - 1) self.layers = nn.ModuleList( nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) ) def forward(self, x): for i, layer in enumerate(self.layers): x = torch.relu(layer(x)) if i < len(self.layers) - 1 else layer(x) return x
if __name__ == "__main__": model = GazeAnywhere() model.eval() image = torch.randn(2, 3, 224, 224) text_prompt = "the person wearing a red shirt" with torch.no_grad(): output = model(image, text_prompt=text_prompt) print("=== GazeAnywhere 测试 ===") print(f"输入图像: {image.shape}") print(f"文本提示: '{text_prompt}'") print(f"预测bbox: {output['bbox'].shape} → {output['bbox'][0].tolist()}") print(f"在画面内: {output['presence'][0].item():.4f}") print(f"视线落点: {output['gaze_point'][0].tolist()}") print(f"视线热力图: {output['gaze_heatmap'].shape}") print() print("论文核心价值: 端到端,无中间检测阶段") print("→ IMS应用: 可用自然语言指定驾驶员,无需人脸检测前置")
|