Sub topic 4
Matching detections to ground truth: true and false positives
A detector outputs scored boxes, and a dataset contains labeled ground-truth boxes. Before you can compute precision, recall, or average precision (AP), you must decide which detections count as correct. This chapter defines that matching step.
This chapter assumes you know how to compute IoU for two boxes, which the previous chapter covered. It also assumes you know precision and recall from classification, and that you can read basic Python. Duplicate suppression with non-maximum suppression (NMS) came just before this chapter. Matching still has to handle duplicates, because NMS never removes all of them.
What matching has to decide
Every detection ends up with one of two labels. A detection is a true positive (TP) if it correctly finds a ground-truth object. It is a false positive (FP) if it does not. Every ground-truth box that no detection finds is a false negative (FN).
A detection is not correct just because it overlaps something. It needs all of these:
- It is in the same image as the ground-truth box.
- It has the same class label as the ground-truth box.
- Its IoU with that box is at least the chosen threshold, such as 0.5.
- That ground-truth box has not already been claimed by a higher-scoring detection.
The fourth rule is the one that makes matching a procedure instead of a simple test. Each ground-truth box can be found only once. If a detector draws three boxes around one dog, one of them is a TP and two are FPs.
There are no true negatives in detection. The space of possible empty boxes is effectively infinite, so there is nothing to count. This is why detection metrics use precision and recall and never accuracy or specificity.
The matching procedure
Matching is greedy. It processes detections from the highest score to the lowest, so confident detections get the first claim on ground truth. Run it separately for each class, and within each class look for ground truth only in the detection's own image.
For each detection, in descending score order:
- Compute the IoU between the detection and every ground-truth box of that class in the same image.
- Take the ground-truth box with the highest IoU.
- If that IoU is at least the threshold and the box is not yet matched, mark the box as matched and label the detection TP.
- Otherwise label the detection FP.
When all detections are processed, every ground-truth box still unmatched is an FN.
Sorting by score matters. If you process detections in an arbitrary order, a weak, sloppy box could claim a ground-truth object before a confident, accurate box gets its turn. The accurate box would then become an FP, and the metric would depend on file order instead of detector quality.
Implementation
This code implements the procedure. It includes the iou function from the previous chapter so the block runs on its own. The skip_matched option is explained in the variants section below.
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2) with x1 < x2 and y1 < y2."""
ix1 = max(a[0], b[0])
iy1 = max(a[1], b[1])
ix2 = min(a[2], b[2])
iy2 = min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
def match_detections(detections, ground_truths, iou_threshold=0.5, skip_matched=False):
"""Label each detection of ONE class as TP or FP.
detections: list of (image_id, score, box)
ground_truths: dict mapping image_id -> list of boxes
skip_matched: if True, only unmatched ground-truth boxes are candidates
(COCO style). If False, the best box overall is chosen
(Pascal VOC style).
Returns (results, n_fn). results is a list of
(image_id, score, label, gt_index, iou_value) in descending score order.
"""
matched = {img: [False] * len(boxes) for img, boxes in ground_truths.items()}
results = []
for img, score, box in sorted(detections, key=lambda d: -d[1]):
best_iou, best_j = 0.0, -1
for j, gt in enumerate(ground_truths.get(img, [])):
if skip_matched and matched[img][j]:
continue
v = iou(box, gt)
if v > best_iou:
best_iou, best_j = v, j
if best_j >= 0 and best_iou >= iou_threshold and not matched[img][best_j]:
matched[img][best_j] = True
results.append((img, score, "TP", best_j, best_iou))
else:
results.append((img, score, "FP", best_j, best_iou))
n_fn = sum(1 for flags in matched.values() for m in flags if not m)
return results, n_fn
gts = {"img1": [(0, 0, 10, 10), (20, 20, 30, 30)]}
dets = [
("img1", 0.9, (0, 0, 10, 10)),
("img1", 0.8, (1, 1, 10, 10)),
("img1", 0.7, (20, 20, 30, 30)),
]
results, n_fn = match_detections(dets, gts)
for r in results:
print(r)
print("FN:", n_fn)The output is:
('img1', 0.9, 'TP', 0, 1.0)
('img1', 0.8, 'FP', 0, 0.81)
('img1', 0.7, 'TP', 1, 1.0)
FN: 0Worked example
The example above has two ground-truth boxes and three detections. The table shows what happens at each step at an IoU threshold of 0.5.
| Rank | Score | Best GT | IoU | GT already matched? | Label |
|---|---|---|---|---|---|
| 1 | 0.9 | GT 0 | 1.00 | No | TP |
| 2 | 0.8 | GT 0 | 0.81 | Yes | FP |
| 3 | 0.7 | GT 1 | 1.00 | No | TP |
Detection 2 overlaps GT 0 with an IoU of 0.81, well above the threshold. It is still an FP because detection 1 already claimed that box. This is the duplicate case. Both GT boxes ended up matched, so the FN count is 0.
From these labels you can read off cumulative precision and recall as you walk down the ranking. After rank 1 the precision is 1/1 and recall is 1/2. After rank 2 the precision is 1/2 and recall stays 1/2. After rank 3 the precision is 2/3 and recall is 2/2. The next chapters build the precision-recall curve and AP from these numbers. For this example they give the AP of 0.8333 from the earlier code.
Two matching variants
Implementations differ on one point: what happens when the best-overlapping ground-truth box is already taken.
- Pascal VOC style picks the single ground-truth box with the highest IoU. If it is already matched, the detection is an FP, even if another unmatched box also overlaps enough.
- COCO style (as in
pycocotools) considers only ground-truth boxes that are still unmatched. A detection can fall back to a second box if that box clears the threshold.
The difference shows up when ground-truth boxes overlap each other, as with people in a crowd.
gts = {"img1": [(0, 0, 10, 10), (4, 0, 14, 10)]}
dets = [
("img1", 0.9, (0, 0, 10, 10)),
("img1", 0.8, (1, 0, 11, 10)),
]
for skip in (False, True):
results, n_fn = match_detections(dets, gts, 0.5, skip_matched=skip)
print("skip_matched =", skip, [r[2] for r in results], "FN:", n_fn)This prints:
skip_matched = False ['TP', 'FP'] FN: 1
skip_matched = True ['TP', 'TP'] FN: 0The second detection overlaps ground truth 0 with an IoU of about 0.82, and ground truth 1 with an IoU of about 0.54. VOC style locks onto ground truth 0, finds it taken, and reports an FP. COCO style skips ground truth 0 and matches ground truth 1. The same detector gets a slightly different score depending on the protocol. Always state which one you used.
COCO adds two further rules that this chapter's code omits. Ground-truth boxes flagged as "crowd" can absorb any number of detections without penalty. Ground-truth boxes outside the object-size range being evaluated are ignored, and detections that match them are neither TP nor FP. The COCO chapter covers both.
Why a detection becomes a false positive
An FP is a single label that hides several different failures. Separating them tells you what to fix.
| Cause | What happened | Typical fix |
|---|---|---|
| Localization error | Right class, right object, but IoU is below the threshold | Better box regression, higher input resolution |
| Duplicate | Object already claimed by a higher-scoring box | Tune NMS, check for overlapping anchors |
| Background | No ground-truth object near the box | Hard-negative mining, more background data |
| Classification error | Box fits an object, but the class is wrong | Better classifier, more data for confusable classes |
| Missing annotation | The object is real but the dataset lacks a label | Fix the annotations |
Only the first two are decided by the matching rule itself. Class confusion shows up because matching is per class. A box labeled "cat" on a ground-truth dog is an FP for cat, and the dog becomes an FN for dog.
Edge cases and gotchas
- The threshold is inclusive. The condition is IoU
>=threshold. A detection with an IoU of exactly 0.5 counts at a threshold of 0.5. This rarely matters with real floats, but it matters in hand-built test cases. - Do not filter by score before matching. Evaluation needs the full ranked list, including low-confidence detections, because they trace the right-hand end of the precision-recall curve. Dropping detections below, say, 0.5 before scoring truncates recall and changes AP. Deployment thresholds belong to a separate analysis.
- Ties in score. The code uses a stable sort, so equal-scored detections keep their input order. If two tied detections compete for one ground-truth box, which one becomes the TP depends on that order. Some libraries break ties differently, which can cause tiny metric differences.
- Images with no ground truth. The
ground_truths.get(img, [])call means every detection in such an image is an FP. This is correct. Do not drop these images from the evaluation, because they measure how well the detector avoids false alarms. - Class-agnostic matching is a different metric. If you ignore the class when matching, a mislabeled box can count as a TP. That measures localization only and is not comparable with standard mAP.
- Coordinate formats must agree. Matching only works if detections and ground truth use the same box format and the same pixel or normalized units. A detection in
(x, y, w, h)compared against(x1, y1, x2, y2)produces garbage IoUs without any error. - Greedy is not optimal. The procedure does not search for the assignment that maximizes the number of TPs. A high-scoring box can take a ground-truth box that a lower-scoring box would have fit better. Standard benchmarks accept this, because the result is deterministic and depends on confidence order.
Check your understanding
Exercise
A detector outputs two boxes for the same single ground-truth object, both with IoU above 0.5. The scores are 0.95 and 0.60. Which is the TP, which is the FP, and what is the FN count?
Show answer
The 0.95 box is processed first, claims the ground-truth box, and is the TP. The 0.60 box finds its best ground-truth box already matched, so it is an FP (a duplicate). The ground-truth box is matched, so the FN count is 0.
Exercise
At an IoU threshold of 0.5, a detection has IoU 0.48 with its object. At a threshold of 0.75, what is its label, and why can lowering the threshold to 0.45 change the labels of other detections as well?
Show answer
At 0.75 it is an FP, because 0.48 is below the threshold. At 0.45 it becomes a TP and claims the ground-truth box. Any lower-scoring detection that previously matched that box as a TP would now be a duplicate and become an FP. So a change in threshold can alter labels beyond the detection whose IoU crossed it.
Exercise
An image contains two ground-truth boxes of the same class that overlap each other. One detection overlaps both with IoU 0.8 on box A and 0.6 on box B, and box A was already matched by a higher-scoring detection. What label does it get under VOC style and under COCO style at threshold 0.5?
Show answer
Under VOC style it is an FP, because its best box (A) is already matched. Under COCO style it is a TP on box B, because matched boxes are skipped and B's IoU of 0.6 clears the threshold.