Level 3 In-Depth AI · Vision, Audio and Multimodal
Object Detection
Find every object in an image, draw a box around it and name it. This chapter covers bounding boxes, IoU, non-maximum suppression, the two-stage (R-CNN) and one-stage (YOLO) detector families, DETR, and how detectors are scored with mAP.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 18 concepts →
- Quiz
- 5 questions ↓
Read first
Image ClassificationThe full path from zero — 18 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- Image Classification
- Object Detection
Read them roughly in this order. See it on the concept map →
Why it matters
Classification answers "what is in this picture?" with one label. Most real tasks need more: where is each pedestrian, how many cars are there, which shelf has an empty slot? Object detection finds every object of interest, draws a bounding box around each one and labels it with a class and a confidence score.
Detectors drive self-driving and driver-assistance systems (cars, cyclists, traffic lights), count people and vehicles in traffic cameras, spot defects on production lines, track players in sports broadcasts, find tumours in scans and power face detection in every phone camera. They are also a building block for instance segmentation, for reading text (first find the text lines) and for video tracking.
The intuition
Imagine checking a crowded photo for cats by hand. You could slide a small cardboard window over every position and size, and at each spot ask a cat classifier "is there a cat in this window?" That is how detection was done before deep learning, and it works, but it is extremely slow. A 640 × 480 image has hundreds of thousands of possible windows.
Modern detectors are clever versions of the same idea. A CNN backbone computes features for the whole image once. Then, from those shared features, a light detection head predicts at many locations at the same time: is an object centred near here, what class is it, and how should a box be stretched to fit it? That produces many overlapping candidate boxes. A final clean-up step, non-maximum suppression, keeps the best box for each object and discards the duplicates.
Two simple measurements tie it all together. Intersection over union (IoU) scores how well two boxes overlap, and mean average precision (mAP) scores a whole detector.
Key idea A detector = backbone + head that predicts, at many places at once, a class score and a box. Many overlapping boxes come out. Non-maximum suppression keeps one per object, IoU measures box overlap, and mAP grades the detector.
How it works
Describing a box
A bounding box is four numbers. Formats differ, which is a common source of bugs:
- Corners
(x1, y1, x2, y2): top-left and bottom-right, in pixels. torchvision uses this. - COCO
(x, y, w, h): top-left corner plus width and height. - YOLO
(cx, cy, w, h): centre, width and height, all divided by the image size so they lie between 0 and 1.
Remember from Images as Data that grows downwards from the top of the image.
Intersection over union
IoU compares a predicted box with a ground-truth box :
The means "overlap of" and means "combined region of". IoU is 1 for a perfect match and 0 for no overlap. The overlap rectangle runs from the larger of the two left edges to the smaller of the two right edges, and likewise vertically. If those cross, the overlap is empty. The union is the two areas added together minus the overlap, which would otherwise be counted twice.
Worked example (the figure above). and . The overlap runs from to (width 50) and from to (height 80), so it covers 4,000 px². Each box has area 10,000, so the union is , and IoU = 0.25. That is not good enough: a prediction typically needs IoU ≥ 0.5 with a true box to count as a hit.
Non-maximum suppression
A detector fires many times around each object, because neighbouring locations all see the same cat. Non-maximum suppression (NMS) removes the duplicates:
- Sort all boxes of a class by confidence score.
- Keep the highest-scoring box.
- Delete every remaining box whose IoU with it is above a threshold, typically 0.5.
- Repeat with the highest remaining box until none are left.
The threshold is a trade-off. Too low, and two genuinely overlapping objects (people in a crowd) get merged into one. Too high, and duplicates survive.
Two-stage detectors: the R-CNN family
- R-CNN (2013) used a classical algorithm to propose about 2,000 candidate regions, cropped each one, ran a CNN on each crop and classified it. It was accurate, but took many seconds per image because the CNN ran 2,000 times.
- Fast R-CNN (2015) ran the CNN once over the whole image and cut each region's features out of the shared feature map (RoI pooling).
- Faster R-CNN (2015) replaced the hand-made proposals with a learned region proposal network (RPN). At each position of the feature map it considers a set of anchor boxes, fixed reference boxes of several sizes and shapes (9 per position in the paper: 3 scales × 3 aspect ratios). For each anchor it predicts "object or not?" and how to shift and stretch the anchor to fit. The best few hundred proposals go to a second stage, which classifies them and refines their boxes. It ran at about 5 images per second on a GPU.
These are two-stage detectors: first propose regions, then classify them. They are accurate and flexible. Mask R-CNN (2017) adds a mask branch for Image Segmentation.
One-stage detectors: YOLO and friends
YOLO ("You Only Look Once", 2015) skipped the proposal stage. It divided the image into a 7 × 7 grid, and each cell directly predicted a couple of boxes, their confidences and class probabilities, in a single pass of one network. It ran at 45 images per second, real time for video, at some cost in accuracy, especially for small objects. SSD (2016) predicted from several feature maps of different resolutions to handle different sizes.
One-stage detectors have a problem: of the tens of thousands of candidate locations, almost all are background. Easy background examples swamp the loss. RetinaNet (2017) fixed this with the focal loss, which down-weights examples the model already gets right. It also used a feature pyramid network (FPN), which combines coarse, semantic deep features with fine, detailed shallow ones so that small and large objects are both found. Later one-stage designs (FCOS, CenterNet and recent YOLO versions) went anchor-free, predicting box edges directly from each location.
YOLO grew into a large family of descendants from several groups, many released through the Ultralytics library (YOLOv5, YOLOv8, YOLO11 and, since January 2026, YOLO26, which drops NMS at inference). They are the usual choice when you need fast detection on modest hardware.
Predicting boxes
Detectors rarely output raw pixel coordinates. They predict offsets from a reference box (an anchor, or a grid location) with centre and size :
Here is the true box's centre and size. Dividing by the anchor's size makes the targets similar for big and small objects, and the log makes "twice as wide" and "half as wide" symmetric. Training adds a box-regression loss on these numbers (smooth L1, or an IoU-based loss such as GIoU) to the usual classification cross-entropy.
DETR: detection as set prediction
DETR (2020) threw away anchors and NMS. A CNN backbone feeds a The Transformer encoder–decoder. The decoder starts from a fixed set of learned object queries (100 in the paper), and each query outputs one box and class, or "no object". During training, each true object is matched to exactly one query using the Hungarian algorithm (an optimal one-to-one assignment), so the model learns not to produce duplicates. The idea is elegant, but the original converged slowly. Successors such as Deformable DETR, DINO-DETR and RT-DETR (real-time) fixed much of that.
Open-vocabulary detection
Classic detectors know only their training classes, such as COCO's 80. Open-vocabulary detectors such as OWL-ViT and Grounding DINO take a text prompt ("red backpack", "forklift") and find matching objects, by combining detection with image–text embeddings. Multimodal LLMs can increasingly output boxes too.
Scoring a detector: mean average precision
For one class, sort all predictions on the test set by confidence. Walk down the list. A prediction is a true positive if it overlaps an as-yet-unmatched true box with IoU ≥ 0.5, and a false positive otherwise. After each prediction, compute precision and recall. The area under the resulting precision–recall curve is the average precision (AP) for that class. Mean average precision (mAP) averages AP over classes.
Worked example. There are 4 cats in the test images and 5 predictions, sorted by confidence, which turn out TP, TP, FP, TP, FP:
| Rank | Result | Precision | Recall |
|---|---|---|---|
| 1 | TP | 1/1 = 1.00 | 1/4 = 0.25 |
| 2 | TP | 2/2 = 1.00 | 2/4 = 0.50 |
| 3 | FP | 2/3 = 0.67 | 0.50 |
| 4 | TP | 3/4 = 0.75 | 3/4 = 0.75 |
| 5 | FP | 3/5 = 0.60 | 0.75 |
Using the usual rule of taking, at each recall level, the best precision achieved at that recall or beyond: recall 0 to 0.25 has precision 1, 0.25 to 0.5 has 1, 0.5 to 0.75 has 0.75, and recall never reaches 1 (one cat was never found). AP = .
PASCAL VOC reports mAP at IoU 0.5 ("AP50"). The stricter COCO mAP averages over ten IoU thresholds from 0.50 to 0.95, so it rewards precise boxes. It is the headline number in most papers. COCO itself has 80 everyday object categories and about 118,000 training images.
In code
IoU and NMS from scratch in NumPy, on the five boxes from the figure:
import numpy as np
def iou(box, boxes):
"""IoU of one box against many. Boxes are [x1, y1, x2, y2] in pixels."""
x1 = np.maximum(box[0], boxes[:, 0])
y1 = np.maximum(box[1], boxes[:, 1])
x2 = np.minimum(box[2], boxes[:, 2])
y2 = np.minimum(box[3], boxes[:, 3])
inter = np.clip(x2 - x1, 0, None) * np.clip(y2 - y1, 0, None)
area = lambda b: (b[..., 2] - b[..., 0]) * (b[..., 3] - b[..., 1])
return inter / (area(box) + area(boxes) - inter)
def nms(boxes, scores, iou_threshold=0.5):
"""Keep the best box, drop boxes that overlap it too much, repeat."""
order = np.argsort(scores)[::-1] # highest score first
keep = []
while len(order) > 0:
best = order[0]
keep.append(int(best))
overlaps = iou(boxes[best], boxes[order[1:]])
order = order[1:][overlaps < iou_threshold]
return keep
print(iou(np.array([40, 40, 140, 140]), np.array([[90, 60, 190, 160]]))) # [0.25]
# Five raw detections around two cats
boxes = np.array([[ 50, 60, 210, 230], # 0: cat 1
[ 60, 50, 220, 220], # 1: cat 1, shifted
[ 40, 80, 190, 240], # 2: cat 1, shifted
[300, 90, 450, 250], # 3: cat 2
[310, 110, 470, 260]]) # 4: cat 2, shifted
scores = np.array([0.92, 0.85, 0.60, 0.88, 0.70])
print(iou(boxes[0], boxes).round(2)) # [1. 0.79 0.7 0. 0. ]
print("kept:", nms(boxes, scores)) # kept: [0, 3]
torchvision has fast versions (torchvision.ops.box_iou, torchvision.ops.nms) and pretrained detectors. A Faster R-CNN trained on COCO, applied to any photo street.jpg:
import torch
from torchvision.io import read_image
from torchvision.models.detection import (fasterrcnn_resnet50_fpn_v2,
FasterRCNN_ResNet50_FPN_V2_Weights)
weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
model = fasterrcnn_resnet50_fpn_v2(weights=weights, box_score_thresh=0.5).eval()
preprocess = weights.transforms()
img = read_image("street.jpg") # uint8 tensor (3, H, W)
with torch.no_grad():
pred = model([preprocess(img)])[0] # dict with boxes, labels, scores
for box, label, score in zip(pred["boxes"], pred["labels"], pred["scores"]):
print(weights.meta["categories"][label], f"{score:.2f}", box.round().tolist())
The same with a small, fast YOLO model from the ultralytics package:
from ultralytics import YOLO
model = YOLO("yolo26n.pt") # nano model, downloads on first use
result = model("street.jpg")[0]
for cls, conf, xyxy in zip(result.boxes.cls, result.boxes.conf, result.boxes.xyxy):
print(model.names[int(cls)], f"{conf:.2f}", xyxy.round().tolist())
Common pitfalls
- Mixed-up box formats.
(x, y, w, h)read as(x1, y1, x2, y2)gives boxes that are subtly or wildly wrong. Draw your ground-truth boxes on a few images before training anything. - Forgetting to transform boxes with the image. Every resize, crop and flip in Data Augmentation must be applied to the boxes too.
- Small objects. Objects a few pixels wide disappear in a downsampled feature map. Use higher input resolution, a feature pyramid, or tiling (cutting a large image into overlapping tiles).
- The confidence threshold. Boxes below the score threshold are hidden. A threshold tuned on the validation set for your precision/recall needs matters more than another point of mAP.
- Comparing mAP numbers loosely. AP50 and COCO mAP (0.50–0.95) differ a lot for the same model. So do results at different input sizes.
- Crowds and NMS. In dense scenes, NMS can delete correct boxes on people standing close together. Consider a higher IoU threshold, Soft-NMS, or an NMS-free DETR-style model.
- Label quality. Inconsistent boxes (tight in some images, loose in others), or objects left unlabelled, cap your accuracy and confuse the metrics. A model is "wrong" every time it finds an object the labeller missed.
Watch out A detector that is 95% accurate in your test set can still miss exactly the cases that matter, such as a child partly hidden behind a car, at night. For safety-relevant uses, measure recall separately for small, occluded and rare objects and in poor conditions, not just the overall mAP.
Where it leads
- Image Segmentation goes from boxes to exact pixel outlines. Mask R-CNN is Faster R-CNN plus a mask branch.
- OCR begins by detecting text regions, and layout analysis detects tables, figures and paragraphs.
- Video Understanding links detections across frames to track objects over time.
- Vision Transformers serve as backbones for DETR-style detectors.
- CLIP and Contrastive Learning and Multimodal LLMs make detection open-vocabulary: describe what to look for in words.
A bit of history
The first widely deployed detector was the Viola–Jones face detector (2001). It used simple rectangle features and a cascade of quick classifiers, fast enough to run in early digital cameras. In 2005, HOG features (histograms of oriented gradients) with a linear SVM made pedestrian detection practical, and "deformable part models" led the PASCAL VOC benchmark in the late 2000s.
Ross Girshick and colleagues' R-CNN (2013) brought CNN features to detection and improved the best previous mAP on PASCAL VOC 2012 by more than 30% in relative terms. Fast and Faster R-CNN followed in 2015, as did Joseph Redmon's YOLO. COCO (2014) became the standard benchmark. FPN and RetinaNet came in 2017, and DETR in 2020 showed that a Transformer could do the whole job end to end. Since then the field has moved towards Transformer-based and open-vocabulary detectors, while YOLO-style models dominate fast, practical deployment.
Try it
- Compute by hand the IoU of
(0, 0, 10, 10)and(5, 5, 15, 15). Check with theioufunction.- Run
nmswithiou_threshold=0.75. Which boxes survive now, and why?- Harder: write a function
average_precision(is_tp, n_true)that takes a list of True/False values (sorted by confidence) and the number of true objects, and returns AP as in the worked example. Check that it gives 0.6875 for[True, True, False, True, False]and 4.Hint for 2: box 1 has IoU 0.79 with box 0, so it is still removed, but box 2 (IoU 0.70) is now kept. Look at box 4 against box 3 too.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks
Introduced anchors and the region proposal network, making two-stage detection fast and fully learned. Still a standard baseline.
You Only Look Once: Unified, Real-Time Object Detection
Object detection as a single fast regression problem.
End-to-End Object Detection with Transformers
DETR treats detection as predicting a set of boxes with a Transformer and bipartite matching, removing anchors and non-maximum suppression.
Microsoft COCO: Common Objects in Context
The COCO dataset paper. COCO's 80 object categories and its mAP metric became the standard benchmark for detection and segmentation.
TorchVision Object Detection Finetuning Tutorial
Fine-tunes a pretrained Mask R-CNN on a small pedestrian dataset, covering the dataset format for boxes and masks, training and evaluation.
Ultralytics YOLO documentation
Docs for the popular ultralytics Python package, which trains and runs YOLO models for detection, segmentation, pose and tracking in a few lines.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/object-detection.md