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
| import torch import torch.nn as nn import torch.nn.functional as F from typing import Dict, Tuple, Optional
class Monocular3DPoseEstimator(nn.Module): """ 单目3D姿态估计器 方法:2D关键点检测 + 3D提升 步骤: 1. 2D关键点检测(使用HRNet/HigherHRNet) 2. 2D关键点提升到3D(使用图卷积网络) 3. 后处理优化 """ def __init__(self, num_joints: int = 17, heatmap_size: Tuple[int, int] = (64, 48), depth_range: Tuple[float, float] = (-0.5, 0.5)): """ 初始化 Args: num_joints: 关节点数量 heatmap_size: 热图尺寸 depth_range: 深度范围(米) """ super().__init__() self.num_joints = num_joints self.heatmap_size = heatmap_size self.depth_range = depth_range self.backbone = HRNetBackbone() self.heatmap_head = nn.Sequential( nn.Conv2d(256, 256, 3, padding=1), nn.ReLU(), nn.Conv2d(256, num_joints, 1) ) self.lift_net = PoseLifter(num_joints) self.depth_head = nn.Sequential( nn.Conv2d(256, 256, 3, padding=1), nn.ReLU(), nn.Conv2d(256, num_joints, 1) ) def forward(self, image: torch.Tensor) -> Dict: """ 前向传播 Args: image: 输入图像 (B, C, H, W) Returns: output: 包含2D/3D姿态的字典 """ features = self.backbone(image) heatmaps_2d = self.heatmap_head(features) depth_maps = self.depth_head(features) keypoints_2d = self._extract_keypoints_from_heatmap(heatmaps_2d) depths = self._extract_depth_from_map(depth_maps, keypoints_2d) keypoints_3d = self._lift_to_3d(keypoints_2d, depths) keypoints_3d_refined = self.lift_net(keypoints_3d) return { 'heatmaps_2d': heatmaps_2d, 'depth_maps': depth_maps, 'keypoints_2d': keypoints_2d, 'keypoints_3d': keypoints_3d_refined } def _extract_keypoints_from_heatmap(self, heatmaps: torch.Tensor) -> torch.Tensor: """ 从热图提取关键点 Args: heatmaps: 热图 (B, J, H, W) Returns: keypoints: 2D坐标 (B, J, 2) """ B, J, H, W = heatmaps.shape keypoints = [] for j in range(J): heatmap = heatmaps[:, j] heatmap_flat = heatmap.view(B, -1) max_idx = heatmap_flat.argmax(dim=1) x = (max_idx % W).float() y = (max_idx // W).float() keypoints.append(torch.stack([x, y], dim=-1)) return torch.stack(keypoints, dim=1) def _extract_depth_from_map(self, depth_maps: torch.Tensor, keypoints_2d: torch.Tensor) -> torch.Tensor: """ 从深度图提取关键点深度 Args: depth_maps: 深度图 (B, J, H, W) keypoints_2d: 2D坐标 (B, J, 2) Returns: depths: 深度值 (B, J, 1) """ B, J, H, W = depth_maps.shape depths = [] for j in range(J): x = keypoints_2d[:, j, 0].long().clamp(0, W-1) y = keypoints_2d[:, j, 1].long().clamp(0, H-1) depth_j = depth_maps[torch.arange(B), j, y, x] depths.append(depth_j.unsqueeze(-1)) return torch.stack(depths, dim=1) def _lift_to_3d(self, keypoints_2d: torch.Tensor, depths: torch.Tensor) -> torch.Tensor: """ 将2D关键点提升到3D Args: keypoints_2d: 2D坐标 (B, J, 2) depths: 深度值 (B, J, 1) Returns: keypoints_3d: 3D坐标 (B, J, 3) """ depth_min, depth_max = self.depth_range depths_normalized = depths * (depth_max - depth_min) + depth_min keypoints_3d = torch.cat([keypoints_2d, depths_normalized], dim=-1) return keypoints_3d
class HRNetBackbone(nn.Module): """HRNet骨干网络""" def __init__(self, in_channels: int = 3): super().__init__() self.stem = nn.Sequential( nn.Conv2d(in_channels, 64, 3, 2, 1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 64, 3, 2, 1), nn.BatchNorm2d(64), nn.ReLU() ) self.stage1 = nn.Sequential( nn.Conv2d(64, 256, 3, 1, 1), nn.BatchNorm2d(256), nn.ReLU() ) self.branch1 = nn.Conv2d(256, 32, 1) self.branch2 = nn.Sequential( nn.Conv2d(256, 32, 3, 2, 1), nn.BatchNorm2d(32), nn.ReLU() ) self.fuse = nn.Conv2d(64, 256, 1) def forward(self, x): x = self.stem(x) x = self.stage1(x) b1 = self.branch1(x) b2 = self.branch2(x) b2_up = F.interpolate(b2, size=b1.shape[2:], mode='nearest') x = torch.cat([b1, b2_up], dim=1) x = self.fuse(x) return x
class PoseLifter(nn.Module): """ 姿态提升网络 使用图卷积网络优化3D姿态 """ def __init__(self, num_joints: int = 17, hidden_dim: int = 256): super().__init__() self.num_joints = num_joints self.gc1 = GraphConvolution(3, hidden_dim) self.gc2 = GraphConvolution(hidden_dim, hidden_dim) self.gc3 = GraphConvolution(hidden_dim, 3) self.adj = self._build_adjacency_matrix() def forward(self, pose_3d: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: pose_3d: 3D姿态 (B, J, 3) Returns: pose_3d_refined: 优化后的3D姿态 (B, J, 3) """ B = pose_3d.shape[0] adj = self.adj.unsqueeze(0).expand(B, -1, -1).to(pose_3d.device) x = F.relu(self.gc1(pose_3d, adj)) x = F.dropout(x, 0.1, self.training) x = F.relu(self.gc2(x, adj)) x = self.gc3(x, adj) return pose_3d + x def _build_adjacency_matrix(self) -> torch.Tensor: """ 构建人体骨架邻接矩阵 COCO格式关键点连接 """ skeleton = [ (0, 1), (0, 2), (1, 3), (2, 4), (0, 5), (0, 6), (5, 7), (7, 9), (6, 8), (8, 10), (5, 11), (6, 12), (11, 13), (13, 15), (12, 14), (14, 16) ] adj = torch.zeros(self.num_joints, self.num_joints) for i, j in skeleton: if i < self.num_joints and j < self.num_joints: adj[i, j] = 1 adj[j, i] = 1 adj = adj + torch.eye(self.num_joints) degree = adj.sum(dim=1, keepdim=True) adj = adj / degree return adj
class GraphConvolution(nn.Module): """图卷积层""" def __init__(self, in_features: int, out_features: int): super().__init__() self.linear = nn.Linear(in_features, out_features) def forward(self, x: torch.Tensor, adj: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 节点特征 (B, N, F_in) adj: 邻接矩阵 (B, N, N) Returns: output: 输出特征 (B, N, F_out) """ support = self.linear(x) output = torch.bmm(adj, support) return output
if __name__ == "__main__": model = Monocular3DPoseEstimator() image = torch.randn(2, 3, 384, 288) output = model(image) print("3D姿态估计输出:") print(f" 2D热图: {output['heatmaps_2d'].shape}") print(f" 深度图: {output['depth_maps'].shape}") print(f" 2D关键点: {output['keypoints_2d'].shape}") print(f" 3D关键点: {output['keypoints_3d'].shape}")
|