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 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
| """ ChairPose模型完整实现 论文:ChairPose: Pressure-based Chair Morphology Grounded Sitting Pose Estimation 会议:ACM UIST 2025 """
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from typing import Tuple, Optional
class MotionQuantizer(nn.Module): """ 动作量化器(MQ) 将连续3D姿态序列量化为离散token """ def __init__( self, num_joints: int = 22, hidden_dim: int = 512, codebook_size: int = 1028, num_frames: int = 15 ): """ Args: num_joints: 关节数量(SMPL格式为22) hidden_dim: 隐藏层维度 codebook_size: 代码本大小 num_frames: 时间窗口帧数 """ super().__init__() self.num_joints = num_joints self.codebook_size = codebook_size self.num_frames = num_frames input_dim = num_joints * 3 * 6 self.encoder = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.ReLU() ) self.temporal_encoder = nn.Sequential( nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1), nn.ReLU(), nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1), nn.ReLU() ) self.codebook = nn.Embedding(codebook_size, hidden_dim) nn.init.normal_(self.codebook.weight, mean=0, std=0.02) self.decoder = nn.Sequential( nn.Linear(hidden_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, num_joints * 3) ) self.register_buffer('ema_count', torch.zeros(codebook_size)) self.register_buffer('ema_weight', self.codebook.weight.data.clone()) self.gamma = 0.99 def encode(self, pose_sequence: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ 编码姿态序列为离散token Args: pose_sequence: 姿态序列 (B, T, J, D) B=batch, T=time, J=joints, D=3 Returns: z_q: 量化后的特征 (B, T, hidden_dim) indices: 代码本索引 (B, T) """ B, T, J, D = pose_sequence.shape position = pose_sequence velocity_linear = torch.diff(position, dim=1, append=position[:, -1:].clone()) velocity_angular = velocity_linear accel_linear = torch.diff(velocity_linear, dim=1, append=velocity_linear[:, -1:].clone()) accel_angular = accel_linear features = torch.cat([ position, velocity_linear, velocity_angular, accel_linear, accel_angular, position ], dim=-1) features = features.reshape(B, T, -1) z = self.encoder(features) z = z.transpose(1, 2) z = self.temporal_encoder(z) z = z.transpose(1, 2) distances = torch.cdist(z, self.codebook.weight) indices = torch.argmin(distances, dim=-1) z_q = self.codebook(indices) z_q = z + (z_q - z).detach() return z_q, indices def decode(self, z_q: torch.Tensor) -> torch.Tensor: """ 解码token为3D姿态 Args: z_q: 量化特征 (B, T, hidden_dim) Returns: pose: 3D关节位置 (B, T, J, 3) """ pose_flat = self.decoder(z_q) B, T, _ = pose_flat.shape pose = pose_flat.reshape(B, T, self.num_joints, 3) return pose def forward(self, pose_sequence: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ 前向传播 Args: pose_sequence: 输入姿态 (B, T, J, 3) Returns: pose_recon: 重构姿态 (B, T, J, 3) indices: 代码本索引 (B, T) loss: 总损失 """ z_q, indices = self.encode(pose_sequence) pose_recon = self.decode(z_q) recon_loss = F.mse_loss(pose_recon, pose_sequence) z = self.encoder(pose_sequence.reshape(pose_sequence.shape[0], pose_sequence.shape[1], -1)) quant_loss = F.mse_loss(z_q, z.detach()) if self.training: self._update_ema(indices) loss = recon_loss + 0.25 * quant_loss return pose_recon, indices, loss def _update_ema(self, indices: torch.Tensor): """EMA更新代码本(稳定训练)""" indices_flat = indices.flatten() counts = torch.bincount( indices_flat, minlength=self.codebook_size ).float() self.ema_count = self.gamma * self.ema_count + (1 - self.gamma) * counts
class PointNetEncoder(nn.Module): """ PointNet编码器 提取椅子3D扫描的特征 """ definit__(self, input_dim: int = 3, hidden_dim: int = 512): """ Args: input_dim: 点云维度(x, y, z) hidden_dim: 输出特征维度 """ super().__init__() self.conv1 = nn.Conv1d(input_dim, 64, kernel_size=1) self.conv2 = nn.Conv1d(64, 128, kernel_size=1) self.conv3 = nn.Conv1d(128, 256, kernel_size=1) self.fc = nn.Sequential( nn.Linear(256, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim) ) self.bn1 = nn.BatchNorm1d(64) self.bn2 = nn.BatchNorm1d(128) self.bn3 = nn.BatchNorm1d(256) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 点云 (B, N, 3) Returns: features: 全局特征 (B, hidden_dim) """ x = x.transpose(1, 2) x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) x = torch.max(x, dim=-1)[0] x = self.fc(x) return x
class Pressure2Pose(nn.Module): """ 压力图到姿态的预测器(P2P) 自回归生成姿态token序列 """ def __init__( self, pressure_shape: Tuple[int, int] = (80, 28), hidden_dim: int = 512, codebook_size: int = 1028 ): """ Args: pressure_shape: 压力传感器矩阵形状 (height, width) hidden_dim: 隐藏层维度 codebook_size: 代码本大小(与MQ一致) """ super().__init__() self.pressure_shape = pressure_shape self.codebook_size = codebook_size self.pressure_encoder = nn.Sequential( nn.Conv2d(1, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d((4, 4)), nn.Flatten(), nn.Linear(128 * 16, hidden_dim) ) self.chair_encoder = PointNetEncoder(input_dim=3, hidden_dim=hidden_dim) self.predictor = nn.TransformerDecoder( nn.TransformerDecoderLayer( d_model=hidden_dim, nhead=8, dim_feedforward=1024, dropout=0.1, batch_first=True ), num_layers=6 ) self.classifier = nn.Linear(hidden_dim, codebook_size) self.start_token = nn.Parameter(torch.randn(1, hidden_dim)) def forward( self, pressure_sequence: torch.Tensor, chair_points: torch.Tensor, mq_decoder: MotionQuantizer, max_length: int = 15 ) -> torch.Tensor: """ 自回归生成姿态序列 Args: pressure_sequence: 压力序列 (B, T, H, W) chair_points: 椅子点云 (B, N, 3) mq_decoder: MQ解码器(用于从token解码为姿态) max_length: 最大序列长度 Returns: pose_sequence: 预测的姿态序列 (B, T, J, 3) """ B = pressure_sequence.shape[0] pressure_features = self.pressure_encoder( pressure_sequence.reshape(-1, 1, *self.pressure_shape) ) pressure_features = pressure_features.reshape(B, -1, pressure_features.shape[-1]) chair_features = self.chair_encoder(chair_points) generated_tokens = [] current_token = self.start_token.expand(B, -1) for t in range(max_length): combined = pressure_features[:, t:t+1] + chair_features.unsqueeze(1) + current_token.unsqueeze(1) decoded = self.predictor(combined, combined) logits = self.classifier(decoded.squeeze(1)) token_idx = torch.argmax(logits, dim=-1) generated_tokens.append(token_idx) current_token = mq_decoder.codebook(token_idx) token_indices = torch.stack(generated_tokens, dim=1) z_q = mq_decoder.codebook(token_indices) pose_sequence = mq_decoder.decode(z_q) return pose_sequence
class ChairPose(nn.Module): """ ChairPose完整模型 压力图 + 椅子形状 → 3D坐姿估计 """ def __init__(self, config: dict): """ Args: config: 配置字典 - num_joints: 关节数(默认22) - hidden_dim: 隐藏维度(默认512) - codebook_size: 代码本大小(默认1028) - pressure_shape: 压力矩阵形状(默认(80, 28)) """ super().__init__() self.mq = MotionQuantizer( num_joints=config.get('num_joints', 22), hidden_dim=config.get('hidden_dim', 512), codebook_size=config.get('codebook_size', 1028) ) self.p2p = Pressure2Pose( pressure_shape=config.get('pressure_shape', (80, 28)), hidden_dim=config.get('hidden_dim', 512), codebook_size=config.get('codebook_size', 1028) ) def forward( self, pressure_sequence: torch.Tensor, chair_points: torch.Tensor, pose_sequence: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, dict]: """ 前向传播 Args: pressure_sequence: 压力序列 (B, T, H, W) chair_points: 椅子点云 (B, N, 3) pose_sequence: 真实姿态(训练时需要) (B, T, J, 3) Returns: pose_pred: 预测姿态 (B, T, J, 3) losses: 损失字典 """ if pose_sequence is not None and self.training: pose_recon, indices, mq_loss = self.mq(pose_sequence) pose_pred = self.p2p(pressure_sequence, chair_points, self.mq) sequence_loss = F.mse_loss(pose_pred, pose_sequence) total_loss = mq_loss + 0.5 * sequence_loss losses = { 'mq_loss': mq_loss.item(), 'sequence_loss': sequence_loss.item(), 'total_loss': total_loss.item() } return pose_pred, losses else: pose_pred = self.p2p(pressure_sequence, chair_points, self.mq) return pose_pred, {}
if __name__ == "__main__": config = { 'num_joints': 22, 'hidden_dim': 512, 'codebook_size': 1028, 'pressure_shape': (80, 28) } model = ChairPose(config) model.eval() B, T, H, W = 2, 15, 80, 28 N, J, D = 5000, 22, 3 pressure_sequence = torch.randn(B, T, H, W) * 0.1 chair_points = torch.randn(B, N, 3) * 0.5 pressure_sequence[:, :, 30:50, 10:20] += 0.5 pressure_sequence[:, :, 10:30, 12:18] += 0.3 with torch.no_grad(): pose_pred, _ = model(pressure_sequence, chair_points) print(f"输入压力序列形状: {pressure_sequence.shape}") print(f"输入椅子点云形状: {chair_points.shape}") print(f"输出姿态序列形状: {pose_pred.shape}") print(f"平均关节位置误差: {torch.mean(torch.norm(pose_pred, dim=-1)).item():.3f}m") total_params = sum(p.numel() for p in model.parameters()) print(f"\n模型总参数量: {total_params:,} ({total_params/1e6:.2f}M)")
|