Sub topic 2
Measuring box overlap with IoU
Every stage of an object detector has to answer one question: how well does this box match that box? Intersection over Union (IoU) is the standard answer. This chapter defines IoU, implements it, and covers its edge cases and limits. Later chapters use it for anchor matching, non-maximum suppression, and evaluation.
This chapter assumes basic Python and NumPy, and the idea that a detector outputs boxes with class scores. You don't need to know how the boxes are produced yet.
The definition
IoU compares two regions. It is the area where they overlap, divided by the area covered by either of them:
IoU(A, B) = area(A ∩ B) / area(A ∪ B)
The union is not a separate measurement. You compute it as area(A) + area(B) − area(A ∩ B), so the overlap is not counted twice.
The result has useful properties:
- It is 1.0 only when the boxes are identical.
- It is 0.0 when the boxes share no area.
- It is symmetric: IoU(A, B) equals IoU(B, A).
- It does not change if you scale both boxes and the image by the same factor.
IoU is also called the Jaccard index. Segmentation papers use the same formula on pixel masks.
Box format
This tutorial writes a box as (x1, y1, x2, y2): the top-left corner and the bottom-right corner, with x growing rightward and y growing downward. Other formats are common, including (cx, cy, w, h) and (x, y, w, h). Convert to corner format before computing IoU. Mixing formats is one of the most common silent bugs in detection code, because the function still returns a number.
Computing it step by step
The intersection of two axis-aligned boxes is itself a box. Its left edge is the larger of the two left edges, and its right edge is the smaller of the two right edges. The same rule applies vertically. If the resulting width or height is negative, the boxes don't overlap, so you clamp it to zero.
Here is the implementation:
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2)."""
ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
print(iou((0, 0, 10, 10), (5, 5, 15, 15))) # 25 / 175 = 0.142857...For the example, the intersection is the square from (5, 5) to (10, 10), which has area 25. Each box has area 100, so the union is 100 + 100 − 25 = 175. The IoU is about 0.143, even though each box covers a quarter of the other. IoU is stricter than your intuition about "overlapping a lot."
Edge cases
- Disjoint boxes. The clamp produces an intersection of 0, so IoU is 0.0. Without the clamp, two negative sides would multiply into a positive area and give a wrong answer.
- Touching boxes. Boxes that share only an edge have zero intersection area, so IoU is 0.0.
- Containment. If a 4×4 box sits inside a 10×10 box, the intersection is the small box (area 16) and the union is the large box (area 100). The IoU is 0.16, even though one box is fully inside the other.
- Degenerate boxes. A box with zero width and height contributes zero area. If both boxes are degenerate, the union is 0, and the
union > 0guard avoids a division by zero. - Inverted boxes. If a model outputs
x2 < x1, the area formula gives a negative or misleading number. Clamp or sort corners before computing IoU if your model can produce such boxes.
The pixel convention
Some older code treats coordinates as pixel indices and computes width as x2 - x1 + 1, so a box covering one pixel has width 1. Other code, including the function above, treats coordinates as continuous positions and uses x2 - x1. The two conventions differ slightly for small boxes. Use the same one for training, inference, and evaluation. A mismatch produces small but consistent shifts in your metrics.
Computing IoU in bulk
Detectors compare thousands of anchors against a handful of ground-truth boxes. A Python loop over pairs is too slow, so you compute a matrix of IoUs with broadcasting:
import numpy as np
def pairwise_iou(a, b):
"""IoU between every box in a (N, 4) and every box in b (M, 4).
Boxes are (x1, y1, x2, y2). Returns an (N, M) array.
"""
a = np.asarray(a, dtype=float)
b = np.asarray(b, dtype=float)
lt = np.maximum(a[:, None, :2], b[None, :, :2]) # (N, M, 2)
rb = np.minimum(a[:, None, 2:], b[None, :, 2:]) # (N, M, 2)
wh = np.clip(rb - lt, 0, None)
inter = wh[..., 0] * wh[..., 1]
area_a = (a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1])
area_b = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
union = area_a[:, None] + area_b[None, :] - inter
return np.where(union > 0, inter / np.maximum(union, 1e-12), 0.0)
a = [(0, 0, 10, 10), (50, 50, 60, 60)]
b = [(5, 5, 15, 15), (0, 0, 10, 10), (2, 2, 6, 6)]
print(np.round(pairwise_iou(a, b), 3))
# [[0.143 1. 0.16 ]
# [0. 0. 0. ]]The None indexing adds axes so every box in a is paired with every box in b. Row i, column j of the result is the IoU of a[i] and b[j]. This matrix is what anchor matching and NMS consume.
Where IoU is used
IoU appears three times in a detection pipeline:
| Stage | How IoU is used | Typical threshold |
|---|---|---|
| Training: label assignment | An anchor whose IoU with a ground-truth box is high becomes a positive example; a low IoU makes it a negative | 0.5 to 0.7 for positive, below 0.3 to 0.4 for negative, depending on the detector |
| Inference: non-maximum suppression | A box that overlaps a higher-scoring box too much is discarded as a duplicate | 0.5 is a common default |
| Evaluation | A prediction counts as correct only if its IoU with a ground-truth box passes a threshold | 0.5, or an average over 0.5 to 0.95 |
The threshold is a design choice, not a law. A higher threshold demands tighter boxes. A lower one tolerates sloppy localization.
Limits of IoU
Sensitivity depends on box size. Shift a 10×10 box by one pixel horizontally and the IoU drops to 90/110, about 0.82. Shift a 100×100 box by the same one pixel and the IoU is 9900/10100, about 0.98. A fixed IoU threshold is therefore much harsher on small objects, which is part of why small objects are hard to detect.
IoU gives no signal for disjoint boxes. Any two non-overlapping boxes have IoU 0, whether they are one pixel apart or the whole image apart. If you use 1 − IoU as a training loss, a prediction that misses the target entirely gets zero gradient and learns nothing. Variants such as generalized IoU (GIoU) add a term that depends on the smallest box enclosing both boxes, so that distant boxes still produce a useful gradient. Later chapters on detection losses return to this.
IoU ignores shape and alignment. Different pairs of boxes can share the same IoU. A box shifted sideways and a box that is too large can both score 0.5. IoU also says nothing about which error is worse for your application.
Exercise
Compute the IoU of boxes (0, 0, 4, 4) and (2, 0, 6, 4) by hand, using the corner format and the continuous convention.
Show answer
The intersection is the box from (2, 0) to (4, 4), with width 2 and height 4, so its area is 8. Each box has area 16, so the union is 16 + 16 − 8 = 24. The IoU is 8 / 24 = 1/3, about 0.333.
Exercise
A 20×20 box and a 200×200 box are each shifted by 2 pixels horizontally relative to a ground-truth box of the same size. Which has the higher IoU, and why does this matter for a fixed threshold such as 0.5 or 0.75?
Show answer
The 200×200 box has the higher IoU. For the 20×20 box, the intersection is 18×20 = 360 and the union is 400 + 400 − 360 = 440, so IoU is about 0.82. For the 200×200 box, the intersection is 198×200 = 39600 and the union is 80000 − 39600 = 40400, so IoU is about 0.98. The same pixel error costs a small object much more IoU, so a fixed threshold is stricter for small objects.