Sub topic 15
Failure modes and debugging
This chapter assumes you have read the earlier chapters on the COCO keypoint layout, heatmap decoding, top-down and bottom-up pipelines, Object Keypoint Similarity (OKS), and running a pretrained model. You should be comfortable with NumPy and with the idea of a detector producing bounding boxes.
Pose models rarely fail at random. Most errors fall into a small number of patterns, and each pattern leaves a recognizable signature in the keypoints, the confidence scores, or the OKS numbers. The skill is to look at the output, name the pattern, and test one cause at a time.
A debugging mindset
A pose pipeline has several stages, and an error in one stage often looks like a model weakness in another. Before blaming the network, check the stages in order.
- Is the input what you think it is (color order, size, orientation)?
- Did the detector find the person, and is the box a sensible fit?
- Do the raw heatmaps or keypoints look reasonable?
- Are the coordinates mapped back to the original image correctly?
- Is post-processing hiding or creating the problem?
Draw the output on the image at every stage. A plot reveals in seconds what a table of numbers hides.
Occlusion and truncation
Occlusion means a body part is hidden by an object or another person. Truncation means it lies outside the image. These cases are common in real footage: a desk hides the legs, or a person stands at the frame edge.
What you see:
- Hidden joints are still predicted, usually at a plausible guess. A model has learned typical body proportions, so it places an occluded wrist near where a wrist usually is.
- Confidence for those joints is often lower, but not always low enough to filter them out.
- Truncated joints are placed near the image border or inside the image instead of off-screen.
What to do:
- Filter by per-keypoint confidence, not only by person confidence. Treat a joint below your threshold as missing.
- Do not compute angles from missing joints. Return
NoneorNaNinstead. - Remember that the COCO visibility flags (0, 1, 2) mean the training data included labelled-but-occluded joints, so the model is trained to guess them. A guess is not a measurement.
import numpy as np
def mask_low_confidence(xy, conf, threshold=0.5):
"""Return a copy of xy (K, 2) with NaN rows where confidence is below threshold."""
out = np.asarray(xy, dtype=float).copy()
out[np.asarray(conf) < threshold] = np.nan
return out
xy = np.array([[100.0, 50.0], [120.0, 80.0], [130.0, 140.0]])
conf = np.array([0.92, 0.31, 0.77])
print(mask_low_confidence(xy, conf))A confidence threshold is a trade-off. A high value gives clean but sparse skeletons. A low value keeps more joints but admits guesses. Pick it by looking at footage from your own setting, not by copying a default.
Crowding and person merging
When people overlap, each pipeline family fails in its own way.
| Pipeline | Typical crowding failure | Why it happens |
|---|---|---|
| Top-down | Keypoints from a neighbour appear on the wrong person | The crop contains parts of two people, and the model must pick one |
| Top-down | A person is missing entirely | The detector's non-maximum suppression (NMS) removed a box that overlapped a stronger one |
| Bottom-up | A limb joins joints from two different people | The grouping step links the wrong pairs |
| Single-stage | Two people collapse into one skeleton | Both are assigned to the same anchor or query |
For top-down pipelines, the first thing to inspect is the detector. If the box is missing, no pose can appear. Try lowering the NMS IoU threshold's strictness (that is, raising it so fewer overlapping boxes are suppressed) and see whether the missing person returns. Expect more duplicate boxes as a cost.
For bottom-up pipelines, look at the grouping scores. Wrong links usually have weak association scores, so a stricter minimum on the link score removes them at the price of fragmenting some real skeletons.
Left-right swaps
A left-right swap happens when the model labels a person's left wrist as the right wrist, or the reverse. The skeleton looks anatomically valid, so this error is easy to miss. Its main causes are:
- Mirror augmentation with a wrong flip map. When you flip an image horizontally during training, the left and right keypoint labels must also be exchanged. If the swap list is wrong or absent, the model learns contradictory labels. Check the list against the layout: eyes, ears, shoulders, elbows, wrists, hips, knees and ankles each have a left-right pair, and the nose does not.
- Mirrored test images. Webcam previews are often mirrored. The model sees a flipped person, so "left" in the output is the camera's left, not the person's.
- Back views and ambiguous poses. From behind, or with a person in profile, the visual cue separating left from right is weak, and models do swap sides, particularly in frames where the person is turning.
A quick test for training code is to flip a labelled sample, apply your flip function, and confirm that the label for the left shoulder now sits on the image's other side and carries the right-shoulder index.
import numpy as np
# COCO 17-keypoint indices: 0 nose, 1/2 eyes, 3/4 ears, 5/6 shoulders,
# 7/8 elbows, 9/10 wrists, 11/12 hips, 13/14 knees, 15/16 ankles.
FLIP_PAIRS = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16)]
def flip_keypoints(xy, image_width):
"""Horizontally flip (17, 2) keypoints and swap left/right indices."""
out = np.asarray(xy, dtype=float).copy()
out[:, 0] = image_width - 1 - out[:, 0]
for a, b in FLIP_PAIRS:
out[[a, b]] = out[[b, a]]
return out
xy = np.zeros((17, 2))
xy[5] = [30, 100] # left shoulder
xy[6] = [70, 100] # right shoulder
flipped = flip_keypoints(xy, image_width=100)
print(flipped[5], flipped[6]) # index 5 is now the mirrored old right shoulderWhen smoothing video, a swap shows up as a joint that jumps across the body in a single frame. A simple check is to flag frames where a keypoint moves more than some fraction of the body size between frames.
Coordinate and scale bugs
Many "model failures" are mapping errors. The skeleton looks correct in shape but sits in the wrong place or has the wrong size.
- Stride error. Heatmap coordinates must be multiplied by the stride between heatmap and input, as in the decoding function from the heatmap chapter. A missing or wrong stride shrinks the skeleton toward the top-left corner.
- Crop offset not added back. In a top-down pipeline, keypoints are predicted in crop coordinates. You must scale by the crop-to-box ratio and add the box's top-left corner. Skipping the offset places every skeleton near the image origin.
- Letterboxing. Models that pad the image to keep its aspect ratio need the padding subtracted before scaling back. Forgetting it shifts all points by a constant amount along one axis.
- Axis order. NumPy arrays are indexed
(row, column), which is(y, x). Pose coordinates are(x, y). Swapping them mirrors the skeleton along the diagonal. - Color order. OpenCV loads images as BGR, while many models expect RGB. This rarely breaks a pose model completely, but it lowers accuracy in a way that is hard to trace.
- Image rotation. Phone photos carry an EXIF orientation tag. A library that ignores the tag shows the image sideways, and the model sees a person lying down.
A sharp diagnostic is to look at the error as a pattern. A constant shift points to an offset or padding bug. A scale error that grows with distance from the origin points to a stride or resize bug. A mirrored layout points to an axis or flip bug.
Heatmap-level problems
If the final keypoints look wrong, inspect the raw heatmaps for the offending joint.
- Multiple peaks. Two strong peaks mean the model is unsure between two locations, as with a left-right ambiguity or two nearby people. The arg-max decoder picks one and discards the other, so the confidence value can still look high.
- Flat, low map. A map with no clear peak means the model sees no evidence for that joint. Expect a low score and an arbitrary location.
- Quantization. An arg-max location is limited to the heatmap grid. With a stride of 4, the position is only accurate to about 4 pixels. Sub-pixel refinement, such as shifting the location a quarter pixel toward the higher neighbouring value, usually improves accuracy at no real cost.
Temporal problems in video
Frame-by-frame prediction has no memory, so video reveals extra errors.
- Jitter. Keypoints tremble by a few pixels even for a still person. A smoothing filter such as an exponential moving average or a One Euro filter reduces it. The cost is lag: heavy smoothing makes fast motion trail behind the real body.
- Identity switches. When people cross paths, a tracker may swap their identities. Track by box overlap plus pose similarity, not box overlap alone.
- Flicker. A joint appears and disappears as its confidence crosses the threshold. Use a lower exit threshold than entry threshold (hysteresis) or hold the last valid position for a few frames.
Using OKS to find what is wrong
When you have labelled data, OKS turns "it looks wrong" into numbers. Compute the per-keypoint similarity term instead of only the mean, and average it across the dataset. A joint whose term is consistently low is a weak spot.
Compare subsets too: small people against large, crowded scenes against single-person scenes, and occluded joints (visibility 1) against fully visible ones (visibility 2). Large drops in one subset tell you where to collect data or adjust training.
Keep in mind that OKS is normalized by object area. A one-pixel error on a small person costs more than the same error on a large one, so small figures dominate failures. If keypoint AP drops but mean OKS stays flat, look at the thresholds: a few predictions may have crossed from a match to a miss.
A short checklist
- Draw the raw output on the unscaled image.
- Check the input orientation, color order and size.
- Check that the detector box exists and fits.
- Inspect heatmaps for the failing joint.
- Verify the coordinate mapping with a known test image.
- Test flip and swap logic with a synthetic example.
- Measure per-keypoint OKS by subset.
- Only then consider retraining or changing models.
Exercise
A top-down pipeline produces skeletons with the right shape and size, but every skeleton sits near the top-left corner of the image. Which bug is most likely, and how would you confirm it?
Show answer
The crop offset was not added back. The keypoints are in crop coordinates and need the bounding box's top-left corner added after scaling. To confirm, print one person's box origin and one keypoint. If adding the box origin moves the keypoint onto the body, the mapping was missing the offset.
Exercise
After adding horizontal-flip augmentation, a model starts confusing left and right wrists on test images. You flip the image and the x-coordinates. What did you probably forget, and what small test would catch it?
Show answer
You did not swap the left and right keypoint indices (the flip pairs such as 5/6 and 9/10). Flip a labelled sample, apply the flip function, and check that the old left-shoulder position now appears on the other side and carries the right-shoulder index.