A classifier looks at a street scene and says “car”. Which car? Where? Are there three of them? A detector answers all of that: it returns a box around each object, the class of the object and how sure it is. A car that brakes for a pedestrian needs a box, and not one label per picture.
This lesson teaches the parts that every detector shares: how a box is written, how the overlap of two boxes is measured, how a network predicts a box from a reference box called an anchor, how duplicate boxes are cleaned up, and how the result is scored. How the parts are put into a network (R-CNN, YOLO, SSD, DETR) is the next lesson, P5.12.
What a detector returns
Three tasks on the same picture, in order of difficulty:
- Classification (P4.10): one label for the whole image, “there is a cat”.
- Localization: the image holds one object of a known kind, and the answer is its box.
- Detection: any number of objects of many classes, each with a box.
The output of a detector is a list of detections. Each one is
for example . The score (confidence) is a number between 0 and 1 that says how sure the detector is of this detection. The list has no fixed length: an empty street gives few detections and a crowd gives many, so a detector is not simply a classifier with a bigger output layer. Also, most of a picture is background, and most places a detector looks at hold no object. Training and evaluation have to cope with that.
Boxes: three ways to write the same rectangle
A box is a rectangle with sides parallel to the image edges. Three formats are in use, and mixing them up is a common source of silent bugs. In all of them the image -axis points down: is the top row, and a larger is lower in the picture. So is the top-left corner and the bottom-right one.
- Corners, : the top-left and the bottom-right corner.
- Corner and size, : the top-left corner, the width and the height.
- Centre and size, : the middle of the box, the width and the height.
The box with corners has width and height , so it is in the second format and, with centre , in the third. Back from the centre format, and , and the same for . torchvision.ops.box_convert converts between them and calls them xyxy, xywh and cxcywh.
The numbers can be pixels or normalised: divided by the image width (for and ) or height (for and ), so that they lie between 0 and 1. In an image 200 pixels wide and 100 high, the box has centre , width 80 and height 60, which is normalised. Normalised boxes do not change when the image is resized.
COCO annotation files store in pixels, and YOLO label files the normalised centre format: check a library’s format before feeding it boxes.
Boxes move with their pixels. When augmenting images (P4.18), the boxes must be changed with them. Flip the image left to right: a point at horizontal position goes to , so the box becomes , and the box above, , becomes : the two values swap their roles, and is unchanged. Scaling multiplies every coordinate by the same factor, and a crop shifts the coordinates and cuts boxes at the border.
IoU: how much do two boxes agree?
To compare a predicted box with the true box we want a measure that is 1 for a perfect match, 0 for no overlap, and independent of the picture size. Intersection over union (IoU), also called the Jaccard index, does it:
where is an area, is the intersection area and , are the areas of the two boxes.
The union is not the sum of the two areas, because that counts the shared part twice, so the shared part is subtracted once.
Take and . Each has area . For the intersection, take the larger of the left edges and the smaller of the right edges, and the same for the top and bottom:
so , the union is , and . If the width or the height comes out as zero or negative, the boxes share no area and the intersection is 0, not a negative number.
See it: drag two boxes
Drag a box (or a corner dot to resize it), or use the buttons and the arrow keys. The readout under the picture does the arithmetic above with your numbers.
Things to try:
- Press One inside the other. The small box has area 400 and lies inside (area 1600), so the intersection is 400, the union is 1600 and the IoU is : IoU punishes a box that is much too small. (Partial overlap gives the computed above, and No overlap and Touching edges give 0.)
- Press Shifted by a third. Two boxes, one moved sideways by 16 (a third of the width), have an IoU of exactly .
Why 0.5, and what it does not mean
An IoU of 0.5 is the usual line between “a match” and “a miss”. The PASCAL VOC detection challenge counted a detection as correct at an overlap of 50%, and the COCO benchmark reports the same setting as AP at 0.50. It is a convention, and it is looser than it may look: two equal boxes shifted by a third of their width have an IoU of exactly 0.5 and look visibly off. The COCO headline number averages over stricter thresholds too (see the evaluation section).
Box regression: predict offsets from a reference box
How can a network output a box? Outputting the four numbers directly works poorly: they are large, and their size depends on the picture and on the object. The detectors of this lesson start from a reference box (an anchor, see the next section) and predict a small correction to it.
Write the box as centre and size, , and the anchor as . The ground-truth box is . The four regression targets are
The network outputs four numbers and is trained to match these targets. A box is recovered with , , and . The Faster R-CNN paper (Ren et al., 2015) adopts this parameterisation “following” R-CNN (Girshick et al., 2014), as regression “from an anchor box to a nearby ground-truth box”.
A worked example. The anchor is centred at and is . The ground-truth box has centre , width 50 and height 30. Then
Decoding gives back , , and .
Why this form?
- Dividing by the anchor size makes the targets scale-free: 6 pixels is a large shift for a -pixel anchor and a small one for a -pixel anchor.
- The logarithm keeps the predicted width positive whatever the network outputs, since . It also treats growing and shrinking alike: doubling gives and halving gives .
Faster R-CNN uses a smooth L1 loss on these targets, and only for anchors that are positive (next section), since a background anchor has no object box to move to.
Anchors: guesses laid over the picture
A detector must answer “is there an object here, and what box?” for every place in the picture. The trick of anchor-based detectors is to fix a set of candidate boxes in advance, the anchors, and turn the problem into two questions per anchor: “is an object here?” and “how should this anchor be corrected?”.
Anchors come from the feature map of the CNN (P5.4, P5.6). Each cell of the feature map corresponds to a patch of the image, and at every cell the same set of anchors is centred. In Faster R-CNN (Ren et al., 2015) the set is 3 sizes times 3 aspect ratios: box areas of , and pixels, and aspect ratios 1:1, 1:2 and 2:1, so anchors per cell. For the area , the three shapes are , about and (width times height; the area stays and the ratio is height over width). For a feature map of cells, which is about the size the paper mentions, the layer has anchors.
Which anchors are positive?
For training, every anchor needs a label, and the label comes from the IoU with the ground-truth boxes. Faster R-CNN’s rule for its region proposal network:
- Positive if its IoU with some ground-truth box is above 0.7, or if it is the anchor with the highest IoU for some ground-truth box (this second rule rescues an object that no anchor overlaps by 0.7).
- Negative if its IoU is below 0.3 for all ground-truth boxes.
- Ignored otherwise. These anchors do not contribute to the training loss.
An example with one ground-truth box , which is :
- Anchor centred at : IoU , positive.
- Anchor at the same centre: IoU , positive.
- Anchor centred at (15 pixels to the right): IoU , ignored.
- Anchor at (inside the box): IoU , ignored.
- Anchor at (the box inside it): IoU , negative.
- Anchor centred at : IoU , negative.
Of these, only the positive anchors learn a box: their targets are computed against that ground-truth box. A single object gets several positive anchors, and that is one reason for the duplicates that NMS removes later.
Almost every anchor is negative, so training on all of them would teach the network to say “background” always. Faster R-CNN samples 256 anchors per image for the loss, with up to half of them positive (P5.12 covers other ways to handle the imbalance).
Scores, and a first clean-up
Every predicted box carries a score, usually a probability from a sigmoid or softmax (P3.A7, P3.A8) that the box holds an object of that class. A score is a ranking tool, not automatically a calibrated probability (P3.A10).
A score threshold drops boxes the detector hardly believes in. For a display it is set high, to keep the picture clean, and for the evaluation it is set low, because the evaluation below needs the low-scoring boxes too (the torchvision implementation of Faster R-CNN defaults to 0.05). Then non-maximum suppression removes duplicates.
Non-maximum suppression: one box per object
A detector fires several times around one object: the anchors near it are all positive, and each predicts a slightly different box with a high score. Non-maximum suppression (NMS) keeps the best and discards the others. The greedy algorithm:
- Sort the boxes by score, highest first.
- Keep the first box. Remove every remaining box whose IoU with it is above a threshold (0.5 is a common default).
- Take the highest-scoring box that is left, and repeat step 2, until no box is left.
A box that is already removed removes nothing. The threshold decides how much overlap counts as “the same object”: a low one removes aggressively, and a high one lets near-duplicates through.
Per class, or all classes together
A person on a bicycle has two boxes that overlap a lot and are both right. Per-class NMS therefore runs the algorithm separately for each class. Class-agnostic NMS mixes all the boxes in one list: it gives one label per place, and it can remove a correct box of another class.
See it: step through NMS
The picture has four drawn objects, two squares and two circles, and twelve scored boxes, numbered by score (1 is the highest). A box of the circle class is blue, and a box of the square class is pink. Press Next step to go through the algorithm: first the best box is kept, then everything that overlaps it too much is removed, and so on.
Things to try:
- Keep Per class and threshold , and press Run to the end. Seven boxes are kept: the four objects (boxes 1, 2, 3 and 5) and three false boxes (10, 11 and 12). Box 4 (square, 0.81) overlaps box 1 with an IoU of 0.78 and is removed. Switch to All classes together: six boxes remain, because box 10, a square-class box on top of the circle (IoU 0.90 with box 3), is removed when the classes are mixed.
- Lower the threshold to with Per class. Box 5 (the second circle, score 0.79) is removed, because it overlaps box 3 (the first circle) with an IoU of 0.42. Box 8, another box on the second circle, survives for now (its IoU with box 3 is 0.34). At box 8 goes too: the second circle has no box left. That is a real object lost, and it is how NMS fails on crowds.
- Set the threshold to with All classes together. Box 3 (a circle) is removed by box 1 (a square), because the two boxes overlap with an IoU of 0.29, and the other boxes on the first circle (6 and 10) go the same way: a real object is lost to a box of another class.
Go deeper Soft-NMS: lower the score instead of removing
The failure on crowds comes from the hard decision. Bodla, Singh, Chellappa and Davis proposed Soft-NMS (ICCV 2017): a box that overlaps the kept box gets its score decayed as a continuous function of the overlap, so no box is eliminated outright. They report better COCO-style mAP on PASCAL VOC and MS-COCO from this change alone. Some detectors avoid NMS altogether by being trained to produce one box per object (P5.12).
Evaluating a detector
A detection has a box, a class and a score, so “is it correct?” needs a rule. AP pools the detections of one class over the whole test set. Sort them from the highest score down and go through them in that order, each matched against the ground-truth boxes of its own image. The PASCAL VOC rule is:
- A detection is a true positive (TP) if its highest-IoU ground-truth box of the same class has an IoU of at least 0.5 (the devkit text says “exceeds”; the edge case rarely matters) and has not been matched yet. Each ground-truth box can be matched once.
- Otherwise it is a false positive (FP), including a second detection of an object that is already matched: the PASCAL VOC development kit counts five detections of one object as one correct detection and four false ones.
- A ground-truth box with no detection is a false negative (FN).
COCO’s rule is close: it matches each detection to the best ground-truth box that is still free, and it has special handling for crowd regions.
Precision and recall are the quantities of P3.A9: and , where TPFN is the number of ground-truth boxes. Go down the ranked list and compute both after every detection.
An example. One class, four ground-truth objects, six detections, matched at IoU 0.5 (the code below runs it from the boxes):
| Rank | Score | Hit | Prec. | Recall |
|---|---|---|---|---|
| 1 | 0.95 | TP | 1 | 0.25 |
| 2 | 0.90 | FP | 0.5 | 0.25 |
| 3 | 0.80 | TP | 0.667 | 0.5 |
| 4 | 0.70 | TP | 0.75 | 0.75 |
| 5 | 0.60 | FP | 0.6 | 0.75 |
| 6 | 0.40 | FP | 0.5 | 0.75 |
Rank 2 is a second box on the object found at rank 1, rank 5 is badly placed and rank 6 sits on no object. The fourth object is never found, so the recall stops at 0.75. The points (recall, precision) trace the precision-recall curve, and average precision (AP) is the area under it. For detection the curve is first made non-increasing: the precision at recall is replaced by the largest precision at any recall , which removes the zigzag. The precision is then 1 up to a recall of , and from there to , so
Mean average precision (mAP) is the mean of the APs over the classes: two classes with APs and give . A perfect detector has an AP of 1, and one that finds nothing has 0.
The two conventions you will meet
- PASCAL VOC: IoU threshold 0.5. Since 2010 the AP is the area under the precision-recall curve with the non-increasing precision, as above. Before 2010 it was the average of the precision sampled at the eleven recall values .
- COCO: the headline AP is averaged over ten IoU thresholds, 0.50, 0.55, …, 0.95, and over all classes. The COCO site makes no distinction between AP and mAP and calls this average the most important metric. “AP at 0.50” is the PASCAL VOC metric. COCO also reports AP for small, medium and large objects, and allows at most 100 detections per image. Averaging rewards tight boxes: loose boxes can give a good AP at 0.5 and a poor COCO AP.
With the six detections above, the AP is at an IoU threshold of 0.5 and also at 0.75, but at 0.9 only the first detection is matched and the AP falls to . Averaged over the ten thresholds it is . When you read “mAP”, check which convention it is: a number at 0.5 and a COCO number are not comparable.
Go deeper Other ways to sample the precision-recall curve
The AP of P3.A9 sums with the raw precision, which gives on the example, against with the non-increasing precision. The pre-2010 VOC rule (eleven recall values) gives , and COCO samples 101 recall values. A number is only comparable with numbers from the same rule.
Three views of the same ideas
Intuition
IoU is two sheets of paper on a table: how much of the covered table is covered twice. NMS is a crowd of people all pointing at the same bird: the most confident person stays, everyone pointing at almost the same place sits down, and the next most confident person goes on. An anchor is a template held up to the picture: “is something shaped like this here, and how should I stretch and slide it?”
The pictures break: two birds that sit close together look like one to the rule “sit down if you point at nearly the same place”, and one of them is lost.
Math
Average precision. With the detections sorted by score, and the cumulative counts, and ground-truth boxes: , . The envelope is , and
, and the COCO headline number averages over the thresholds .
Code
The helpers of torchvision.ops give the same numbers as the widgets and the from-scratch cells below. The code ran locally with PyTorch 2.9.1 and torchvision 0.24.1, and its output is shown as printed. Boxes are with shape . In the output, indices count from 0, and the widget numbers count from 1.
import torch
from torchvision import ops
# Boxes are (x1, y1, x2, y2) in pixels, shape (N, 4).
a = torch.tensor([[10., 10, 50, 50]])
b = torch.tensor([[30., 10, 70, 50],
[60., 60, 90, 90],
[20., 20, 40, 40]])
print(ops.box_iou(a, b))
box = torch.tensor([[40., 20, 120, 80]])
cxcy = ops.box_convert(box, "xyxy", "cxcywh")
print(cxcy)
print(cxcy / torch.tensor([200., 100, 200, 100]))
print(ops.box_convert(cxcy, "cxcywh", "xyxy"))
# Twelve scored boxes of the lesson's scene
boxes = torch.tensor([
[15, 23, 55, 62], [117, 30, 150, 63], [35, 19, 75, 58],
[12, 20, 52, 61], [45, 27, 85, 66], [32, 15, 72, 56],
[20, 28, 58, 66], [48, 30, 86, 68], [112, 34, 148, 66],
[36, 20, 74, 59], [95, 60, 125, 92], [80, 8, 110, 30]]).float()
scores = torch.tensor([.92, .90, .88, .81, .79, .67,
.58, .52, .46, .35, .31, .22])
labels = torch.tensor([1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1])
keep = ops.nms(boxes, scores, 0.5)
print("all classes:", sorted(keep.tolist()))
keep = ops.batched_nms(boxes, scores, labels, 0.5)
print("per class: ", sorted(keep.tolist()))
keep = ops.batched_nms(boxes, scores, labels, 0.3)
print("per class, 0.3:", sorted(keep.tolist()))Output:
tensor([[0.3333, 0.0000, 0.2500]])
tensor([[80., 50., 80., 60.]])
tensor([[0.4000, 0.5000, 0.4000, 0.6000]])
tensor([[ 40., 20., 120., 80.]])
all classes: [0, 1, 2, 4, 10, 11]
per class: [0, 1, 2, 4, 9, 10, 11]
per class, 0.3: [0, 1, 2, 9, 10, 11]ops.box_iou(a, b) returns the IoU of every box of a with every box of b, here , 0 and . ops.batched_nms takes a class label per box and never compares boxes of different labels, which is per-class NMS. The two lists at threshold 0.5 differ by index 9, the square-class box on top of the first circle.
Try it in Python
The two cells need only NumPy: NMS from scratch on the twelve boxes of the widget, and the matching of detections with the average precision.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The cell prints the kept indices of the widget at three settings. Try other thresholds and compare with the widget (add 1 to each index).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The cell prints the true positives (1 marks one), the precision and recall after each detection, an AP of at 0.5, and averaged over the ten thresholds. Move a detection by a few pixels and see which thresholds it breaks.
Common mistakes
Quiz
Check your understanding
In the Faster R-CNN labelling rule, an anchor has an IoU of 0.45 with its best ground-truth box, and it is not the best anchor for any box. What label does it get?
Anchors above 0.7 (or the best one per box) are positive, anchors below 0.3 for all boxes are negative, and everything in between is ignored and gives no loss. The option with 0.5 uses the evaluation threshold, which is not the rule for anchors. The option with “overlaps an object” would make nearly every anchor positive. The option about the best anchor invents a rule: being the best anchor for a box makes an anchor positive, and not being it does not make an anchor negative.
An anchor is 40 pixels wide, and the ground-truth box has the same centre and is 80 pixels wide. What is the width target ?
The width target is the logarithm of the ratio of widths, . The value 1 applies the centre-style formula, which divides a difference by the anchor size, to the width. The value 40 is the difference in pixels, which has no scale-free meaning. The value 2 is the ratio itself, without the logarithm.
Two real objects of one class have predicted boxes with an IoU of 0.6. Per-class NMS runs with a threshold of 0.5. What happens?
NMS keeps the better box and removes every box whose IoU with it is above the threshold, so one real object is lost. NMS cannot see that the boxes belong to different objects, so the option that keeps both is wrong. The highest-scored box of a group is always kept, so the option that removes both boxes and the option that removes the higher-scored one are wrong.
Exercises
- A image (width times height) has a box with corners . Give the box in centre format, in normalised centre format, and after a left-to-right flip of the image (in corner format).
Show answer
The centre is , the width 120 and the height 80, so . Normalised: divide the values by 300 and the values by 200, which gives , , and . After the flip the new corners are : is unchanged, and the two values swap roles. - Four ground-truth objects and four detections, from the highest score, are TP, TP, FP, TP. Compute the precision and recall after each detection and the average precision with the non-increasing precision.
Show answer
After the four detections: precision and recall . The precision made non-increasing: . The recall rises by at ranks 1, 2 and 4, with the precisions , and , so . The raw sum of P3.A9 would use at rank 4 as well, so here the two agree; they differ only when the precision rises after a dip. - Four boxes have scores , , , , numbered 1 to 4. The IoUs of the pairs are: , , , , and every other pair is 0. Run NMS with threshold 0.5.
Show answer
Keep box 1. Box 2 has an IoU of 0.6 with it and is removed, box 3 (0.2) and box 4 (0) stay. The next box is 3, which is kept. Box 4 has an IoU of 0.7 with it and is removed. The result is boxes 1 and 3. The pair with 0.55 plays no role, because box 2 was already removed and a removed box removes nothing.
Next: P5.12 puts these parts into detectors, the R-CNN family, YOLO, SSD and DETR, and shows where each of them places the anchors, the matching and the NMS step.