Object detection: IoU, NMS and mAP
If a photo has two cats in it, the single answer "cat" is not enough. You need to point at where each cat is, with a box. Drag a predicted box to build IoU, the score for how well it matches the true box. Then clean up the pile of boxes a detector puts on one object, using NMS.
Short answer. Object detection gives each object in a picture a box, a name and a confidence score. Whether a box is right is measured with IoU = overlap area ÷ union area: IoU = I ÷ (A + B − I), from 0 to 1. A detector puts several boxes on one object, so NMS keeps the highest scoring box and removes the boxes that overlap it a lot. A whole detector is scored by using an IoU cutoff (for example 0.5) to mark each box right or wrong, then taking the area under the precision-recall curve, called AP. The average of AP over all object types is mAP.
Drag the blue predicted box P to move it, and drag the handle at its bottom right corner to resize it. You can also type in the number boxes (in grid squares; these are picture coordinates, so y grows downward). Each press of "Next" adds one piece to the formula (light orange marks the new piece, solid orange marks a wrong turn), paints that piece on the picture, and explains why below. Green is the true box G, blue is the prediction P, orange is the overlap I, and the purple dashed box is the huge box H. All boxes are made up.
Definitions
The text below explains with the lab and a worked example. These are the textbook definitions. G is the ground truth box, P is the predicted box, and |·| is area.
- object detection
- The task of giving, for each object in an image, a bounding box, a class name and a confidence score. The confidence score is the model's belief, from 0 to 1, that this object is in this box.
- bounding box
- A rectangle around an object whose sides run along the width and height axes of the image. It is written as four numbers. This page uses the top left (x1, y1) and the bottom right (x2, y2). Another format uses the center and the size (cx, cy, w, h).
- IoU (intersection over union)
- The area where two boxes overlap divided by the area they cover together. If A and B are the areas of the two boxes and I is the overlap, it is below. It goes from 0 to 1.
- NMS (non-maximum suppression)
- A method that goes through the boxes from the highest score down. It keeps the box with the highest score, deletes the boxes whose IoU with it is above the threshold, and repeats until no boxes are left.
- AP, mAP (average precision, mean average precision)
- Sort the predicted boxes from the highest score down, and count a box as correct when its IoU with a ground truth box is at or above the threshold. With precision Pn (correct ÷ boxes so far) and recall Rn (correct ÷ ground truth boxes) up to box n, AP is the area under the precision-recall curve. Counted without interpolation, as in the example in the text, it is the first formula (R0 = 0). The mean of the AP over C classes is mAP.
1. Classification, detection, segmentation
You can ask three different questions about the same photo.
| Task | Question | Output |
|---|---|---|
| Classification | What is this picture? | One name (and a score) per picture. "cat" |
| Detection | What is where, and how many? | A box, a name and a confidence score per object. Two lines of "cat, (40, 30) to (200, 180), 0.93" |
| Segmentation | What is each pixel? | A name map the size of the picture. One name per type is semantic segmentation; a separate label per object is instance segmentation |
A box is four numbers. This page writes it as the top left corner (x1, y1) and the bottom right corner (x2, y2). Some tools use the center and size (cx, cy, w, h) instead, so check the format first when you use a library (torchvision's nms takes the first format). In picture coordinates the top left is (0, 0) and y grows downward.
The confidence score is how strongly the model believes "this object is in this box", from 0 to 1. It looks like a probability, but there is no promise that 8 out of 10 boxes with score 0.8 are right. Usually low scoring boxes are dropped first (a score cutoff), and NMS cleans up the rest. Inside, a detector is a convolutional neural network that pulls features out of the picture (CNN architectures).
2. How the formula is built: IoU
In the lab above, G is the true box a person drew and P is the box the model predicted. A is the area of G, B is the area of P, I is the overlap area, and U is the union area (the area that at least one of them covers). They start at G = (4, 3) to (10, 7) and P = (6, 4) to (12, 8), and areas are counted in grid squares.
- Overlap only:
score = I. More overlap seems better. P overlaps G by 12 squares. - A huge box wins. A huge box like H = (2, 1) to (16, 10) covers all of G, so it overlaps all 24 squares of G. That beats the 12 of P. Why it fails: the overlap only grows as you draw a bigger box. With this score, a model that draws giant boxes anywhere comes first.
- Divide by the union:
I ÷ U. P gets12 ÷ 36 = 0.33and H gets24 ÷ 126 = 0.19. Now H loses. Why it works: a box drawn too wide makes U bigger, which lowers the score. A box drawn too small makes I smaller, which also lowers it. Only a box in the right place with the right size scores high. - Done:
IoU = I ÷ (A + B − I). Counting U directly is awkward, so add the two areas. That counts the overlap twice, so subtract I once:24 + 24 − 12 = 36. This is where the name comes from: Intersection over Union. It runs from 0 to 1. It is 1 when the boxes match exactly and 0 when they do not overlap.
Try this. ① At the start, I is 12, U is 36 and IoU is 0.33. ② Type 4, 3, 10, 7 into the number boxes so P matches G exactly, and IoU is 1. ③ From there, move one square right (5, 3, 11, 7) and it drops to 0.71. Two squares (6, 3, 12, 7) gives exactly 0.5. A box 6 squares wide that is off by two squares only just passes the common cutoff of 0.5. ④ Put a small P inside G (5, 4, 7, 6). I is 4, all of P, but IoU is only 0.17. Cover all of G with a box twice as wide (4, 3, 16, 7) and IoU is 0.5. Too small and too big both lose points. ⑤ Let only the corners touch (10, 7, 16, 11) and IoU is 0.
3. Work it out by hand
Compute IoU for the starting boxes G = (4, 3) to (10, 7) and P = (6, 4) to (12, 8).
- Areas.
A = (10 − 4) × (7 − 3) = 24,B = (12 − 6) × (8 − 4) = 24. - Overlap box. Left is the larger left edge,
max(4, 6) = 6. Top ismax(3, 4) = 4. Right is the smaller right edge,min(10, 12) = 10. Bottom ismin(7, 8) = 7. The overlap box is (6, 4) to (10, 7). - Overlap area. Width
10 − 6 = 4, height7 − 4 = 3, soI = 12. If the width or height comes out 0 or less, the boxes do not overlap, so use 0. Skip this and two far apart boxes can give negative × negative = positive, which looks like an overlap. - Union and IoU.
U = 24 + 24 − 12 = 36,IoU = 12 ÷ 36 = 0.33.
function iou(a, b) { // a, b = [x1, y1, x2, y2]
const w = Math.max(0, Math.min(a[2], b[2]) - Math.max(a[0], b[0]));
const h = Math.max(0, Math.min(a[3], b[3]) - Math.max(a[1], b[1]));
const i = w * h;
const u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i;
return u > 0 ? i / u : 0;
}
4. What IoU does and does not see
| Property | In plain words | In the lab |
|---|---|---|
| From 0 to 1 | 1 for a perfect match, 0 for no overlap. Touching corners still give 0 | Try this ② and ⑤ |
| Checks place and size together | Too big raises U, too small lowers I, and both lower the score | Try this ④ |
| Does not care about scale | Make both boxes twice as big and I and U both grow 4 times, so IoU stays the same. Pixels or fractions of the image give the same value | (0, 0) to (2, 2) against (1, 1) to (3, 3), and the same boxes doubled, both give 1/7 |
| Strict on small objects | Being off by one square costs a small box more | Moving the 6 wide box by one square gives 0.71; moving a 2 by 2 box by one square gives 0.33 |
| Blind to distance | Without overlap it is 0, whether the box is right next door or far away. IoU alone cannot tell which way to move a box to improve it | Drag P far from G |
5. Removing duplicate boxes: NMS
A detector proposes boxes at many places in the picture, so one object gets several slightly shifted boxes. Leave them all and one cat is counted as several cats. NMS (non-maximum suppression, "push down everything that is not the top") cleans them up like this.
- Sort the boxes from highest score to lowest.
- Keep the first one, the highest score.
- Among the rest, remove every box whose IoU with the box you just kept is above the cutoff. It is treated as a duplicate of the same object.
- Repeat steps 2 and 3 until no boxes are left.
Each "Next step" runs one round of NMS. Green thick boxes (✓) are kept, and the thickest is the one kept in this round. Orange dashed boxes (✕) were removed in this round, grey dashed boxes (✕) in an earlier round, and blue boxes are still waiting. Change the cutoff and the same number of rounds is run again with the new cutoff. This is a small made-up example: A, B and C sit on the left object, and D, E and F on the right one. A real detector proposes far more boxes.
Try this. ① With cutoff 0.5, press "Next step". A (0.92) is kept, and B (IoU 0.71) and C (0.57) are removed. Press again: D (0.88) is kept, and E (0.58) and F (0.77) are removed. It ends with two boxes, A and D. Two objects, two boxes. ② Raise the cutoff to 0.6 and C (0.57) and E (0.58) survive, leaving four boxes: A, D, E, C. Each object is counted twice. At 0.8 nothing is removed and all six stay. ③ Lower the cutoff to 0.15 and A also removes D (IoU 0.17) from the neighboring object. E, with a lower score, stays instead, so you get A and E. At 0.05 A even removes E (IoU 0.07), so only A is left and the right object is lost.
A high cutoff leaves duplicates. A low cutoff also removes a different object standing close by. This is why NMS struggles in pictures where objects overlap a lot, like a crowd of people. In practice NMS is usually run separately for each object type (class), so a cat box never removes the dog box next to it (torchvision's batched_nms).
6. One-stage and two-stage detectors
- Two-stage (the R-CNN family). First pick places where an object might be (region proposals). Then, for each place, decide what it is and refine the box. In Faster R-CNN a small network that makes the proposals (the RPN) shares the picture's features with the detection network.
- One-stage (the YOLO family). No proposal step. The picture goes through the network once, and the boxes and type scores come out together. The first YOLO splits the picture into an S × S grid, and each cell predicts boxes and scores. That is where the name "You Only Look Once" comes from.
Both kinds propose many boxes and clean them up with NMS. So IoU and NMS come along whichever you use.
7. Scoring a detector: AP and mAP
IoU scores one box. A whole detector is scored on the boxes from many pictures. For one object type (say, cats) it goes like this.
- Sort the predicted boxes from all pictures by score, highest first.
- Go down the list. If a box has IoU at or above the cutoff (for example 0.5) with a true box that has no match yet, it is right. Otherwise it is wrong. A second box on the same object is also wrong, so duplicates that NMS missed cost points here.
- After each row, write down the precision (right ÷ boxes so far) and the recall (right ÷ number of true boxes). These points make the precision-recall curve.
- The area under the curve is AP. Compute AP for each type and average them to get mAP.
An example with 3 true boxes and 5 predicted boxes:
| Rank | Score | Result | Precision | Recall |
|---|---|---|---|---|
| 1 | 0.95 | right | 1/1 = 1 | 1/3 = 0.33 |
| 2 | 0.9 | right | 2/2 = 1 | 2/3 = 0.67 |
| 3 | 0.8 | wrong | 2/3 = 0.67 | 0.67 |
| 4 | 0.6 | right | 3/4 = 0.75 | 3/3 = 1 |
| 5 | 0.4 | wrong | 3/5 = 0.6 | 1 |
Each time recall goes up by 1/3, multiply by the precision at that point and add: 1/3 × 1 + 1/3 × 1 + 1/3 × 0.75 ≈ 0.92. That is the AP. Benchmarks differ a little in how they smooth the zigzag of the curve (interpolation) and how many points they measure, so the same result can give slightly different numbers.
The IoU cutoff. The COCO docs list AP at IoU 0.5 as the Pascal VOC metric. COCO itself uses as its main score the average of AP over 10 cutoffs, 0.5, 0.55, and so on up to 0.95, and also reports single cutoffs as AP50 and AP75. COCO calls the value averaged over types simply AP and makes no difference between AP and mAP. So the "AP" in a paper is often really mAP.
8. When to use what
| Option | Good | Bad | Use it when |
|---|---|---|---|
| Classification only | Cheap labels (one name per picture). Small model, little compute | Does not say where things are or how many | One answer per picture is enough. Is this part broken? What kind of photo is this? |
| One-stage detection (YOLO family) | The picture goes through once, so it is fast. Simple design | The first YOLO paper itself said it made more box position errors than the best detectors of its time, and struggled with small objects in groups (a flock of birds) | You watch video in real time, or run on a phone or small device |
| Two-stage detection (R-CNN family) | Looks again at each proposed place and refines the box | Two stages, so it is usually slower than one-stage and more complex | Accuracy matters more than speed, or you process stored photos in batches |
| Segmentation (per pixel) | Gives the exact shape and area. Fits tilted or curved objects with no empty box corners | Expensive labels (you trace outlines). More compute | You need an area (a lesion, a field, a roof), a robot must grab an object, or you need the edge between overlapping objects |
Which one is more accurate changes with the model version, the settings and the data. Instead of memorizing rankings, measure mAP and speed on your own data and choose.
Where it is used
- Self-driving cars and robots. Where are the people, cars and signs?
- Factory inspection. Not only whether there is a defect (classification), but where it is.
- Drone and satellite photos. Find and count cars, buildings and trees.
- Medical images. Mark places worth a look with boxes, and a person checks them.
- Checking labels. Compare boxes drawn by people with the model's boxes, and recheck only the ones with low IoU.
Frequently asked questions
Why is the IoU cutoff 0.5?
It is a convention, not a law. The Pascal VOC evaluation used IoU 0.5, and many others followed. COCO uses the average over 10 cutoffs from 0.5 to 0.95 as its main score, so a detector that places boxes more exactly gets a higher score. If your task needs exact boxes, look at the score for a higher cutoff (for example 0.75).
Is the IoU cutoff in NMS the same as the one in evaluation?
No. They use the same IoU math for different jobs. The NMS cutoff compares the detector's own boxes with each other to remove duplicates. The evaluation cutoff compares a predicted box with a true box to decide right or wrong. The two numbers do not have to match.
Why use mAP instead of accuracy?
In detection you cannot count the correct "nothing here" answers (true negatives). There are endless places where no box should be. So detection is scored with precision and recall, which do not use true negatives. Also, AP is the area under a curve that tries every score cutoff, so you can compare detectors without picking one cutoff first.
Words
| Plain words used here | Textbook term |
|---|---|
| Finding objects | object detection |
| Box | bounding box |
| How sure the model is | confidence score |
| True box | ground truth box |
| Overlap ÷ union | IoU (intersection over union), Jaccard index |
| Removing duplicate boxes | non-maximum suppression (NMS) |
| Places that might hold an object | region proposals; the network that makes them is the RPN (region proposal network) |
| One-stage, two-stage | one-stage detector, two-stage detector |
| Object type | class |
| Naming every pixel | segmentation: semantic segmentation, instance segmentation |
| Right, wrong | true positive (TP), false positive (FP) |
| Precision, recall | precision, recall |
| Area under the curve | average precision (AP) |
| AP averaged over types | mAP (mean average precision) |
| Smoothing the zigzag | interpolation |
Sources
- Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi, You Only Look Once: Unified, Real-Time Object Detection, arXiv:1506.02640. One pass, the S × S grid, the weaknesses the paper names.
- Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun, Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks, arXiv:1506.01497. Region proposals, the RPN, shared features.
- COCO, Detection Evaluation. AP averaged over IoU 0.5 to 0.95, AP50 and AP75, no difference between AP and mAP.
- torchvision docs: nms, batched_nms. The (x1, y1, x2, y2) box format, removing boxes above the cutoff, one class at a time.
← Residual connections (ResNet)Detector architectures: the R-CNN family and YOLO →