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
| class GazeObjectTransformer(nn.Module): """ 基于Transformer交叉注意力的注视物体预测模型 论文 Section 4.3 核心 Query: 面部+眼部特征 Key/Value: 交通物体空间特征 输出: 每个物体的注意力权重 + 背景类 准确率: 60%(vs PoG关联方法 51%) 错误率: 11.68%(vs PoG方法 23.21%,降低49.7%) """ def __init__(self, face_feat_dim: int = 512, obj_feat_dim: int = 128, d_model: int = 256, nhead: int = 8, num_layers: int = 3): super().__init__() self.face_proj = nn.Linear(face_feat_dim, d_model) self.obj_proj = nn.Linear(obj_feat_dim, d_model) self.pos_embed = nn.Sequential( nn.Linear(4, 64), nn.ReLU(), nn.Linear(64, d_model) ) cross_attention_layer = nn.TransformerDecoderLayer( d_model=d_model, nhead=nhead, dim_feedforward=512, dropout=0.1, batch_first=True ) self.cross_attention = nn.TransformerDecoder( cross_attention_layer, num_layers=num_layers ) self.classifier = nn.Sequential( nn.Linear(d_model, 128), nn.ReLU(), nn.Dropout(0.1), nn.Linear(128, 1) ) def forward(self, face_features: torch.Tensor, obj_features: torch.Tensor, obj_bboxes: torch.Tensor) -> dict: """ Args: face_features: (B, 512) 面部+眼部融合特征 obj_features: (B, N, 128) 物体空间特征 obj_bboxes: (B, N, 4) 物体归一化坐标 Returns: output: { 'scores': (B, N+1) 每个物体+背景的得分, 'attn_weights': (B, 1, N) 注意力权重 } """ B, N, _ = obj_features.shape face_query = self.face_proj(face_features) obj_kv = self.obj_proj(obj_features) pos = self.pos_embed(obj_bboxes) obj_kv = obj_kv + pos face_query = face_query.unsqueeze(1) attn_out = self.cross_attention( tgt=face_query, memory=obj_kv ) attn_weights = torch.matmul( face_query, obj_kv.transpose(-1, -2) ) / (256 ** 0.5) obj_scores = self.classifier(attn_out.squeeze(1)) bg_score = attn_weights.mean(dim=-1) all_scores = torch.cat([obj_scores.squeeze(-1), bg_score.squeeze(-1)], dim=-1) return { 'scores': all_scores, 'attn_weights': attn_weights }
class TransGazeObjectInference: """ TransGaze-Object 完整推理流程 从摄像头输入到注视物体预测的端到端流程 """ def __init__(self, device='cuda'): self.device = device self.face_extractor = FacialFeatureExtractor() self.face_encoder = DualStreamFaceEncoder().to(device).eval() self.object_encoder = TrafficObjectEncoder().to(device).eval() self.gaze_transformer = GazeObjectTransformer().to(device).eval() from ultralytics import YOLO self.detector = YOLO('yolov8n.pt') self.transform = __import__('torchvision.transforms').transforms.Compose([ __import__('torchvision.transforms').transforms.ToPILImage(), __import__('torchvision.transforms').transforms.Resize((224, 224)), __import__('torchvision.transforms').transforms.ToTensor(), __import__('torchvision.transforms').transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ]) def predict(self, face_img: np.ndarray, scene_img: np.ndarray) -> dict: """ 端到端注视物体预测 Args: face_img: 驾驶员面部图像 (H, W, 3) BGR scene_img: 前向场景图像 (H, W, 3) BGR Returns: result: { 'gaze_object_idx': int, # 注视物体索引(-1=背景) 'gaze_object_class': str, # 物体类别 'confidence': float, # 置信度 'all_scores': np.ndarray # 所有物体得分 } """ with torch.no_grad(): face_data = self.face_extractor.extract(face_img) if face_data is None: return {'gaze_object_idx': -1, 'confidence': 0.0} face_tensor = self.transform(face_data['face_roi']).unsqueeze(0).to(self.device) eye_tensor = self.transform(face_data['eye_roi']).unsqueeze(0).to(self.device) face_feat = self.face_encoder(face_tensor, eye_tensor) results = self.detector(scene_img, verbose=False) boxes = results[0].boxes if len(boxes) == 0: return {'gaze_object_idx': -1, 'confidence': 1.0} h, w = scene_img.shape[:2] bboxes = [] obj_types = [] for box in boxes: x1, y1, x2, y2 = box.xyxy[0].cpu().numpy() bboxes.append([x1/w, y1/h, x2/w, y2/h]) obj_types.append(int(box.cls[0])) bboxes = torch.tensor(bboxes).float().unsqueeze(0).to(self.device) obj_types = torch.tensor(obj_types).long().unsqueeze(0).to(self.device) obj_feat = self.object_encoder(bboxes, obj_types) output = self.gaze_transformer(face_feat, obj_feat, bboxes) scores = output['scores'] probs = torch.softmax(scores, dim=-1) pred_idx = probs.argmax(dim=-1).item() confidence = probs.max().item() if pred_idx >= len(boxes): gaze_class = 'background' gaze_idx = -1 else: gaze_idx = pred_idx gaze_class = results[0].names[int(boxes[pred_idx].cls[0])] return { 'gaze_object_idx': gaze_idx, 'gaze_object_class': gaze_class, 'confidence': confidence, 'all_scores': probs.cpu().numpy() }
if __name__ == "__main__": import numpy as np inference = TransGazeObjectInference(device='cpu') face_img = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) scene_img = np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8) result = inference.predict(face_img, scene_img) print(f"注视物体: {result['gaze_object_class']}") print(f"置信度: {result['confidence']:.4f}") print(f"所有得分: {result['all_scores']}")
|