Sub topic 16
Extension: lifting 2D poses to 3D
This chapter assumes you can decode 2D keypoints from a pose model (heatmap decoding, COCO layout, confidence scores) and that you know PyTorch basics. It adds one step: turning a 2D skeleton into a 3D one.
Why 2D to 3D is ill-posed
A camera maps 3D points to pixels with a pinhole model. Every point on a ray through the camera centre lands on the same pixel, so depth is lost. A 2D skeleton therefore matches many 3D skeletons. Scaling a whole pose away from the camera gives an identical 2D result.
import numpy as np
def project(points, focal, center):
"""Pinhole projection. points: (J, 3) camera coordinates, Z > 0."""
xy = points[:, :2] / points[:, 2:3]
return focal * xy + center
pose = np.array([[0.0, 0.0, 4.0], [0.3, -0.5, 4.2], [-0.2, 0.6, 3.9]])
center = np.array([320.0, 240.0])
uv_near = project(pose, 1000.0, center)
uv_far = project(pose * 2.0, 1000.0, center) # same pose, twice as far
print(np.allclose(uv_near, uv_far)) # TrueEven with a fixed distance, the ambiguity remains. A wrist can point toward the camera or away from it and give nearly the same 2D position. A lifting model resolves this with learned priors: bone lengths are roughly constant, joints bend only in certain directions, and people move in typical ways.
The lifting approach
A lifting model is a second network that takes 2D keypoints as input and outputs 3D joint positions. It does not see the image. The full pipeline has two stages.
Compared with predicting 3D directly from pixels, lifting has clear advantages and costs.
| Property | Lifting (2D then 3D) | Direct image-to-3D |
|---|---|---|
| Training data | 2D detector uses in-the-wild images; lifter needs 3D mocap pairs only | Needs images with 3D labels |
| Domain gap | Small for the lifter, since 2D keypoints look similar everywhere | Large: lab backgrounds and clothing differ from real scenes |
| Error behaviour | 2D mistakes pass straight to the lifter | Errors are learned jointly |
| Cost | Lifter is tiny and fast | Heavier backbone |
| Image cues lost | Shading, size and appearance cues are discarded | Kept |
Representing the target
Most lifters predict a root-relative pose. The root is usually the pelvis. The network outputs each joint's 3D offset from the root, in metres or millimetres. This removes the need to guess global position and distance, which is the hardest part to infer from 2D alone.
The input needs matching care.
- Convert your 2D skeleton to the layout the lifter was trained on. Human3.6M uses 17 joints, including a pelvis, spine and head. COCO has no pelvis or spine, so these are usually synthesized, for example the pelvis as the midpoint of the two hips.
- Subtract the root's pixel position so the pose is centred.
- Divide by a scale so a person's size or distance does not matter. Some pipelines use image width, others use the mean joint distance from the root.
import numpy as np
def normalize_2d(kp, hips=(11, 12)):
"""kp: (J, 2) pixel coordinates in COCO order. Returns normalized pose, root, scale."""
root = kp[list(hips)].mean(axis=0)
centered = kp - root
scale = np.linalg.norm(centered, axis=1).mean() + 1e-9
return centered / scale, root, scale
def mpjpe(pred, gt, root=0):
"""Mean per-joint position error after aligning both poses at the root joint."""
pred = pred - pred[root]
gt = gt - gt[root]
return float(np.linalg.norm(pred - gt, axis=-1).mean())The mpjpe function implements the standard metric, Mean Per-Joint Position Error. It is the average Euclidean distance between predicted and true joints, typically in millimetres. Published results on Human3.6M are often below 50 mm for good video models.
A simple lifting network
The "simple baseline" of Martinez et al. (2017) showed that a small fully connected network with residual blocks lifts surprisingly well when the 2D input is accurate. Here is a compact version.
import torch
import torch.nn as nn
class Block(nn.Module):
def __init__(self, width, p):
super().__init__()
self.net = nn.Sequential(
nn.Linear(width, width), nn.BatchNorm1d(width), nn.ReLU(), nn.Dropout(p),
nn.Linear(width, width), nn.BatchNorm1d(width), nn.ReLU(), nn.Dropout(p),
)
def forward(self, x):
return x + self.net(x)
class Lifter(nn.Module):
def __init__(self, joints=17, width=1024, blocks=2, p=0.25):
super().__init__()
self.joints = joints
self.inp = nn.Linear(joints * 2, width)
self.blocks = nn.Sequential(*[Block(width, p) for _ in range(blocks)])
self.out = nn.Linear(width, joints * 3)
def forward(self, x):
# x: (B, J, 2) normalized 2D keypoints -> (B, J, 3) root-relative 3D
h = self.inp(x.flatten(1))
h = self.blocks(h)
return self.out(h).view(-1, self.joints, 3)
model = Lifter().eval()
with torch.no_grad():
pose3d = model(torch.randn(8, 17, 2))
print(pose3d.shape) # torch.Size([8, 17, 3])Training minimizes the L2 distance between predicted and ground-truth root-relative joints. These weights are untrained, so the output here only shows the shapes.
Using time to resolve ambiguity
A single frame leaves depth uncertain, but a sequence constrains it. A limb that moves in a smooth arc is easier to place than one seen once. Video lifters take a window of 2D poses as input:
- Temporal convolutions (VideoPose3D, Pavllo et al. 2019) apply dilated 1D convolutions across frames and predict the centre frame.
- Transformers (PoseFormer, MixSTE) attend across both joints and frames.
Windows of 27 to 243 frames are common. Longer windows reduce jitter but add latency, which matters for live applications.
Placing the pose in the world
Root-relative output has no position. To draw the skeleton at the right place in camera space you need the root's 3D location. Options include:
- Predict root depth with an extra network branch.
- Assume a bone length and solve for depth from the 2D size of a limb, which requires camera intrinsics (focal length and principal point).
- Use multiple calibrated cameras and triangulate 2D keypoints directly. This avoids learning depth, and is the most accurate option if you can set it up.
Failure modes
- Bad 2D input. A left-right swap or a hallucinated occluded joint in 2D becomes a distorted 3D pose, because the lifter trusts its input. Check 2D quality first.
- Skeleton mismatch. Feeding COCO keypoints in COCO order into a Human3.6M model scrambles joints silently. Always map joints explicitly.
- Normalization mismatch. Use exactly the root and scale convention from training.
- Camera domain shift. A lifter trained on a few indoor cameras may fail on high, low or wide-angle views. Training with random virtual cameras helps.
- Unseen motions. Mocap datasets cover limited actions. Yoga poses or sports moves often come out as an average walking pose.
- Depth flips. Plausible but wrong poses with a limb mirrored in depth are the typical symptom of the ambiguity above.
Exercise
A lifter trained on Human3.6M gives plausible poses on lab video but strongly bent torsos on your phone footage of someone sitting on a low chair. Name two likely causes and one check for each.
Show answer
Cause 1: unseen pose or motion, since the training data has few low-seated postures, so the model falls back to common poses. Check by testing on similar poses in the training distribution, or fine-tune on matching data. Cause 2: camera or normalization mismatch, for example a different viewing height or a different root and scale convention. Check by printing the normalized 2D input and comparing its ranges with training inputs, and by verifying the joint mapping from COCO to the 17-joint layout.
Exercise
Two predicted 3D poses have identical root-relative joint positions up to a uniform scale factor of 2. Can the 2D keypoints distinguish them, and what does this say about the lifter's output scale?
Show answer
No. A uniform scale about the camera produces identical 2D keypoints, as the projection example showed, so 2D input cannot fix the scale. The lifter must infer scale from priors such as typical bone lengths, so its output is only as reliable as those priors, and absolute size should come from a known height, bone length or calibrated cameras.