Sub topic 6
Decoding Heatmaps into Coordinates and Confidence
Assume you know basic Python, NumPy, convolutional neural networks, image coordinates, and bounding boxes. This chapter focuses on turning a model's heatmaps into usable keypoint coordinates and confidence scores.
What a heatmap represents
A pose model often produces one heatmap for each keypoint. For the COCO layout, the output has 17 channels: one for the nose, one for each eye, shoulder, elbow, wrist, hip, knee, and ankle.
Each heatmap is a grid of values. A high value means that the model believes the corresponding keypoint is near that grid cell. If the heatmap has height H and width W, its shape is:
| Dimension | Meaning |
|---|---|
| `K` | Number of keypoints |
| `H` | Heatmap rows |
| `W` | Heatmap columns |
The model input is usually larger than the heatmap. The ratio between their sizes is the stride. For example, a 64 × 48 heatmap made from a 256 × 192 input has a stride of 4.
Arg-max decoding
The simplest decoder finds the maximum value in each keypoint heatmap. This operation is called arg-max because it returns the position of the maximum value.
The maximum value becomes the keypoint's score. The cell position is multiplied by the stride to estimate the position in input pixels.
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, scoresnp.divmod converts a flattened index back into a row and column. The returned coordinate order is (x, y), while NumPy arrays usually use [row, column], or (y, x). Mixing these conventions is a common source of flipped results.
Improving coordinate precision
The heatmap is lower resolution than the input, so arg-max introduces quantization error. A peak at column 20 with stride 4 maps to approximately x = 80, but the true location might lie between heatmap cells.
Common refinements include:
- Taking a weighted average around the highest-valued cell. This is often called a soft-argmax.
- Fitting a small quadratic surface around the peak.
- Predicting a separate offset for each heatmap cell.
- Using a higher-resolution heatmap.
Also check the coordinate convention. Some pipelines map cell (x, y) to x * stride, while others use (x + 0.5) * stride to represent the cell center. The decoder must match the model's training and preprocessing conventions.
Exercise
A heatmap has shape (17, 64, 48), and its stride is 4. For keypoint 3, the maximum is at row 10, column 20. What coordinate does the decoder return?
Show answer
It returns (80, 40): x = 20 * 4 and y = 10 * 4.