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
| import torch import torch.nn as nn import torch.nn.functional as F
class DepthPoseEstimationNet(nn.Module): """ 深度图像3D姿态估计网络 论文核心架构:多分支特征提取 + 3D提升 """ def __init__(self, num_joints: int = 17): super().__init__() self.num_joints = num_joints self.depth_encoder = self._build_encoder() self.ir_encoder = self._build_encoder() self.fusion = nn.Sequential( nn.Conv2d(128, 256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True), nn.Conv2d(256, 256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True), ) self.heatmap_head = nn.Conv2d(256, num_joints, 1) self.lift_head = nn.Sequential( nn.Linear(num_joints * 64, 512), nn.ReLU(inplace=True), nn.Dropout(0.5), nn.Linear(512, num_joints * 3) ) self.depth_head = nn.Conv2d(256, 1, 1) def _build_encoder(self) -> nn.Module: """构建编码器""" return nn.Sequential( nn.Conv2d(1, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.Conv2d(64, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), ) def forward(self, depth_img: torch.Tensor, ir_img: torch.Tensor) -> dict: """ 前向传播 Args: depth_img: 深度图 (B, 1, H, W) ir_img: 红外图 (B, 1, H, W) Returns: output: { 'keypoints_3d': (B, num_joints, 3), 'heatmaps': (B, num_joints, H/8, W/8), 'depth_pred': (B, 1, H/8, W/8) } """ depth_feat = self.depth_encoder(depth_img) ir_feat = self.ir_encoder(ir_img) fused = torch.cat([depth_feat, ir_feat], dim=1) fused = self.fusion(fused) heatmaps = self.heatmap_head(fused) B, C, H, W = heatmaps.shape heatmap_flat = heatmaps.view(B, C, -1) keypoints_3d = self.lift_head(heatmap_flat) keypoints_3d = keypoints_3d.view(B, self.num_joints, 3) depth_pred = self.depth_head(fused) return { 'keypoints_3d': keypoints_3d, 'heatmaps': heatmaps, 'depth_pred': depth_pred }
class FewShotTrainer: """ 少样本训练策略 论文方法:<100样本微调 """ def __init__(self, model: nn.Module): self.model = model self.pretrained = False def pretrain_on_synthetic(self, synthetic_loader, epochs: int = 100): """ 合成数据预训练 Args: synthetic_loader: 合成数据(自动标注) epochs: 预训练轮数 """ print("=== 合成数据预训练 ===") optimizer = torch.optim.Adam(self.model.parameters(), lr=1e-3) criterion = nn.MSELoss() for epoch in range(epochs): for batch in synthetic_loader: depth = batch['depth'] ir = batch['ir'] keypoints_gt = batch['keypoints_3d'] output = self.model(depth, ir) loss = criterion(output['keypoints_3d'], keypoints_gt) optimizer.zero_grad() loss.backward() optimizer.step() if epoch % 20 == 0: print(f"Epoch {epoch}, Loss: {loss.item():.4f}") self.pretrained = True print("预训练完成") def finetune_on_real(self, real_loader, epochs: int = 20): """ 真实数据微调 Args: real_loader: 真实数据(<100样本) epochs: 微调轮数 """ if not self.pretrained: raise ValueError("请先预训练") print(f"=== 真实数据微调({len(real_loader.dataset)}样本)===") optimizer = torch.optim.Adam(self.model.parameters(), lr=1e-5) criterion = nn.MSELoss() for epoch in range(epochs): for batch in real_loader: depth = batch['depth'] ir = batch['ir'] keypoints_gt = batch['keypoints_3d'] output = self.model(depth, ir) loss = criterion(output['keypoints_3d'], keypoints_gt) optimizer.zero_grad() loss.backward() optimizer.step() print(f"Epoch {epoch}, Loss: {loss.item():.4f}") print("微调完成") def evaluate(self, test_loader) -> dict: """ 评估模型 Returns: metrics: { 'mpjpe': Mean Per Joint Position Error (cm), 'pck': Percentage of Correct Keypoints } """ errors = [] for batch in test_loader: depth = batch['depth'] ir = batch['ir'] keypoints_gt = batch['keypoints_3d'] output = self.model(depth, ir) keypoints_pred = output['keypoints_3d'] error = torch.norm(keypoints_pred - keypoints_gt, dim=-1) errors.append(error) errors = torch.cat(errors) mpjpe = errors.mean().item() * 100 pck = (errors < 0.1).float().mean().item() return { 'mpjpe': mpjpe, 'pck': pck }
if __name__ == "__main__": model = DepthPoseEstimationNet(num_joints=17) total_params = sum(p.numel() for p in model.parameters()) print(f"模型参数: {total_params:,}") depth = torch.randn(1, 1, 256, 256) ir = torch.randn(1, 1, 256, 256) output = model(depth, ir) print(f"3D关键点形状: {output['keypoints_3d'].shape}") print(f"热图形状: {output['heatmaps'].shape}")
|