Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Object detection basics

P5.1145 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A classifier says what is in a picture. A detector also says where, for every object at once, and the same few tools (boxes, IoU, anchors, NMS and average precision) sit inside most detectors and detection benchmarks.

Before this: The convolution operation, Pooling and receptive fields, Evaluation metrics

After this lesson you can

  • Say what a detector outputs and convert a box between the three formats, in pixels and normalised
  • Compute the IoU of two boxes by hand, edge cases included, and say why 0.5 is a common threshold
  • Compute box regression targets from an anchor, and label anchors positive, negative or ignored
  • Run greedy NMS by hand and say what the threshold, the per-class form and crowds change
  • Compute precision, recall and average precision from a ranked list, and tell the VOC and COCO mAP apart

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

(box, class, score),(\text{box},\ \text{class},\ \text{score}),

for example ((40,20,120,80), dog, 0.91)((40,20,120,80),\ \text{dog},\ 0.91). 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 yy-axis points down: y=0y=0 is the top row, and a larger yy is lower in the picture. So (x1,y1)(x_1,y_1) is the top-left corner and (x2,y2)(x_2,y_2) the bottom-right one.

  • Corners, (x1,y1,x2,y2)(x_1,y_1,x_2,y_2): the top-left and the bottom-right corner.
  • Corner and size, (x,y,w,h)(x,y,w,h): the top-left corner, the width and the height.
  • Centre and size, (cx,cy,w,h)(c_x,c_y,w,h): the middle of the box, the width and the height.

The box with corners (10,10,50,50)(10,10,50,50) has width and height 4040, so it is (10,10,40,40)(10,10,40,40) in the second format and, with centre (30,30)(30,30), (30,30,40,40)(30,30,40,40) in the third. Back from the centre format, x1=cx−w/2x_1=c_x-w/2 and x2=cx+w/2x_2=c_x+w/2, and the same for yy. 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 xx and ww) or height (for yy and hh), so that they lie between 0 and 1. In an image 200 pixels wide and 100 high, the box (40,20,120,80)(40,20,120,80) has centre (80,50)(80,50), width 80 and height 60, which is (0.4, 0.5, 0.4, 0.6)(0.4,\,0.5,\,0.4,\,0.6) normalised. Normalised boxes do not change when the image is resized.

COCO annotation files store (x,y,w,h)(x,y,w,h) 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 200×100200\times100 image left to right: a point at horizontal position xx goes to 200−x200-x, so the box (x1,x2)(x_1,x_2) becomes (200−x2, 200−x1)(200-x_2,\,200-x_1), and the box above, (40,20,120,80)(40,20,120,80), becomes (80,20,160,80)(80,20,160,80): the two xx values swap their roles, and yy 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:

IoU(A,B)=∣A∩B∣∣A∪B∣=IaA+aB−I,\begin{aligned} \text{IoU}(A,B)&=\frac{\lvert A\cap B\rvert}{\lvert A\cup B\rvert}\\[4pt] &=\frac{I}{a_A+a_B-I}, \end{aligned}

where ∣⋅∣\lvert\cdot\rvert is an area, II is the intersection area and aAa_A, aBa_B 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 A=(10,10,50,50)A=(10,10,50,50) and B=(30,10,70,50)B=(30,10,70,50). Each has area 40⋅40=160040\cdot40=1600. 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:

width=min⁡(50,70)−max⁡(10,30)=20,height=min⁡(50,50)−max⁡(10,10)=40,\begin{aligned} \text{width}&=\min(50,70)-\max(10,30)\\ &=20,\\ \text{height}&=\min(50,50)-\max(10,10)\\ &=40, \end{aligned}

so I=20⋅40=800I=20\cdot40=800, the union is 1600+1600−800=24001600+1600-800=2400, and IoU=800/2400=1/3\text{IoU}=800/2400=1/3. 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.

002020404060608080100100AB

