Sub topic 3
Datasets, annotations and visibility flags
This chapter assumes you know basic Python and NumPy, can read JSON, and have seen the COCO 17-keypoint layout from the first chapter. It covers how pose datasets store keypoints, what the visibility flag means, and how the flag changes training and evaluation. Bugs in this layer rarely raise errors. A misread flag or a missed left-right swap just makes the model quietly worse.
The main pose datasets
Datasets differ in joint count, in how they mark hidden joints, and in how crowded their scenes are. The skeleton you train on decides which pretrained weights and metrics you can reuse.
| Dataset | Keypoints | Notes |
|---|---|---|
| COCO Keypoints | 17 | Over 250,000 labelled people in everyday scenes. Three-valued visibility flag. Standard benchmark for OKS and keypoint AP. |
| MPII Human Pose | 16 | Activity-focused images. Single-person and multi-person protocols. Per-joint visible/not-visible flag. |
| CrowdPose | 14 | Heavily overlapping people, built to test crowded scenes. |
| AI Challenger | 14 | Large dataset with its own skeleton and flag convention. |
| COCO-WholeBody | 133 | Adds hands, face and feet to the 17 body keypoints. |
| Human3.6M | 3D joints | Motion-capture data for 3D pose. See the lifting chapter. |
Mixing datasets means mapping skeletons to a common joint list first. Joints like "neck" or "pelvis" that one dataset has and another lacks must be treated as unlabelled, not as zeros.
The COCO annotation record
COCO stores one JSON file per split. The annotations list has one entry per person, linked to an image by image_id. The fields that matter for pose are:
keypoints: a flat list of 51 numbers,[x1, y1, v1, x2, y2, v2, ...], in the fixed COCO joint order.num_keypoints: how many keypoints havev > 0.bbox:[x, y, width, height]of the person. The format is top-left corner plus size, not two corners.area: the area of the person's segmentation mask, not of the box. OKS uses it later as a scale.iscrowd: 1 for a group region that is not an individual person.
Coordinates are in image pixels, with x to the right and y downward.
Visibility flags
Each keypoint carries a flag v with three values.
| `v` | Meaning | Stored `x, y` |
|---|---|---|
| 0 | Not labelled. Either outside the image or impossible to place. | `0, 0` |
| 1 | Labelled but not visible. The annotator could infer where it is (for example a wrist behind the back). | Annotator's estimate |
| 2 | Labelled and visible. | Actual position |
The key trap is that a v = 0 point is stored at (0, 0). That location is a real pixel in the top-left corner. If you ignore the flag and treat the coordinates as data, the model learns to pull some joints toward the corner.
Parsing annotations into arrays
The function below turns a COCO record into a coordinate array and a flag array. It also builds the label mask, which says which joints are allowed to contribute to a loss.
import numpy as np
KEYPOINT_NAMES = [
"nose", "left_eye", "right_eye", "left_ear", "right_ear",
"left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
"left_wrist", "right_wrist", "left_hip", "right_hip",
"left_knee", "right_knee", "left_ankle", "right_ankle",
]
# Triples are (x, y, v) in COCO joint order.
triples = [
(320, 100, 2), (332, 92, 2), (308, 92, 2), (0, 0, 0), (296, 98, 1),
(360, 160, 2), (280, 160, 2), (385, 235, 2), (255, 235, 1),
(400, 300, 2), (0, 0, 0), (350, 300, 2), (290, 300, 2),
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
]
annotation = {
"image_id": 1,
"category_id": 1,
"iscrowd": 0,
"num_keypoints": 11,
"bbox": [240.0, 70.0, 180.0, 260.0],
"keypoints": [value for triple in triples for value in triple],
}
def parse_keypoints(ann):
"""Return (xy, vis, mask): (K, 2) float coords, (K,) int flags, (K,) bool mask."""
kp = np.asarray(ann["keypoints"], dtype=np.float32).reshape(-1, 3)
xy = kp[:, :2]
vis = kp[:, 2].astype(np.int64)
mask = vis > 0
return xy, vis, mask
xy, vis, mask = parse_keypoints(annotation)
print("labelled:", int(mask.sum()))
print("flags 0/1/2:", [int((vis == v).sum()) for v in (0, 1, 2)])
print("first unlabelled joint:", KEYPOINT_NAMES[int(np.argmin(mask))])This prints 11 labelled joints, the flag counts [6, 2, 9], and left_ear as the first unlabelled joint.
How the flags are used in training
During training, the mask decides which joints contribute to the loss. A heatmap target for an unlabelled joint should be all zeros and should carry no loss weight. Otherwise the network is told "there is no joint anywhere" for a joint that exists but was simply not annotated.
Treatment of v = 1 varies between codebases. Many pipelines treat v > 0 as a valid target, so the model learns to guess hidden joints. Some use only v = 2, which gives cleaner supervision but never teaches the model to reason about occlusion. Check which your framework does before comparing results.
Augmentation must respect the flags
Augmentation changes coordinates, and the flags must follow. The most common source of bugs is horizontal flipping. After a mirror flip, the person's left wrist becomes the image's right-hand wrist, so the joint labels must be swapped as well as the x coordinates.
FLIP_INDEX = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]
def flip_pose(xy, vis, image_width):
"""Horizontal flip: swap left/right joints, mirror x, keep unlabelled joints at (0, 0)."""
xy_f = xy[FLIP_INDEX].copy()
vis_f = vis[FLIP_INDEX].copy()
xy_f[:, 0] = (image_width - 1) - xy_f[:, 0]
xy_f[vis_f == 0] = 0.0
return xy_f, vis_f
xy_f, vis_f = flip_pose(xy, vis, image_width=640)
print(KEYPOINT_NAMES[1], "->", xy_f[1]) # left_eye now holds the old right_eye, mirrored
print("flags preserved in count:", int((vis_f > 0).sum()) == int((vis > 0).sum()))The last line should print True. The final xy_f[vis_f == 0] = 0.0 matters. Without it, the mirror step would turn the placeholder (0, 0) into (639, 0), which looks like a real labelled point.
Other transforms need similar care. Cropping can push a labelled joint outside the crop. Treat it as unlabelled (v = 0), not as clipped to the border. Rotation and scaling must be applied to both coordinates and the crop box.
Validating a dataset before you train
A short consistency check catches most conversion errors, especially when you build annotations from another tool.
def validate(ann, image_width, image_height):
problems = []
xy, vis, mask = parse_keypoints(ann)
if len(vis) != 17:
problems.append(f"expected 17 keypoints, got {len(vis)}")
if int(mask.sum()) != ann["num_keypoints"]:
problems.append("num_keypoints does not match count of v > 0")
if np.any(xy[~mask] != 0):
problems.append("unlabelled joints have non-zero coordinates")
inside = (xy[mask, 0] >= 0) & (xy[mask, 0] < image_width) & \
(xy[mask, 1] >= 0) & (xy[mask, 1] < image_height)
if not inside.all():
problems.append("labelled joint lies outside the image")
if not set(np.unique(vis)).issubset({0, 1, 2}):
problems.append("flag outside {0, 1, 2}")
return problems
print(validate(annotation, 640, 480) or "ok")How the flags are used in evaluation
The COCO evaluator uses the annotation fields in specific ways, and they affect how you read your scores.
- Only ground-truth joints with
v > 0count in OKS. Predictions atv = 0joints are neither rewarded nor penalised. - A person with
num_keypoints = 0is ignored. Detections on such people are not false positives. - Crowd regions (
iscrowd = 1) are ignored too. areacomes from the person mask. A tiny person with a loose box is still scored on the small mask area.
The next chapters on OKS and keypoint AP build on this. Wrong flags in a custom dataset make the metric look better or worse without any change in model quality.
Common errors
- Using the coordinates of
v = 0joints as targets, which drags predictions toward the corner. - Flipping images without swapping left and right joint indices, so the model learns inconsistent labels.
- Reading
bboxas[x1, y1, x2, y2]when it is[x, y, w, h]. - Comparing scores across codebases that treat
v = 1differently. - Merging datasets with different skeletons without marking missing joints as unlabelled.
Exercise
A training image is flipped horizontally. The original annotation has the left wrist at (400, 300) with v = 2, the right wrist at (0, 0) with v = 0, and the image is 640 pixels wide. Using FLIP_INDEX and the (width - 1) - x convention, what are the coordinates and flags of the left and right wrist after the flip?
Show answer
The joints swap roles first. The new left wrist comes from the old right wrist, so it has v = 0 and is reset to (0, 0) after the mirror step. The new right wrist comes from the old left wrist: x = 639 - 400 = 239, y stays 300, v = 2. Result: left wrist (0, 0) with v = 0, right wrist (239, 300) with v = 2.
Exercise
Why is a v = 1 joint different from a v = 0 joint, and what are the two ways a training pipeline might handle v = 1?
Show answer
A v = 1 joint was labelled with an estimated position even though it is hidden, so it has a usable location. A v = 0 joint has no location at all, and its stored (0, 0) is a placeholder. A pipeline can either treat all v > 0 joints as valid targets, which teaches the model to guess occluded joints, or train only on v = 2 joints, which gives cleaner supervision but no occlusion reasoning.