Sub topic 6
Decoding heatmaps into coordinates and confidence
This chapter assumes you know NumPy array indexing, how a convolutional network produces feature maps, and the idea of a heatmap target from the previous chapter. Here you will turn the network's output tensor into the numbers an application uses: an (x, y) position and a score for each keypoint.
What the network gives you
A heatmap-based pose model outputs one 2D map per keypoint. For the COCO layout that is 17 maps, so the output has shape (K, H, W) with K = 17. A common setup feeds a 256×192 crop to the network and gets back 17 maps of 64×48. Each cell holds a value that is high where the network believes the keypoint is.
The heatmap is smaller than the input by a factor called the stride. In this example the stride is 4, because 256 / 64 = 4. One heatmap cell covers a 4×4 patch of input pixels. Decoding must undo this scaling.
Argmax decoding
The simplest decoder takes the position of the maximum in each map as the location. It takes the maximum value as the confidence.
import numpy as np
def decode_heatmaps(heatmaps, stride):
"""heatmaps: array of shape (K, H, W). Returns (K, 2) x,y coords in input pixels and (K,) scores."""
k, h, w = heatmaps.shape
flat = heatmaps.reshape(k, -1)
idx = flat.argmax(axis=1)
scores = flat.max(axis=1)
ys, xs = np.divmod(idx, w)
coords = np.stack([xs, ys], axis=1).astype(np.float32) * stride
return coords, scoresThree details are easy to get wrong:
- Flattening order.
reshape(k, -1)flattens each map in row-major order, so the flat index equalsy * w + x. That is whynp.divmod(idx, w)returns(y, x), in that order. Swapping them transposes every keypoint. - Output order. The result is
(x, y), but array indexing is[row, column]=[y, x]. Keep this straight when you index back into the heatmap. - Cell centre. Multiplying by the stride puts the point at the top-left corner of the cell. Some codebases add
stride / 2to use the cell centre. Others compensate for the choice during training. Follow the convention of the model you use. A fixed half-cell bias is small, but it shows up when you compute OKS at tight thresholds.
The accuracy limit of argmax
With a stride of 4, argmax can only return multiples of 4 pixels. The true position lies somewhere inside the cell, so the error can reach about 2 pixels in each axis even for a perfect heatmap. For small people this matters. A 2-pixel error on a person 60 pixels tall is a visible fraction of the body.
The standard fix is sub-cell refinement. The heatmap is roughly a Gaussian bump, so the neighbouring cell with the higher value shows which side of the peak the true position lies on. Shift the estimate a quarter of a cell toward that side.
import numpy as np
def decode_heatmaps(heatmaps, stride, refine=True):
"""heatmaps: (K, H, W). Returns (K, 2) x,y in input pixels and (K,) scores."""
k, h, w = heatmaps.shape
flat = heatmaps.reshape(k, -1)
idx = flat.argmax(axis=1)
scores = flat.max(axis=1)
ys, xs = np.divmod(idx, w)
coords = np.stack([xs, ys], axis=1).astype(np.float32)
if refine:
for i in range(k):
x, y = xs[i], ys[i]
if 0 < x < w - 1 and 0 < y < h - 1:
hm = heatmaps[i]
coords[i, 0] += 0.25 * np.sign(hm[y, x + 1] - hm[y, x - 1])
coords[i, 1] += 0.25 * np.sign(hm[y + 1, x] - hm[y - 1, x])
return coords * stride, scores
# Synthetic test: a Gaussian peak at (20.3, 10.6) on a 64x48 map, stride 4.
H, W, sigma = 64, 48, 2.0
yy, xx = np.mgrid[0:H, 0:W]
hm = np.exp(-((xx - 20.3) ** 2 + (yy - 10.6) ** 2) / (2 * sigma ** 2))
hm = hm[None] # shape (1, H, W)
plain, _ = decode_heatmaps(hm, 4, refine=False)
fine, score = decode_heatmaps(hm, 4, refine=True)
print(plain, fine, np.round(score, 2))The plain decoder returns (80, 44). The refined decoder returns (81, 43), which is closer to the true point (81.2, 42.4). The score is about 0.97, below 1.0 because the true peak fell between cells.
The border check (0 < x < w - 1) matters. At the edge there is no neighbour on one side, so the code skips refinement instead of reading outside the array. Without it, negative indices would silently wrap around to the other side of the map.
Decoding methods compared
| Method | How it works | Strength | Weakness |
|---|---|---|---|
| Argmax | Peak cell times stride | Fast, simple | Quantised to stride |
| Argmax with quarter-cell shift | Moves toward the larger neighbour | Cheap accuracy gain | Assumes a roughly Gaussian peak |
| Soft-argmax | Probability-weighted mean of coordinates | Differentiable, sub-pixel | Biased by secondary peaks and noise |
| Gaussian fit around the peak | Fits a model to the local area | Accurate with a smooth peak | Slower, and sensitive to the training sigma |
Soft-argmax is the one to pick if you need gradients through the decoder, for example to train with a coordinate loss. It averages over the whole map, so a second bump (a different person's wrist, say) pulls the answer toward the midpoint between them. Argmax avoids this because it commits to a single peak.
Confidence is a peak height
The score you get is the heatmap value at the peak. It is a useful ranking signal, but it is not a calibrated probability. A score of 0.8 does not mean the point is right 80% of the time. Its meaning depends on the training sigma, on whether the model's final layer uses a sigmoid, and on how the data was augmented.
Use the scores in three ways:
- Thresholding. Drop keypoints below a cutoff, often 0.3, before drawing or computing angles.
- Weighting. Weight keypoints by score when you average them or fit a model, for example to estimate a body centre.
- Instance ranking. Average the keypoint scores to rank people, as COCO evaluation expects in the final prediction score.
Mapping back to the original image
In a top-down pipeline the network only sees a crop around a detected person. The decoder returns coordinates in the crop's input frame, so you must map them back using the box.
import numpy as np
def crop_to_image(coords, box, input_w, input_h):
"""coords: (K, 2) in crop-input pixels. box: (x1, y1, x2, y2) in the original image."""
x1, y1, x2, y2 = box
sx = (x2 - x1) / input_w
sy = (y2 - y1) / input_h
out = np.asarray(coords, dtype=np.float32).copy()
out[:, 0] = x1 + out[:, 0] * sx
out[:, 1] = y1 + out[:, 1] * sy
return outThis assumes the crop was resized directly to the input size. If your pipeline pads the crop to keep its aspect ratio, or rotates it, invert that transform as well. Forgetting this step is the most common reason keypoints look right on the crop and wrong on the full image.
Edge cases and debugging
- Flat or empty maps. If a keypoint is out of frame, the map may be near zero everywhere. Argmax still returns a position, but the score is tiny. Rely on the score, not the position, to decide whether the point exists.
- Ties.
argmaxreturns the first maximum in row-major order. Ties are rare with float outputs but common with quantised models (int8), where they bias the point to the top-left of a plateau. - Multiple peaks. A single-person decoder keeps only the strongest. In a crowded crop, the strongest peak may belong to a neighbour. Bottom-up methods keep several peaks per map and group them, covered in a later chapter.
- Flip testing. Many systems average the heatmaps of the image and its mirror image before decoding. Remember to swap the left and right channels (for example, left wrist and right wrist) when you un-flip, or you create the very left-right errors you want to avoid.
- Smoothing the map. A light Gaussian blur of the heatmap before argmax stabilises noisy peaks. Match the blur to the training sigma. A much larger blur flattens the peak and shifts it.
Exercise
A model takes 384×288 crops (height × width) and outputs heatmaps of shape (17, 96, 72). Argmax finds the right-wrist peak at row 40, column 30, and the neighbours satisfy hm[40, 31] > hm[40, 29] and hm[41, 30] < hm[39, 30]. Using quarter-cell refinement, what are the right wrist's (x, y) in input pixels? The crop came from a box (100, 50, 244, 242) in the original image. What are its coordinates there?
Show answer
The stride is 384 / 96 = 4. Refinement shifts x by +0.25 (the right neighbour is higher) and y by -0.25 (the upper neighbour is higher). So the heatmap position is (30.25, 39.75) and the input position is (121.0, 159.0). The crop has width 144 and height 192, so sx = 144 / 288 = 0.5 and sy = 192 / 384 = 0.5. The original position is x = 100 + 121.0 × 0.5 = 160.5 and y = 50 + 159.0 × 0.5 = 129.5, so (160.5, 129.5).