Move box A: drag it, drag a corner dot, or use the arrows (on the keyboard, Shift makes steps of 5; the keys A and B pick the box). The x axis points right and the y axis points down.

  • A = (10, 10, 50, 50), area = 40 × 40 = 1600
  • B = (30, 10, 70, 50), area = 40 × 40 = 1600
  • Intersection: width = min(50, 70) − max(10, 30) = 20, height = min(50, 50) − max(10, 10) = 40, so area = 20 × 40 = 800
  • Union = 1600 + 1600 − 800 = 2400
  • IoU = 800 / 2400 = 0.333 (below 0.5: not a match at the common threshold)
IoU calculator on a 100 by 100 picture. Box A is blue and solid, box B is pink and dashed, and the green area is their intersection. Drag a box or a corner dot, or use the buttons and arrow keys. The readout shows the areas, the intersection, the union and the IoU. Nothing animates, so Lite Mode shows the same.

Things to try:

  1. Press One inside the other. The small box (20,20,40,40)(20,20,40,40) has area 400 and lies inside AA (area 1600), so the intersection is 400, the union is 1600 and the IoU is 0.250.25: IoU punishes a box that is much too small. (Partial overlap gives the 1/31/3 computed above, and No overlap and Touching edges give 0.)
  2. Press Shifted by a third. Two 48×4848\times48 boxes, one moved sideways by 16 (a third of the width), have an IoU of exactly 0.50.5.

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 (x1,y1,x2,y2)(x_1,y_1,x_2,y_2) 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, (x,y,w,h)(x,y,w,h), and the anchor as (xa,ya,wa,ha)(x_a,y_a,w_a,h_a). The ground-truth box is (x∗,y∗,w∗,h∗)(x^*,y^*,w^*,h^*). The four regression targets are

tx=x∗−xawa,ty=y∗−yaha,tw=ln⁡w∗wa,th=ln⁡h∗ha.\begin{aligned} t_x&=\frac{x^*-x_a}{w_a},\\[4pt] t_y&=\frac{y^*-y_a}{h_a},\\[4pt] t_w&=\ln\frac{w^*}{w_a},\\[4pt] t_h&=\ln\frac{h^*}{h_a}. \end{aligned}

The network outputs four numbers (tx,ty,tw,th)(t_x,t_y,t_w,t_h) and is trained to match these targets. A box is recovered with x=xa+txwax=x_a+t_xw_a, y=ya+tyhay=y_a+t_yh_a, w=waetww=w_a e^{t_w} and h=haethh=h_a e^{t_h}. 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 (50,50)(50,50) and is 40×4040\times40. The ground-truth box has centre (56,47)(56,47), width 50 and height 30. Then

tx=56−5040=0.15,ty=47−5040=−0.075,tw=ln⁡5040=0.223,th=ln⁡3040=−0.288.\begin{aligned} t_x&=\frac{56-50}{40}=0.15,\\[4pt] t_y&=\frac{47-50}{40}=-0.075,\\[4pt] t_w&=\ln\frac{50}{40}=0.223,\\[4pt] t_h&=\ln\frac{30}{40}=-0.288. \end{aligned}

Decoding gives back x=50+0.15⋅40=56x=50+0.15\cdot40=56, y=50−0.075⋅40=47y=50-0.075\cdot40=47, w=40e0.223=50w=40e^{0.223}=50 and h=40e−0.288=30h=40e^{-0.288}=30.

Why this form?

  • Dividing by the anchor size makes the targets scale-free: 6 pixels is a large shift for a 4040-pixel anchor and a small one for a 400400-pixel anchor.
  • The logarithm keeps the predicted width positive whatever the network outputs, since etw>0e^{t_w}>0. It also treats growing and shrinking alike: doubling gives +ln⁡2=+0.69+\ln2=+0.69 and halving gives −0.69-0.69.

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 1282128^2, 2562256^2 and 5122512^2 pixels, and aspect ratios 1:1, 1:2 and 2:1, so k=9k=9 anchors per cell. For the area 1282128^2, the three shapes are 128×128128\times128, about 91×18191\times181 and 181×91181\times91 (width times height; the area stays 16,38416{,}384 and the ratio is height over width). For a feature map of 40×60=240040\times60=2400 cells, which is about the size the paper mentions, the layer has 2400⋅9=21,6002400\cdot9=21{,}600 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 (30,30,90,90)(30,30,90,90), which is 60×6060\times60:

  • Anchor 60×6060\times60 centred at (60,60)(60,60): IoU 1.001.00, positive.
  • Anchor 70×7070\times70 at the same centre: IoU 0.730.73, positive.
  • Anchor 60×6060\times60 centred at (75,60)(75,60) (15 pixels to the right): IoU 0.600.60, ignored.
  • Anchor 40×4040\times40 at (60,60)(60,60) (inside the box): IoU 0.440.44, ignored.
  • Anchor 120×120120\times120 at (60,60)(60,60) (the box inside it): IoU 0.250.25, negative.
  • Anchor 60×6060\times60 centred at (100,100)(100,100): IoU 0.060.06, negative.

