Sub topic 5
Heatmaps: representing each keypoint as a spatial map
This chapter assumes you know what a convolutional feature map is, how a CNN produces spatial outputs, and the COCO 17-keypoint layout from earlier chapters. It also assumes you are comfortable with NumPy arrays and tensor shapes. The next chapter covers decoding heatmaps in detail. Here the goal is to understand what a heatmap is, why it works better than the alternatives, and what its shape and resolution mean.
The idea: one spatial map per keypoint
A pose model must output where each body joint is. The most direct way is to output numbers: 17 keypoints times (x, y) gives 34 values. The heatmap approach changes the output format. The network produces one 2D map per keypoint, and each map shows how likely that keypoint is to sit at each location.
For the COCO layout the output tensor has shape (K, H, W) with K = 17. Channel k is the heatmap for keypoint k. For example, channel 9 is the left wrist. A bright spot in that channel at column x, row y says "the left wrist is probably here."
This turns a coordinate problem into a per-pixel prediction problem, which is what convolutional networks do well. The output keeps the spatial layout of the image, so the network does not have to compress location into a vector of numbers.
Shapes and stride
Heatmaps are almost always smaller than the input. The ratio is the stride: the number of input pixels covered by one heatmap pixel. A common top-down setup feeds a 256×192 crop (height × width) and outputs 64×48 heatmaps, so the stride is 4.
| Quantity | Typical value |
|---|---|
| Input size (H × W) | 256 × 192 |
| Heatmap size (H × W) | 64 × 48 |
| Stride | 4 |
| Channels K (COCO) | 17 |
| Output tensor | (17, 64, 48) |
Lower resolution keeps compute and memory manageable. It also limits precision: with stride 4, a heatmap pixel represents a 4×4 patch of the input. The decoder must recover finer positions than one cell, which the next chapter covers.
The head that produces the heatmaps is usually small. A 1×1 convolution maps the final feature channels to K channels. Some designs add a few deconvolution (transposed convolution) layers first to raise the resolution, as in SimpleBaseline.
Why heatmaps beat direct regression
The previous chapter described direct coordinate regression and its limits. Heatmaps address three of them.
- Spatial generalization. Convolutions are translation-equivariant. If a wrist appears 20 pixels to the right, the heatmap peak moves 20 pixels to the right. A fully connected regression head must learn that mapping separately for each position.
- Richer supervision. A regression target is two numbers. A heatmap target gives a loss at every pixel of every map, which gives denser gradients.
- Uncertainty is visible. A peaked map means the model is confident. A flat or multi-modal map signals ambiguity, such as a left/right confusion with two peaks. A regressed coordinate cannot express this, and when the model is torn between two positions it tends to output their average, which is often wrong for both.
The trade-offs are real. Heatmaps cost more memory than 34 numbers. Position is quantized by the stride unless you refine it. The arg-max step is not differentiable, so you cannot train directly on final coordinates without extra tricks.
Building a Gaussian target
During training you need a ground-truth heatmap for each keypoint. The standard choice is a 2D Gaussian centered on the keypoint's location in heatmap coordinates:
target(x, y) = exp(-((x - mx)^2 + (y - my)^2) / (2 * sigma^2))
Here (mx, my) is the keypoint position on the heatmap grid and sigma controls the spread. The peak value is 1 at the keypoint. The Gaussian is used instead of a single hot pixel because a one-pixel target is extremely sparse and punishes a prediction one pixel off as harshly as one far away. A soft blob gives partial credit for near misses and a smoother loss.
The following code builds targets for a set of keypoints. It follows the COCO visibility convention from the annotations chapter: 0 means not labelled, so its heatmap stays all zeros.
import numpy as np
def make_gaussian_targets(keypoints, visibility, input_size, heatmap_size, sigma=2.0):
"""
keypoints: (K, 2) x,y in input pixels.
visibility: (K,) COCO flags (0 = not labelled).
input_size, heatmap_size: (H, W) tuples.
Returns targets (K, Hh, Wh) and weights (K,).
"""
k = keypoints.shape[0]
hh, wh = heatmap_size
stride_y = input_size[0] / hh
stride_x = input_size[1] / wh
targets = np.zeros((k, hh, wh), dtype=np.float32)
weights = (visibility > 0).astype(np.float32)
ys, xs = np.mgrid[0:hh, 0:wh]
for i in range(k):
if weights[i] == 0:
continue
mx = keypoints[i, 0] / stride_x
my = keypoints[i, 1] / stride_y
# skip keypoints whose centre falls outside the map
if mx < 0 or my < 0 or mx >= wh or my >= hh:
weights[i] = 0
continue
d2 = (xs - mx) ** 2 + (ys - my) ** 2
targets[i] = np.exp(-d2 / (2 * sigma ** 2))
return targets, weights
kps = np.array([[96.0, 128.0], [10.0, 20.0], [0.0, 0.0]])
vis = np.array([2, 1, 0])
t, w = make_gaussian_targets(kps, vis, (256, 192), (64, 48), sigma=2.0)
print(t.shape, w, t[0].max().round(3))The weights array is multiplied into the loss so unlabelled keypoints add no gradient. Training details, including the loss and augmentation, come in a later chapter.
Choosing sigma
sigma is measured in heatmap pixels, and it trades off two things.
- Small sigma (about 1) gives a sharp target and precise localization, but training is harder because the signal is sparse and the model is sensitive to small errors.
- Large sigma (about 3 or more) is easier to learn but blurs the peak, so nearby keypoints such as the eyes and nose can merge.
A value of 2 is a common default for 64×48 maps. If you change the heatmap resolution, scale sigma with it so the blob covers a similar fraction of the body.
Reading a heatmap at inference
At inference the network outputs raw values, not a clean Gaussian. Healthy outputs look like this:
- A single compact peak near the true joint, with values that fall off smoothly.
- Peak height that reflects confidence. A clear, unoccluded joint often peaks near 0.8 to 1.0. An occluded or guessed joint peaks lower.
- Background near zero. Values can dip slightly negative because the output has no activation function.
The peak value is reused as the keypoint confidence score. That is a convenient proxy, but it is not a calibrated probability. A model can output a high peak on a wrong location, for instance on the other person's limb in a crowd.
Edge cases to watch
- Keypoints near the border. A joint at the edge of the crop puts the Gaussian partly outside the map. The target is still valid if the center is inside, and it is truncated at the edge. If the center is outside, skip it, as the code above does.
- Flip augmentation. Flipping the image horizontally swaps left and right keypoints. You must swap the channel order too (left wrist to right wrist), or the model learns inconsistent labels. This is a classic source of left-right swap errors.
- Multiple people in one map. A top-down model sees one person per crop, so each channel has one peak. A bottom-up model sees everyone, so each channel has several peaks, and a grouping step must assign them to people. That is covered in a later chapter.
- Quantization. If you place the Gaussian center on a rounded integer pixel, you throw away sub-pixel information and add a systematic bias. The code above keeps the floating-point center for this reason.
Check your understanding
Exercise
A model takes a 384 x 288 (H x W) input and produces 96 x 72 heatmaps for 17 keypoints. (a) What is the stride? (b) What is the output tensor shape? (c) A keypoint is labelled at input pixel (x=144, y=192). Where is its Gaussian center on the heatmap grid?
Show answer
(a) The stride is 384 / 96 = 4, and 288 / 72 = 4, so 4 in both directions. (b) The output shape is (17, 96, 72). (c) Divide by the stride: x = 144 / 4 = 36 and y = 192 / 4 = 48, so the center is at heatmap column 36, row 48.
Exercise
Why does a Gaussian target give a better training signal than setting a single heatmap pixel to 1 and the rest to 0? Name one risk of making sigma too large.
Show answer
A single hot pixel is very sparse, and a prediction that is one pixel off is penalized as strongly as one far away. A Gaussian gives partial credit to nearby pixels, so the loss is smoother and gradients are more informative. If sigma is too large, the peak blurs and nearby keypoints (such as the eyes and nose) can merge, which lowers localization precision.
Exercise
You add horizontal flip augmentation to a heatmap training pipeline, flipping the image and the keypoint x coordinates but not reordering the keypoint channels. What symptom do you expect, and what is the fix?
Show answer
The model receives labels where the "left wrist" channel marks the person's right wrist in flipped images, so it learns inconsistent targets and produces left-right swaps at inference. The fix is to apply a flip permutation to the keypoint channels (swap left and right pairs such as shoulders, elbows, wrists, hips, knees and ankles, and the eyes and ears) whenever the image is flipped.