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 389 390 391 392 393 394 395
| """ InCaRPose: 车内相对相机位姿估计模型
论文:InCaRPose: In-Cabin Relative Camera Pose Estimation Model and Dataset 作者:Stillger et al. """
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from typing import Tuple
class PositionalEncoding(nn.Module): """旋转位置编码 (RoPE)""" def __init__(self, dim: int, max_seq_len: int = 196): super().__init__() self.dim = dim freqs = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim)) positions = torch.arange(max_seq_len) freqs = torch.outer(positions, freqs) self.register_buffer('cos_cached', freqs.cos()) self.register_buffer('sin_cached', freqs.sin()) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 应用旋转位置编码 Args: x: [B, N, D] 输入特征 Returns: 编码后的特征 """ seq_len = x.shape[1] cos = self.cos_cached[:seq_len].unsqueeze(0) sin = self.sin_cached[:seq_len].unsqueeze(0) x1, x2 = x[..., ::2], x[..., 1::2] x_rotated = torch.cat([ x1 * cos - x2 * sin, x1 * sin + x2 * cos ], dim=-1) return x_rotated
class TransformerDecoderLayer(nn.Module): """Transformer解码器层""" def __init__(self, dim: int, num_heads: int = 8, mlp_ratio: float = 4.0): super().__init__() self.self_attn = nn.MultiheadAttention(dim, num_heads, batch_first=True) self.cross_attn = nn.MultiheadAttention(dim, num_heads, batch_first=True) self.norm1 = nn.LayerNorm(dim) self.norm2 = nn.LayerNorm(dim) self.norm3 = nn.LayerNorm(dim) self.mlp = nn.Sequential( nn.Linear(dim, int(dim * mlp_ratio)), nn.GELU(), nn.Linear(int(dim * mlp_ratio), dim) ) def forward(self, x: torch.Tensor, memory: torch.Tensor) -> torch.Tensor: """ 解码器前向传播 Args: x: [B, N, D] 目标查询 memory: [B, M, D] 编码器输出 Returns: 更新后的查询 """ x2 = self.norm1(x) x = x + self.self_attn(x2, x2, x2)[0] x2 = self.norm2(x) x = x + self.cross_attn(x2, memory, memory)[0] x = x + self.mlp(self.norm3(x)) return x
class PoseHead(nn.Module): """位姿预测头""" def __init__(self, dim: int, hidden_dim: int = 256): super().__init__() self.rotation_head = nn.Sequential( nn.Linear(dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, 4) ) self.translation_head = nn.Sequential( nn.Linear(dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, 3) ) def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ 预测相对位姿 Args: x: [B, D] 全局特征 Returns: rotation: [B, 4] 归一化四元数 translation: [B, 3] 平移向量(米) """ rotation = self.rotation_head(x) rotation = F.normalize(rotation, dim=-1) translation = self.translation_head(x) return rotation, translation
class InCaRPose(nn.Module): """ InCaRPose: 车内相对相机位姿估计模型 特点: 1. 使用冻结的DINOv3作为视觉编码器 2. Transformer解码器融合双视图特征 3. 轻量预测头输出度量尺度位姿 """ def __init__( self, backbone: str = 'dinov2_vits14', feature_dim: int = 384, num_decoder_layers: int = 6, num_heads: int = 6, freeze_backbone: bool = True ): super().__init__() self.feature_dim = feature_dim self.backbone = torch.hub.load('facebookresearch/dinov2', backbone) if freeze_backbone: for param in self.backbone.parameters(): param.requires_grad = False self.proj = nn.Linear(feature_dim, feature_dim) self.pos_embed = PositionalEncoding(feature_dim) self.decoder_layers = nn.ModuleList([ TransformerDecoderLayer(feature_dim, num_heads) for _ in range(num_decoder_layers) ]) self.query_token = nn.Parameter(torch.randn(1, 1, feature_dim)) self.pose_head = PoseHead(feature_dim) def extract_features(self, x: torch.Tensor) -> torch.Tensor: """ 提取图像特征 Args: x: [B, 3, H, W] 输入图像 Returns: [B, N, D] 图像特征 """ features = self.backbone.forward_features(x) features = self.proj(features) return features def forward( self, ref_image: torch.Tensor, target_image: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ 预测相对位姿 Args: ref_image: [B, 3, H, W] 参考图像(标定状态) target_image: [B, 3, H, W] 目标图像(当前状态) Returns: rotation: [B, 4] 四元数 [w, x, y, z] translation: [B, 3] 平移向量 [tx, ty, tz](米) confidence: [B] 位姿置信度 """ batch_size = ref_image.shape[0] ref_features = self.extract_features(ref_image) target_features = self.extract_features(target_image) ref_features = self.pos_embed(ref_features) target_features = self.pos_embed(target_features) query = self.query_token.expand(batch_size, -1, -1) for decoder_layer in self.decoder_layers: query = decoder_layer(query, ref_features) query = decoder_layer(query, target_features) global_feature = query.squeeze(1) rotation, translation = self.pose_head(global_feature) confidence = torch.sigmoid(torch.mean(global_feature, dim=-1)) return rotation, translation, confidence
class PoseLoss(nn.Module): """位姿损失函数""" def __init__(self, rotation_weight: float = 1.0, translation_weight: float = 1.0): super().__init__() self.rotation_weight = rotation_weight self.translation_weight = translation_weight def quaternion_angular_error( self, q_pred: torch.Tensor, q_gt: torch.Tensor ) -> torch.Tensor: """ 计算四元数角度误差 Args: q_pred: [B, 4] 预测四元数 q_gt: [B, 4] 真值四元数 Returns: [B] 角度误差(度) """ dot = torch.sum(q_pred * q_gt, dim=-1) dot = torch.abs(dot) dot = torch.clamp(dot, -1.0, 1.0) angle = 2.0 * torch.acos(dot) * 180.0 / 3.14159 return angle def forward( self, rotation_pred: torch.Tensor, translation_pred: torch.Tensor, rotation_gt: torch.Tensor, translation_gt: torch.Tensor ) -> Tuple[torch.Tensor, dict]: """ 计算总损失 Args: rotation_pred: [B, 4] 预测旋转 translation_pred: [B, 3] 预测平移 rotation_gt: [B, 4] 真值旋转 translation_gt: [B, 3] 真值平移 Returns: total_loss: 总损失 metrics: 各项指标 """ angle_error = self.quaternion_angular_error(rotation_pred, rotation_gt) rotation_loss = torch.mean(angle_error) translation_error = torch.norm(translation_pred - translation_gt, dim=-1) translation_loss = torch.mean(translation_error) total_loss = ( self.rotation_weight * rotation_loss + self.translation_weight * translation_loss ) metrics = { 'rotation_error_deg': rotation_loss.item(), 'translation_error_m': translation_loss.item(), 'total_loss': total_loss.item() } return total_loss, metrics
if __name__ == "__main__": model = InCaRPose( backbone='dinov2_vits14', feature_dim=384, num_decoder_layers=6, num_heads=6 ) batch_size = 2 ref_image = torch.randn(batch_size, 3, 224, 224) target_image = torch.randn(batch_size, 3, 224, 224) model.eval() with torch.no_grad(): rotation, translation, confidence = model(ref_image, target_image) print("=" * 60) print("InCaRPose 测试结果") print("=" * 60) print(f"输入图像尺寸: {ref_image.shape}") print(f"旋转输出(四元数): {rotation.shape}") print(f"平移输出(米): {translation.shape}") print(f"置信度: {confidence.shape}") print() print(f"预测旋转(样本1): {rotation[0].numpy()}") print(f"预测平移(样本1): {translation[0].numpy()} 米") print(f"置信度(样本1): {confidence[0].item():.4f}") print() total_params = sum(p.numel() for p in model.parameters()) trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) print(f"总参数量: {total_params / 1e6:.2f}M") print(f"可训练参数量: {trainable_params / 1e6:.2f}M") import time model.eval() with torch.no_grad(): _ = model(ref_image, target_image) start = time.time() for _ in range(100): _ = model(ref_image, target_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")
|