Of these, only the positive anchors learn a box: their targets (tx,ty,tw,th)(t_x,t_y,t_w,t_h) 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:

  1. Sort the boxes by score, highest first.
  2. Keep the first box. Remove every remaining box whose IoU with it is above a threshold (0.5 is a common default).
  3. 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.

123456789101112
  • circle class
  • square class
  • ✓ kept
  • ✕ removed

Step 0 of 15. Start: 12 boxes. Per-class NMS handles each class on its own, circles first and then squares, always from the highest score down.

  1. #1 square, score 0.92 waiting
  2. #2 square, score 0.90 waiting
  3. #3 circle, score 0.88 waiting
  4. #4 square, score 0.81 waiting
  5. #5 circle, score 0.79 waiting
  6. #6 circle, score 0.67 waiting
  7. #7 square, score 0.58 waiting
  8. #8 circle, score 0.52 waiting
  9. #9 square, score 0.46 waiting
  10. #10 square, score 0.35 waiting
  11. #11 circle, score 0.31 waiting
  12. #12 square, score 0.22 waiting
NMS step-through on a drawn scene with four objects and twelve scored boxes. Choose per-class or all-class NMS, set the IoU threshold, and press Next step. Kept boxes are thick with a tick, removed boxes are dashed with a cross, and the list shows the IoU of each comparison. The results equal torchvision's nms and batched_nms. Nothing animates, so Lite Mode shows the same.

Things to try:

  1. Keep Per class and threshold 0.500.50, 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.
  2. Lower the threshold to 0.400.40 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 0.300.30 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.
  3. Set the threshold to 0.250.25 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: TP/(TP+FP)\text{TP}/(\text{TP}+\text{FP}) and TP/(TP+FN)\text{TP}/(\text{TP}+\text{FN}), where TP++FN 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):

RankScoreHitPrec.Recall
10.95TP10.25
20.90FP0.50.25
30.80TP0.6670.5
40.70TP0.750.75
50.60FP0.60.75
60.40FP0.50.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 rr is replaced by the largest precision at any recall r′≥rr'\ge r, which removes the zigzag. The precision is then 1 up to a recall of 0.250.25, and 0.750.75 from there to 0.750.75, so

AP=0.25⋅1+0.25⋅0.75+0.25⋅0.75=0.625.\begin{aligned} \text{AP}&=0.25\cdot1+0.25\cdot0.75\\ &\quad+0.25\cdot0.75=0.625. \end{aligned}

Mean average precision (mAP) is the mean of the APs over the classes: two classes with APs 0.6250.625 and 0.50.5 give 0.56250.5625. 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 0,0.1,…,10,0.1,\dots,1.
  • 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 0.6250.625 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 0.250.25. Averaged over the ten thresholds it is 0.50.5. 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 (Rn−Rn−1)Pn(R_n-R_{n-1})P_n with the raw precision, which gives 0.6040.604 on the example, against 0.6250.625 with the non-increasing precision. The pre-2010 VOC rule (eleven recall values) gives 0.6140.614, 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, TPn\text{TP}_n and FPn\text{FP}_n the cumulative counts, and GG ground-truth boxes: Pn=TPn/(TPn+FPn)P_n=\text{TP}_n/(\text{TP}_n+\text{FP}_n), Rn=TPn/GR_n=\text{TP}_n/G. The envelope is P~n=max⁡m≥nPm\tilde P_n=\max_{m\ge n}P_m, and

AP=∑n(Rn−Rn−1) P~n,R0=0,\begin{aligned} \text{AP}&=\sum_n(R_n-R_{n-1})\,\tilde P_n,\\ R_0&=0, \end{aligned}

