Sub topic 12
Evaluating pose: OKS and keypoint AP
This chapter assumes you know how average precision (AP) works for object detection, that is, precision-recall curves and IoU thresholds. It also assumes you can read the COCO keypoint annotation format from the earlier chapter on datasets and visibility flags. You will learn how a predicted skeleton is scored against a labelled one, and how those scores become the AP numbers in pose papers and leaderboards.
Why box IoU does not work for keypoints
In detection, a prediction matches a ground-truth object when the intersection over union (IoU) of their boxes passes a threshold. A pose has no natural overlap area. A skeleton is 17 points, and a bounding box around it says little about whether the wrist or the knee is in the right place. Two skeletons can have identical boxes and very different limbs.
Keypoint evaluation keeps the AP machinery but swaps the similarity measure. IoU becomes Object Keypoint Similarity (OKS), a number between 0 and 1 that plays the same role. Everything after the matching step (sorting by score, precision-recall curves, averaging over thresholds) works as it does for detection.
Object Keypoint Similarity
For one person, OKS averages a per-keypoint similarity over the keypoints that were labelled:
OKS = sum_i [ exp(-d_i^2 / (2 * s^2 * k_i^2)) * (v_i > 0) ] / sum_i [ v_i > 0 ]The terms are:
d_iis the Euclidean distance in pixels between predicted and ground-truth keypointi.s^2is the object scale, defined in COCO as the ground-truth object's segmentation area. It is not the bounding-box area.k_i = 2 * sigma_i, wheresigma_iis a constant for each keypoint type.v_iis the ground-truth visibility flag. Only keypoints withv_i > 0count.
Each keypoint contributes a Gaussian-shaped score. A perfect hit gives 1. The score falls toward 0 as the error grows relative to the person's size and to that keypoint's tolerance.
import numpy as np
SIGMAS = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72,
.62, .62, 1.07, 1.07, .87, .87, .89, .89]) / 10.0
def oks(gt, pred, visibility, area):
"""gt, pred: (17, 2) arrays. visibility: (17,) COCO flags. area: ground-truth object area."""
d2 = ((gt - pred) ** 2).sum(axis=1)
var = (2 * SIGMAS) ** 2
e = d2 / (2 * var * (area + np.spacing(1)))
mask = visibility > 0
return float(np.exp(-e)[mask].mean()) if mask.any() else 0.0What the sigmas mean
The constants follow the COCO order: nose, eyes, ears, shoulders, elbows, wrists, hips, knees, ankles. They were estimated from how much human annotators disagree when clicking each point. Eyes (0.025) are small and well-defined, so annotators agree closely. Hips (0.107) have no sharp visual landmark, so annotators vary a lot. A larger sigma makes the metric more forgiving for that joint.
Here is a worked comparison. Take a person with area 10,000 px², so s is about 100 px. Suppose the prediction is 10 px off.
| Keypoint | sigma | exp term | Similarity |
|---|---|---|---|
| Nose | 0.026 | 100 / (2 × 0.052² × 10000) = 1.85 | about 0.16 |
| Shoulder | 0.079 | 100 / (2 × 0.158² × 10000) = 0.20 | about 0.82 |
The same 10 px error nearly zeroes the nose and barely hurts the shoulder. The scale term also means that 10 px is a large error for a small person and a minor one for a large person.
Visibility flags and what gets scored
The visibility flag in the ground truth decides which keypoints enter the average:
v = 0: not labelled. The keypoint is ignored, so predicting it anywhere costs nothing.v = 1: labelled but occluded. It is scored.v = 2: labelled and visible. It is scored.
Two consequences follow. First, the model is never rewarded for saying a joint is hidden. OKS uses only the predicted position, not the predicted confidence, so a model must guess a position for occluded joints, and that guess is graded. Second, the denominator counts labelled keypoints only. A person annotated with 5 keypoints is scored on those 5.
From OKS to keypoint AP
Once OKS is defined, AP follows the detection recipe. The evaluator takes these steps:
- Collect every predicted person in the dataset, each with a person-level confidence score.
- Sort the predictions by score, highest first.
- For one OKS threshold, walk down the list. Match each prediction to the unmatched ground-truth person with the highest OKS. If that OKS is at least the threshold, the prediction is a true positive. Otherwise it is a false positive.
- Build the precision-recall curve, then take the area under it using 101-point interpolation.
- Repeat for thresholds 0.50, 0.55, ..., 0.95 and average the ten APs.
The standard report has these columns:
| Metric | Meaning |
|---|---|
| AP | Mean over 10 OKS thresholds, the headline number |
| AP50 | AP at OKS 0.50, a loose match |
| AP75 | AP at OKS 0.75, a strict match |
| APM | AP for medium people (area between 32² and 96² px) |
| APL | AP for large people (area above 96² px) |
| AR | Average recall over the same thresholds |
There is no APS. COCO does not annotate keypoints on very small people, so that bucket is empty.
Where the person-level score comes from
OKS ranks nothing by itself. The sort in step 2 uses a single score per person, and the choice matters because it sets the order of false and true positives. Top-down models often use the detector confidence. Many implementations multiply it by the mean keypoint confidence, or rescore with a learned head. Two models with the same keypoints can get different AP just because they rank people differently.
Running the official evaluator
Do not reimplement AP for reported numbers. Use pycocotools, which has the exact matching rules, including crowd and ignore regions. Predictions must be a JSON list in the COCO results format. Each entry has a flat list of 51 numbers, which is x, y, score repeated 17 times.
import json
import numpy as np
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
def to_coco_result(image_id, xy, conf, person_score):
"""xy: (17, 2) in original-image pixels. conf: (17,). Returns one COCO result dict."""
flat = np.concatenate([xy, conf[:, None]], axis=1).reshape(-1)
return {
"image_id": int(image_id),
"category_id": 1,
"keypoints": [float(v) for v in flat],
"score": float(person_score),
}
# results = [to_coco_result(...) for each predicted person]
# json.dump(results, open("predictions.json", "w"))
gt = COCO("annotations/person_keypoints_val2017.json")
dt = gt.loadRes("predictions.json")
ev = COCOeval(gt, dt, iouType="keypoints")
ev.evaluate()
ev.accumulate()
ev.summarize()
print(dict(zip(["AP", "AP50", "AP75", "APM", "APL"], ev.stats[:5])))The file predictions.json must exist first, so run the commented lines before the evaluation. Passing iouType="keypoints" is what switches the evaluator from box IoU to OKS.
Common errors
- Wrong coordinate space. The evaluator expects pixels in the original image. If you decode heatmaps (see the decoding chapter) and forget to undo the crop, resize and stride, every OKS collapses and AP is near zero. Check that a few predictions line up when drawn on the original image.
- Wrong keypoint order. Left and right swapped, or a different layout such as a 133-point whole-body model, ruins scoring even if the picture looks right.
- Using bounding-box area for
area. COCO uses segmentation area, so a hand-built OKS with box area gives different values from the official tool. - Too many or too few detections. The evaluator keeps at most 20 detections per image. Dumping hundreds of low-score people does not help and wastes time.
- Confusing the thresholds. A model with high AP50 and low AP75 finds the right people but places joints loosely. That points toward heatmap resolution or sub-pixel decoding, not detection.
Exercise
A person has area 8,000 px². The model's left wrist prediction is 20 px from the label, and the wrist sigma is 0.062. Compute the similarity for this one keypoint. Then say whether the result changes if the ground-truth visibility flag for this wrist is 0.
Show answer
k = 2 × 0.062 = 0.124, so k² = 0.015376. The exponent is d² / (2 × area × k²) = 400 / (2 × 8000 × 0.015376) = 400 / 246 ≈ 1.626. The similarity is exp(-1.626) ≈ 0.197. If the visibility flag is 0, the wrist is unlabelled. It is dropped from both the numerator and the denominator, so it does not affect OKS at all.
Exercise
A model has AP50 = 85 and AP75 = 40. What does the gap suggest, and name one change you would try first?
Show answer
The model finds most people and roughly places their joints, since AP50 is high. It places joints imprecisely, since AP75 is low. Try raising heatmap resolution or input crop size, or add sub-pixel refinement to the decoding step. Detection quality is not the main problem.