Object Detection Fundamentals
Imagine handing a computer a photograph of a busy street. Then asking a simple question: what is here, and where exactly is it? A classifier trained on ImageNet and Benchmark Datasets can tell you "car" appears somewhere in the image. But it cannot draw a box around each vehicle, pedestrian, or traffic sign. That extra requirement — localizing every instance of every object category simultaneously — is the object detection task. It sits at the foundation of self-driving perception stacks, medical image analysis, robotic manipulation, video surveillance, and augmented reality. Object detection is harder than classification along three axes at once. The number of objects in an image is unknown and variable. Each object needs a precise location, not just a label. And the evaluation must reward boxes that are both correctly classified and geometrically accurate. There is no clean notion of "correct" the way top-1 accuracy provides for classification. This forces the field to invent new geometric primitives (bounding boxes). It also requires new overlap measures (Intersection over Union), and new aggregate metrics (mean Average Precision). All this must happen before any neural architecture can even be discussed. This article builds those foundations from first principles. It covers what a detection output actually is, and how to measure whether a predicted box "counts" as correct. It also explains how to turn a pile of graded predictions into a single number. That number lets researchers compare systems. Finally, it explores why each design choice is the way it is. Everything here is architecture-agnostic. It applies equally to two-stage detectors, single-shot detectors, and modern transformer-based detectors. That is because it defines the problem, not the solution. By the end, you will be able to compute IoU by hand. You will understand precisely what "AP at IoU 0.5" means. You will trace a full mAP computation on a small worked dataset. And you will see why concepts like anchor boxes and non-maximum suppression exist. These exist as direct consequences of the definitions given here.
- Object detection outputs a set of (bounding box, class label, confidence score) triples per image, unlike classification's single label.
- Intersection over Union (IoU) measures bounding-box overlap and is the geometric currency of the entire field.
- A predicted box is a true positive only if its class matches and its IoU with a ground-truth box exceeds a threshold (commonly 0.5).
- Precision-recall curves, built by ranking predictions by confidence, summarize a detector's tradeoff between false alarms and missed detections.
- Average Precision (AP) is the area under the precision-recall curve per class; mean AP (mAP) averages AP across classes and sometimes across IoU thresholds.
- These definitions directly motivate later machinery: Anchor Boxes for proposing candidate regions, the R-CNN Family for classifying and refining them, and Non-Maximum Suppression for pruning duplicate detections.
Object detection turns "what is in this image" into "what is where," and every metric in the field exists to grade how well a box's location and label match reality.
The idea
Object detection is the task of predicting, for a given image, a variable-length set of detections, each consisting of a bounding box — typically parameterized as or — a class label from a fixed category set, and a confidence score in expressing the model's certainty. This is fundamentally different from image classification, which produces exactly one label (or one probability vector) per image regardless of how many objects it contains. Detection must handle images with zero, one, or dozens of objects, of different classes, sizes, and overlapping arrangement, using an output structure whose size is not fixed in advance. To decide whether a predicted box is "correct," detection needs a notion of geometric agreement between two boxes. The standard measure is Intersection over Union (IoU), also called the Jaccard index:
where and are the pixel regions enclosed by two boxes. IoU is for identical boxes, for non-overlapping boxes, and smoothly interpolates in between — crucially, it is scale-invariant (a tiny box overlapping perfectly scores the same as a huge one) and penalizes both under- and over-sized predictions, unlike pixel-distance measures that only penalize translation. A prediction is declared a true positive (TP) if (a) its class matches a ground-truth object's class, and (b) its IoU with that ground-truth box exceeds a chosen threshold (commonly ). Each ground-truth box can be matched at most once — greedily, in order of confidence — so a second detector output claiming the same object becomes a false positive (FP), since it is a duplicate. Ground-truth objects with no matching prediction above threshold are false negatives (FN). This bookkeeping, class by class and image by image, is the substrate on which precision, recall, Average Precision (AP), and finally mean Average Precision (mAP) — the field's single most quoted number — are built.
How it works
The evaluation pipeline for object detection proceeds in five stages, run independently per class and then combined.
Stage 1 — Collect all predictions and ground truths. Across the entire test set, gather every predicted box for a class (with its confidence score) and every ground-truth box labeled .
Stage 2 — Sort predictions by confidence, descending. This ordering determines the order in which predictions get a chance to claim a ground-truth match — high-confidence predictions are matched first, mirroring how a real system would be used (trusting its most confident outputs first).
Stage 3 — Greedily match. Walk down the sorted list. For each prediction, find the unmatched ground-truth box of the same class in the same image with highest IoU. If that IoU exceeds , mark it TP and mark the ground-truth box as "used." Otherwise mark the prediction FP.
Stage 4 — Build the precision-recall curve. At each rank in the sorted list, compute cumulative precision and recall using only the first predictions:
Stage 5 — Integrate to get AP, then average to get mAP. AP is the area under the (interpolated, monotonic) precision-recall curve for class ; mAP averages AP over all classes (and, in modern benchmarks, over several IoU thresholds). ```
# ---- IoU between two axis-aligned boxes ---- function IoU(boxA, boxB): xA = max(boxA.x1, boxB.x1) yA = max(boxA.y1, boxB.y1) xB = min(boxA.x2, boxB.x2) yB = min(boxA.y2, boxB.y2) interW = max(0, xB - xA) interH = max(0, yB - yA) interArea = interW interH areaA = (boxA.x2 - boxA.x1) (boxA.y2 - boxA.y1) areaB = (boxB.x2 - boxB.x1) * (boxB.y2 - boxB.y1) unionArea = areaA + areaB - interArea if unionArea == 0: return 0.0 return interArea / unionArea
# ---- AP for a single class, given all predictions & ground truths ---- function ComputeAP(predictions, groundTruths, iouThreshold):
# predictions: list of (image_id, box, score)
# groundTruths: dict image_id -> list of boxes (each with a "matched" flag) sort predictions by score descending numGT = total count of ground-truth boxes across all images TP = array of zeros, length = len(predictions) FP = array of zeros, length = len(predictions) for i, (imgId, predBox, score) in enumerate(predictions): candidates = groundTruths[imgId] # only this image's GT boxes bestIoU = 0 bestIdx = -1 for j, gtBox in enumerate(candidates): if gtBox.matched: continue iou = IoU(predBox, gtBox.box) if iou > bestIoU: bestIoU = iou bestIdx = j if bestIoU >= iouThreshold: candidates[bestIdx].matched = true TP[i] = 1 else: FP[i] = 1 cumTP = cumulative_sum(TP) cumFP = cumulative_sum(FP) precision = cumTP / (cumTP + cumFP) # elementwise recall = cumTP / numGT # elementwise return AreaUnderPRCurve(precision, recall)
# ---- 11-point / all-point interpolation of the PR curve ---- function AreaUnderPRCurve(precision, recall):
# Make precision monotonically non-increasing from the right:
# p_interp(r) = max precision at recall >= r for i from len(precision)-2 down to 0: precision[i] = max(precision[i], precision[i+1])
# Integrate via the change in recall (all-point interpolation, PASCAL VOC 2010+ / COCO style) area = 0 prevRecall = 0 for i from 0 to len(precision)-1: area += precision[i] * (recall[i] - prevRecall) prevRecall = recall[i] return area
# ---- mAP over classes (and, for COCO-style, over IoU thresholds) ---- function ComputeMAP(allPredictions, allGroundTruths, classList, iouThresholds): classAPs = [] for c in classList: thresholdAPs = [] for tau in iouThresholds: ap = ComputeAP(allPredictions[c], allGroundTruths[c], tau) thresholdAPs.append(ap) classAPs.append(mean(thresholdAPs)) return mean(classAPs) ``` The precision-monotonizing step deserves emphasis: raw precision is a jagged, non-monotonic function of recall (it can dip and recover as more predictions are added), so both the PASCAL VOC and COCO protocols replace with before integrating, producing a stable, comparable area. COCO's mAP additionally averages over ten IoU thresholds (), rewarding detectors whose boxes are not merely "roughly right" but tightly localized.
Complexity & correctness
Time complexity of one IoU computation. Computing the intersection and union of two axis-aligned boxes involves a constant number of comparisons and arithmetic operations, so it is .
Time complexity of AP computation for one class. With predictions and ground-truth boxes for a class, the naive greedy matcher (as written above) compares each prediction against every ground-truth box in its image. In the worst case (all boxes in one image) this is . Since and are typically at most a few thousand per class per dataset (not per image), this is entirely tractable; restricting the inner loop to ground-truth boxes within the same image (as real implementations do) makes the practical cost far smaller, since per image is usually small (tens of objects). Sorting the predictions costs , which dominates asymptotically. The cumulative-sum and monotonizing passes are .
Time complexity of full mAP. Over classes and IoU thresholds (COCO uses ), total cost is where is now the per-class prediction count — linear-ish in the total number of detections produced, which is exactly the resource budget a detector consumes at inference time, so evaluation never becomes the bottleneck.
Space complexity is per class: one flag per ground-truth box (matched/unmatched) and one score/label pair per prediction. No auxiliary structure grows faster than the input.
Why greedy matching by descending confidence is the correct protocol, not an arbitrary choice. The precision-recall curve is meant to simulate operating the detector at every possible confidence threshold simultaneously: if you deployed the system and only trusted detections above some cutoff, that cutoff corresponds exactly to truncating the sorted list at some rank . Matching greedily in this order guarantees that TP/FP counts at rank equal exactly the TP/FP counts you would get by literally thresholding the detector at that confidence value. Matching in a different order (e.g., by IoU) would silently change what "operating point" each rank represents, breaking the correspondence to real deployment behavior. The "each ground-truth box may be matched once" rule is what forces detectors to be penalized for duplicate detections — without it, a detector could spam the same object with ten boxes and get ten true positives, which is not the desired incentive; this rule, in fact, is the direct evaluation-side reason Non-Maximum Suppression must exist on the prediction side, since a detector that fails to suppress duplicates will see its extra copies scored as false positives.
Why AP (an integral) rather than a single precision/recall number. A detector's raw output score threshold is a knob a user could set anywhere; a single precision or recall number depends arbitrarily on where that knob sits. AP marginalizes over the entire operating range by integrating precision against recall, giving a threshold-free summary — mathematically, it approximates
which equals the average precision value observed each time recall increases by matching a new ground-truth object, exactly analogous to the area under an ROC curve for binary classification but adapted to the class-imbalanced, ranking-based nature of detection (there is no fixed "negative class count" the way there is in classification, since the number of possible negative boxes in an image is unbounded).
Tradeoffs and honesty about limitations. IoU thresholding is a hard cutoff: a box at IoU scores identically to one at IoU (both FP), while a box at IoU is treated as fully correct — a discontinuity that has motivated softer alternatives (e.g., soft-NMS scoring, GIoU/DIoU losses) used during training even though the evaluation metric remains threshold-based. mAP also treats all classes equally regardless of real-world frequency or safety criticality, which can misrepresent performance on rare-but-important classes (e.g., pedestrians in a street scene dominated by "car" instances) — a known and debated limitation of the metric's design.
Worked example
Consider a single class, "cat," evaluated on a small test set with 3 ground-truth cats total (across two images), and a detector producing 5 predictions, sorted by confidence.
| Rank | Image | Score | Best-match GT | IoU | Verdict | Cum. TP | Cum. FP | Precision | Recall |
|---|---|---|---|---|---|---|---|---|---|
| 1 | img1 | 0.95 | GT-1 | 0.78 | TP | 1 | 0 | 1.00 | 0.333 |
| 2 | img1 | 0.90 | GT-1 (already matched) | 0.40 | FP | 1 | 1 | 0.50 | 0.333 |
| 3 | img2 | 0.85 | GT-2 | 0.61 | TP | 2 | 1 | 0.667 | 0.667 |
| 4 | img2 | 0.70 | GT-3 | 0.20 | FP (below τ=0.5) | 2 | 2 | 0.50 | 0.667 |
| 5 | img1 | 0.60 | none available | — | FP | 2 | 3 | 0.40 | 0.667 |
Walking through the logic: at rank 1, the prediction overlaps GT-1 with IoU , so it's a TP and GT-1 becomes "used." At rank 2, the only candidate in img1 is GT-1 again, but it's already matched, so this prediction has no eligible ground truth to claim (treated as IoU against remaining candidates) — a duplicate detection, correctly punished as FP. Rank 3 matches GT-2 in img2 with IoU , a clean TP. Rank 4 finds GT-3 but with IoU only , so despite being the best available match it is FP — the location is simply too far off. Rank 5 has no unmatched ground truth left in its image, so it is FP by default.
Monotonizing precision (replace each precision value with the max of itself and all precisions at equal-or-higher recall, scanning from the end):
| Recall | Raw precision | Interpolated precision |
|---|---|---|
| 0.333 | 0.50 (min of the two entries at this recall) | 0.667 |
| 0.667 | 0.40 (min of the three entries at this recall) | 0.40 |
Concretely: recall reaches first at rank 1 (precision ) and again at rank 2 (precision ) — we keep track of the precision at the moment recall changes. Recall changes to at rank 1 (precision ), stays there through rank 2, changes to at rank 3 (precision ), stays there through ranks 4-5. The interpolation rule sets precision at recall to wait — carefully: interpolated precision at a recall level is the maximum precision for any recall that level. At recall : candidates are precision values at recall , i.e. , max is . At recall : candidates at recall are , max is .
Integrating:
So . Repeating this whole procedure for every class and averaging gives mAP@0.5; repeating again at and averaging those ten values per class (then across classes) gives the stricter COCO-style mAP@[0.5:0.95], which will always be numerically lower than mAP@0.5 because higher thresholds convert former true positives into false positives.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Allowing one ground-truth box to be matched by multiple predictions | Forgetting to mark GT boxes as "used" after a match | Track a matched-flag per GT box; only the first (highest-confidence) claimant counts as TP |
| Using raw (non-monotonized) precision when integrating the PR curve | Precision is naturally jagged and can rise after dips | Always apply the "max precision at recall ≥ r" interpolation before integrating |
| Comparing mAP numbers computed at different IoU thresholds as if equivalent | mAP@0.5 and mAP@[0.5:0.95] measure very different strictness | Always report the IoU threshold(s) used alongside the mAP number |
| Treating IoU as symmetric-safe for very small objects | A 1-pixel shift on a tiny box collapses IoU dramatically more than on a large box | Use scale-aware analysis or normalized coordinates; consider size-stratified AP (COCO reports AP-small/medium/large) |
| Ignoring class imbalance when computing mAP | Rare classes contribute equally to the mean regardless of test-set frequency | Report per-class AP alongside the mean; consider frequency-weighted variants when relevant |
| Confusing confidence-score threshold with IoU threshold | Both are cutoffs but control different things | Confidence threshold picks which detections to keep; IoU threshold decides whether a kept detection is correct |
Pioneers & history
The modern detection-evaluation protocol crystallized through a sequence of benchmark challenges rather than a single paper, each contributing a piece of the machinery described above.
Origins · 1 minMark Everingham and how this was discovered
Everingham's PASCAL VOC challenge (running annually from 2005 through 2012) established the IoU convention, the greedy-matching protocol, and the 11-point interpolated AP that later evolved into the all-point interpolation used today. The Microsoft COCO benchmark, introduced by Tsung-Yi Lin and collaborators, later tightened the metric by averaging AP over ten IoU thresholds and introducing size-stratified breakdowns, pushing the field toward tighter localization rather than merely "roughly right" boxes — directly foreshadowing the precision demands that motivated architectures built around Anchor Boxes and iterative box refinement in the R-CNN Family.
Origins · 1 minhow this was discovered
Where this matters
Every published object detector — from the original R-CNN to YOLO variants to DETR-style transformer detectors — is compared using exactly the IoU-and-mAP machinery described here; without a shared, precisely defined metric, claims of "state of the art" would be incomparable across papers. Autonomous vehicle perception stacks use IoU thresholds directly at runtime, not just for evaluation: a tracking module decides whether two boxes across consecutive frames refer to the same object using IoU-based association, and safety validation reports frequently cite per-class AP for pedestrians and cyclists as a regulatory-adjacent metric. Medical imaging systems that localize tumors or lesions in radiographs report AP at clinically relevant IoU thresholds, since a "close enough" bounding box may still be clinically meaningless if it misses the lesion's boundary by too much. Retail and industrial inspection systems (shelf-monitoring, defect detection) tune their deployed confidence threshold by inspecting the precision-recall curve directly, picking an operating point suited to whether false positives or false negatives are more costly in that application. Dataset curators and challenge organizers (COCO, Open Images, LVIS, Cityscapes) all publish their official rankings using variants of the mAP protocol built directly from IoU matching, cementing this evaluation framework as the lingua franca of the field.
:::quiz[Why does COCO's mAP@[0.5:0.95] tend to be lower than VOC-style mAP@0.5 for the same detector?]
- COCO uses a smaller test set
- Averaging over stricter IoU thresholds converts many former true positives into false positives ✓
- COCO does not use precision-recall curves
- mAP@[0.5:0.95] only evaluates large objects
Ask the tutor: How would the AP computation change if two predictions tie exactly in confidence score?
Why is IoU used instead of simple pixel distance between box centers?
Pixel distance ignores box size and shape entirely — a small box could sit near a large object's center yet cover almost none of it, or a huge box could enclose everything and score as "close" despite being wildly imprecise. IoU instead measures overlap as a fraction of combined area, so it is automatically scale-invariant: a small object's box and a large object's box are judged on the same relative scale. It also penalizes both under-coverage (predicted box too small) and over-coverage (predicted box too large) symmetrically, since both shrink the intersection relative to the union. This makes IoU sensitive to the actual geometric quality of localization in a way that a single distance number cannot capture, which is why it became the near-universal overlap measure in detection, tracking, and segmentation evaluation alike.
Why choose IoU threshold 0.5 specifically, rather than something stricter or looser?
IoU 0.5 was established as a practical compromise by the PASCAL VOC challenge: it is loose enough to tolerate reasonable annotation noise and minor localization imprecision (since human annotators themselves disagree slightly on exact box boundaries), while still requiring substantial genuine overlap rather than a token box in the right neighborhood. It became a de facto standard because comparability across papers matters enormously, and once adopted widely, changing it would break historical comparisons. Modern benchmarks like COCO address the concern that 0.5 is too lenient by additionally reporting mAP averaged across ten thresholds from 0.5 to 0.95, rewarding detectors that achieve tighter localization without abandoning the original, more forgiving 0.5 threshold as a baseline reference point.
What exactly does "mean" refer to in mean Average Precision?
Average Precision (AP) is computed separately for each object class — it is the area under that class's own precision-recall curve. "Mean Average Precision" then averages these per-class AP values across all classes in the dataset, giving one number that summarizes performance across the entire category set. In COCO-style evaluation there is a second averaging layer: AP is first computed at multiple IoU thresholds per class, averaged across thresholds to get a per-class score, and then averaged across classes to produce the final mAP. Because it is an average of averages, mAP can mask large variance — a detector might excel at common classes and fail badly at rare ones while still reporting a respectable mAP, which is why responsible reporting includes per-class breakdowns alongside the single mAP figure.
How does this evaluation framework relate to anchor boxes and non-maximum suppression, which come later?
The evaluation protocol described here creates the exact incentives that later architectural components are designed to satisfy. Because ground-truth boxes can only be matched once, a detector that emits many overlapping, redundant boxes for the same object will see most of them scored as false positives — this is precisely the problem Non-Maximum Suppression solves at inference time, by pruning duplicate detections before they are even output. Meanwhile, because detectors must propose boxes of many scales and aspect ratios without knowing object counts in advance, Anchor Boxes provide a dense, fixed grid of candidate box shapes that get classified and refined — a design whose success is judged entirely using the IoU-and-mAP machinery introduced in this article.
Can mAP be computed for a detector that also does instance segmentation, not just bounding boxes?
Yes — the same conceptual pipeline applies with IoU redefined over pixel masks instead of rectangular boxes. Mask IoU compares the intersection and union of two binary segmentation masks rather than two axis-aligned rectangles, but the matching, precision-recall curve construction, and AP integration proceed identically. COCO reports both "bounding box AP" and "segmentation mask AP" for models like Mask R-CNN, using the exact same greedy-matching-by-confidence and interpolated-integration logic described here, simply swapping the overlap computation. This illustrates that the framework in this article is really about any region-overlap-based recognition task, not bounding boxes specifically.
Does a higher mAP always mean a strictly better detector for a real application?
Not necessarily — mAP treats every class equally regardless of real-world importance or frequency, and it integrates over the entire precision-recall curve rather than the single operating point a deployed system would actually use. Two detectors with identical mAP can have very different precision-recall tradeoffs at the confidence threshold an engineer would realistically deploy at, and a safety-critical application (e.g., pedestrian detection) may care far more about recall at very high precision than about the overall curve area. mAP is an excellent tool for comparing research systems on a level playing field, but production deployment decisions typically also examine per-class AP, the specific operating point's precision/recall, latency, and failure-mode analysis beyond what a single scalar can convey.