mAP=1K∑c=1KAPc\text{mAP}=\frac1K\sum_{c=1}^K\text{AP}_c, and the COCO headline number averages mAP\text{mAP} over the thresholds 0.50,0.55,…,0.950.50,0.55,\dots,0.95.

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 (x1,y1,x2,y2)(x_1,y_1,x_2,y_2) with shape (N,4)(N,4). 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 1/31/3, 0 and 0.250.25. 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.

Non-maximum suppression from scratch

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).

Matching detections and average precision

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 0.6250.625 at 0.5, and 0.50.5 averaged over the ten thresholds. Move a detection by a few pixels and see which thresholds it breaks.

Common mistakes

Quiz

Check your understanding

  1. 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?

  2. 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 twt_w?

  3. 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?

Exercises

  1. A 300×200300\times200 image (width times height) has a box with corners (60,40,180,120)(60,40,180,120). Give the box in centre format, in normalised centre format, and after a left-to-right flip of the image (in corner format).
    Show answerThe centre is (120,80)(120,80), the width 120 and the height 80, so (120,80,120,80)(120,80,120,80). Normalised: divide the xx values by 300 and the yy values by 200, which gives 0.40.4, 0.40.4, 0.40.4 and 0.40.4. After the flip the new corners are (300−180, 40, 300−60, 120)=(120,40,240,120)(300-180,\,40,\,300-60,\,120)=(120,40,240,120): yy is unchanged, and the two xx values swap roles.
  2. 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 answerAfter the four detections: precision 1,1,2/3,3/41,1,2/3,3/4 and recall 0.25,0.5,0.5,0.750.25,0.5,0.5,0.75. The precision made non-increasing: 1,1,0.75,0.751,1,0.75,0.75. The recall rises by 0.250.25 at ranks 1, 2 and 4, with the precisions 11, 11 and 0.750.75, so AP=0.25+0.25+0.1875=0.6875\text{AP}=0.25+0.25+0.1875=0.6875. The raw sum of P3.A9 would use 0.750.75 at rank 4 as well, so here the two agree; they differ only when the precision rises after a dip.
  3. Four boxes have scores 0.90.9, 0.80.8, 0.70.7, 0.60.6, numbered 1 to 4. The IoUs of the pairs are: (1,2)=0.6(1,2)=0.6, (1,3)=0.2(1,3)=0.2, (2,3)=0.55(2,3)=0.55, (3,4)=0.7(3,4)=0.7, and every other pair is 0. Run NMS with threshold 0.5.
    Show answerKeep 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 (2,3)(2,3) 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.

Key takeaways

  • A detector returns a variable-length list of detections, each a box, a class and a score. A box is (x1,y1,x2,y2)(x_1,y_1,x_2,y_2), (x,y,w,h)(x,y,w,h) or (cx,cy,w,h)(c_x,c_y,w,h), in pixels or divided by the image size, with the yy-axis pointing down, and boxes change with their image when it is flipped or scaled.
  • IoU=I/(aA+aB−I)\text{IoU}=I/(a_A+a_B-I) is 0 with no overlap and 1 for identical boxes, and does not depend on the scale of the picture. Two equal boxes shifted by a third of their width have an IoU of 0.5, a common match threshold.
  • A detector regresses a box as offsets from an anchor: tx=(x−xa)/wat_x=(x-x_a)/w_a, ty=(y−ya)/hat_y=(y-y_a)/h_a, tw=ln⁡(w/wa)t_w=\ln(w/w_a), th=ln⁡(h/ha)t_h=\ln(h/h_a). In Faster R-CNN an anchor is positive above an IoU of 0.7, negative below 0.3, and ignored between.
  • Greedy NMS keeps the best box, removes the boxes whose IoU with it is above a threshold, and repeats, usually per class. It fails when real objects overlap more than the threshold.
  • Detections are matched to ground truth in score order, one per object. AP is the area under the precision-recall curve (precision made non-increasing), and mAP averages over classes. VOC uses an IoU of 0.5, and COCO averages over thresholds from 0.50 to 0.95.
Found a mistake? Tell us