Detection Metrics: IoU, AP and mAP
An object detector looks at an image and returns a list of boxes, each with a class and a confidence score. Evaluating it is harder than evaluating a classifier: a predicted box can be almost right, a model can find the same car twice, it can invent objects, and the number of objects differs per image. The standard answer, used by PASCAL VOC, COCO and every detection paper since, has three parts: IoU decides whether a box is close enough, matching turns boxes into true and false positives, and average precision summarises the precision-recall curve over all scores, per class, then averaged into mAP. You build all three here in NumPy on a few hand-made boxes. The Computer Vision course uses them with real detectors.
Intersection over union
A box is [x1, y1, x2, y2], the top-left and bottom-right corners in pixels. For a predicted box and a ground-truth box :
IoU is 1 for identical boxes and 0 for boxes that do not touch. It is scale-free: a 5-pixel offset is serious for a 20-pixel box and harmless for a 400-pixel one. A detection counts as correct at threshold 0.5 (VOC) when .
import numpy as np
def area(b):
return np.clip(b[..., 2] - b[..., 0], 0, None) * np.clip(b[..., 3] - b[..., 1], 0, None)
def iou(a, b):
"""IoU of every box in a (n, 4) with every box in b (m, 4): an (n, m) matrix."""
a, b = np.asarray(a, float)[:, None, :], np.asarray(b, float)[None, :, :]
inter_box = np.concatenate([np.maximum(a[..., :2], b[..., :2]), np.minimum(a[..., 2:], b[..., 2:])], axis=-1)
inter = area(inter_box)
return inter / (area(a) + area(b) - inter)
gt = [[30, 30, 130, 110]]
preds = [[45, 40, 145, 120], # shifted by (15, 10)
[70, 50, 170, 130], # shifted by (40, 20)
[150, 30, 200, 90], # elsewhere
[30, 30, 130, 110]] # identical
print(iou(preds, gt).round(3).ravel().tolist())[0.592, 0.29, 0.0, 1.0]
The ground-truth box is 100 by 80 pixels. Shifted by 15 and 10 pixels, the prediction still has IoU 0.592 and counts as a hit at 0.5; shifted by 40 and 20 it drops to 0.290 and counts as a miss and a false positive. The figure above draws these first two pairs to scale.
Matching detections to objects
Per class, take all detections from all images and sort them by score, highest first. Walk down the list. A detection is a true positive if its best-overlapping ground-truth box in the same image has and has not been matched yet; otherwise it is a false positive. So a second box on the same car is a false positive (the detector should have suppressed it with non-maximum suppression), and an object nobody found is a false negative. After each detection, compute precision and recall so far:
where is the number of ground-truth objects of that class. That gives a precision-recall curve over the score, exactly as in ROC and PR curves, except that recall may never reach 1 (objects that no box hit).
Average precision, VOC style
The PR curve of a detector zig-zags. VOC (since 2010) first replaces each precision by the highest precision at any recall at least as large (the "interpolated" precision, a monotone envelope), then sums it over the recall steps:
mAP is the mean of the AP of every class. COCO changes two things: it samples the envelope at 101 recall points , and its headline number AP@[.5:.95] averages the mAP over ten IoU thresholds , so it rewards tight boxes, not just roughly placed ones. In COCO papers "AP" already means this mean over classes and thresholds.
Three images, two classes (car and person), seven objects and twelve detections:
import numpy as np
def iou1(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
# ground truth: (image, class, box)
gts = [(0, "car", [10, 10, 50, 40]), (0, "car", [60, 20, 100, 60]), (0, "person", [20, 50, 35, 90]),
(1, "car", [5, 5, 45, 35]), (1, "person", [50, 10, 65, 50]), (1, "person", [70, 15, 85, 55]),
(2, "car", [30, 30, 80, 70])]
# detections: (image, class, score, box)
dets = [(0, "car", 0.95, [12, 12, 52, 42]), (0, "car", 0.80, [58, 25, 98, 62]), (0, "car", 0.40, [11, 9, 49, 41]),
(1, "car", 0.90, [8, 4, 50, 38]), (1, "car", 0.60, [60, 60, 90, 90]), (2, "car", 0.70, [40, 40, 90, 80]),
(2, "car", 0.30, [28, 32, 78, 72]), (0, "person", 0.85, [22, 52, 37, 88]), (1, "person", 0.75, [51, 12, 66, 52]),
(1, "person", 0.65, [40, 10, 55, 50]), (1, "person", 0.35, [72, 20, 88, 58]), (2, "person", 0.50, [0, 0, 20, 20])]
def average_precision(cls, thr=0.5, verbose=False):
g = [(img, box) for img, c, box in gts if c == cls]
used = [False] * len(g)
d = sorted([x for x in dets if x[1] == cls], key=lambda x: -x[2])
tp = []
for img, _, score, box in d:
cands = [(iou1(box, gb), j) for j, (gi, gb) in enumerate(g) if gi == img]
best, j = max(cands, default=(0.0, -1))
hit = best >= thr and not used[j]
if hit:
used[j] = True
tp.append(hit)
if verbose:
print(f" img {img} score {score:.2f} best IoU {best:.3f} -> {'TP' if hit else 'FP'}")
tp = np.array(tp, float)
precision = np.cumsum(tp) / np.arange(1, len(tp) + 1)
recall = np.cumsum(tp) / len(g)
envelope = np.maximum.accumulate(precision[::-1])[::-1] # max precision to the right
ap = np.sum(np.diff(np.r_[0, recall]) * envelope)
if verbose:
print(" precision", precision.round(3).tolist())
print(" recall ", recall.round(3).tolist())
print(" envelope ", envelope.round(3).tolist())
return ap
print("car:")
ap_car = average_precision("car", verbose=True)
print("person:")
ap_person = average_precision("person", verbose=True)
print(f"AP@0.5 car {ap_car:.3f} person {ap_person:.3f} mAP {np.mean([ap_car, ap_person]):.3f}")car:
img 0 score 0.95 best IoU 0.796 -> TP
img 1 score 0.90 best IoU 0.731 -> TP
img 0 score 0.80 best IoU 0.760 -> TP
img 2 score 0.70 best IoU 0.429 -> FP
img 1 score 0.60 best IoU 0.000 -> FP
img 0 score 0.40 best IoU 0.893 -> FP
img 2 score 0.30 best IoU 0.838 -> TP
precision [1.0, 1.0, 1.0, 0.75, 0.6, 0.5, 0.571]
recall [0.25, 0.5, 0.75, 0.75, 0.75, 0.75, 1.0]
envelope [1.0, 1.0, 1.0, 0.75, 0.6, 0.571, 0.571]
person:
img 0 score 0.85 best IoU 0.696 -> TP
img 1 score 0.75 best IoU 0.796 -> TP
img 1 score 0.65 best IoU 0.200 -> FP
img 2 score 0.50 best IoU 0.000 -> FP
img 1 score 0.35 best IoU 0.604 -> TP
precision [1.0, 1.0, 0.667, 0.5, 0.6]
recall [0.333, 0.667, 0.667, 0.667, 1.0]
envelope [1.0, 1.0, 0.667, 0.6, 0.6]
AP@0.5 car 0.893 person 0.867 mAP 0.880
Follow the car list. The first three detections hit three different cars, so precision stays 1 while recall climbs to 0.75. The box at score 0.70 overlaps the car in image 2 with IoU 0.429, below 0.5: a false positive. The score-0.40 box overlaps the first car with IoU 0.893, a near-perfect box, yet it is a false positive, because that car was already taken by the 0.95 box. The last detection (score 0.30) finds the fourth car. The envelope turns the zig-zag into a staircase, and . For persons, , and the mAP over the two classes is 0.880.
Notice how much the late true positive is worth: without the score-0.30 box the car recall would stop at 0.75 and AP would be 0.75. That is why detectors are evaluated with a very low score threshold.
Stricter IoU thresholds
The same detections at the COCO thresholds. Rerun the matching for each IoU threshold and average:
import numpy as np
def iou1(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
gts = [(0, "car", [10, 10, 50, 40]), (0, "car", [60, 20, 100, 60]), (0, "person", [20, 50, 35, 90]),
(1, "car", [5, 5, 45, 35]), (1, "person", [50, 10, 65, 50]), (1, "person", [70, 15, 85, 55]),
(2, "car", [30, 30, 80, 70])]
dets = [(0, "car", 0.95, [12, 12, 52, 42]), (0, "car", 0.80, [58, 25, 98, 62]), (0, "car", 0.40, [11, 9, 49, 41]),
(1, "car", 0.90, [8, 4, 50, 38]), (1, "car", 0.60, [60, 60, 90, 90]), (2, "car", 0.70, [40, 40, 90, 80]),
(2, "car", 0.30, [28, 32, 78, 72]), (0, "person", 0.85, [22, 52, 37, 88]), (1, "person", 0.75, [51, 12, 66, 52]),
(1, "person", 0.65, [40, 10, 55, 50]), (1, "person", 0.35, [72, 20, 88, 58]), (2, "person", 0.50, [0, 0, 20, 20])]
def ap(cls, thr, points101=False):
g = [(img, box) for img, c, box in gts if c == cls]
used, tp = [False] * len(g), []
for img, _, score, box in sorted([x for x in dets if x[1] == cls], key=lambda x: -x[2]):
best, j = max([(iou1(box, gb), j) for j, (gi, gb) in enumerate(g) if gi == img], default=(0.0, -1))
hit = best >= thr and not used[j]
if hit:
used[j] = True
tp.append(hit)
tp = np.array(tp, float)
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / len(g)
env = np.maximum.accumulate(prec[::-1])[::-1]
if points101: # COCO: envelope sampled at recall 0, 0.01, ..., 1
return np.mean([env[rec >= r].max() if np.any(rec >= r) else 0.0 for r in np.linspace(0, 1, 101)])
return np.sum(np.diff(np.r_[0, rec]) * env)
for thr in [0.5, 0.75, 0.9]:
print(f"IoU {thr:.2f}: car {ap('car', thr):.3f} person {ap('person', thr):.3f} mAP {np.mean([ap('car', thr), ap('person', thr)]):.3f}")
thrs = np.round(np.arange(0.5, 0.96, 0.05), 2)
coco = np.mean([np.mean([ap(c, t, points101=True) for c in ["car", "person"]]) for t in thrs])
print(f"mAP@0.5 with 101-point sampling: {np.mean([ap(c, 0.5, True) for c in ['car', 'person']]):.3f}")
print(f"COCO-style AP@[.5:.95] over {len(thrs)} thresholds: {coco:.3f}")IoU 0.50: car 0.893 person 0.867 mAP 0.880
IoU 0.75: car 0.524 person 0.167 mAP 0.345
IoU 0.90: car 0.000 person 0.000 mAP 0.000
mAP@0.5 with 101-point sampling: 0.880
COCO-style AP@[.5:.95] over 10 thresholds: 0.439
At IoU 0.75 the car AP falls to 0.524 (the 0.90 box with IoU 0.731 no longer counts) and the person AP to 0.167; at 0.9 no box is tight enough. Averaged over the ten COCO thresholds, the AP is 0.439, half the VOC-style 0.880, although the detections are the same. On this tiny example the 101-point sampling gives the same 0.880 as the all-point sum at IoU 0.5; on real curves the two differ slightly.
Pitfalls
- Comparing mAP numbers from different protocols. VOC mAP@0.5, COCO AP@[.5:.95] and "mAP50" from a training log are different quantities; COCO AP is typically much lower than mAP@0.5 for the same model.
- Box format.
[x1, y1, x2, y2],[x, y, w, h](COCO) and normalised centre format (YOLO) all exist. An IoU computed on mixed formats is silently wrong; convert first (Computer Vision covers annotation formats). - Duplicates count against you. Without non-maximum suppression, every extra box on an object is a false positive.
- Small objects. A few pixels of error ruin IoU for tiny boxes; COCO therefore also reports AP for small, medium and large objects separately.
- Score thresholds before evaluation. AP needs the low-score detections too; filtering at 0.5 first cuts the curve short and lowers recall.
Practice
- Box A is
[0, 0, 10, 10], box B is[5, 0, 15, 10]. Compute the IoU.
Answer
Intersection [5, 0, 10, 10] has area 50; each box has area 100; union ; IoU . Shifting a box by half its width already fails the 0.5 threshold.
- A class has 4 objects. Sorted detections are TP, FP, TP, TP, FP. Compute the VOC all-point AP.
Answer
Precision: ; recall: . Envelope (max to the right): . Recall steps of 0.25 at detections 1, 3 and 4: .
Test yourself
A second detection overlaps an already matched car with IoU 0.9. How is it counted?
- true positive
- false positive
- false negative
- ignored
What does COCO's AP@[.5:.95] average over?
- Images
- Ten IoU thresholds from 0.5 to 0.95 (and the classes)
- Ten score thresholds
- Box sizes
Two boxes of area 100 overlap in an area of 60. What is their IoU?
- 0.6
- 0.429
- 0.3
- 0.75
Why do detection PR curves often never reach recall 1?
- Because of the interpolation
- Some objects are never hit by any detection with enough IoU
- Recall is capped at 0.5
- Because precision is interpolated