Sub topic 2
Intersection over Union: measuring box overlap
Every detection metric in this tutorial depends on one number: how well a predicted box lines up with a ground-truth box. That number is Intersection over Union (IoU). This chapter defines it, implements it, and covers the edge cases and input mistakes that corrupt it.
This chapter assumes you know basic Python (functions, tuples, lists) and what a detector outputs: boxes, class labels, and confidence scores. The NumPy section also assumes you have seen array broadcasting. The previous chapter covered box formats. A short recap appears below, because most IoU bugs are format bugs.
The definition
IoU is the area where two boxes overlap, divided by the total area they cover together.
- The intersection is the region that lies inside both boxes.
- The union is the region that lies inside at least one of them.
For two boxes A and B:
IoU(A, B) = area(A ∩ B) / area(A ∪ B)Computing the union directly is awkward. Use inclusion-exclusion instead: adding the two areas counts the intersection twice, so subtract it once.
area(A ∪ B) = area(A) + area(B) - area(A ∩ B)So you need three quantities: the two box areas and the intersection area.
The result always falls between 0 and 1.
| IoU | Meaning |
|---|---|
| 0.0 | The boxes share no area. |
| Near 0.3 | A weak overlap. Most detectors would call this a miss. |
| 0.5 | The overlap is half of the combined area. This is the classic "correct" threshold. |
| 0.75 | A tight match. Most of both boxes is shared. |
| 1.0 | The boxes are identical. |
Computing the intersection
For axis-aligned boxes in (x1, y1, x2, y2) format, the intersection is itself an axis-aligned rectangle. Its corners come from the inner edges of the two boxes:
- Left edge: the larger of the two
x1values. - Top edge: the larger of the two
y1values. - Right edge: the smaller of the two
x2values. - Bottom edge: the smaller of the two
y2values.
If the boxes do not overlap, the computed right edge falls to the left of the computed left edge. Width then comes out negative. You must clamp width and height at zero, or a negative width times a negative height would produce a positive "area" for two boxes that are far apart.
A reference implementation
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2) with x1 < x2 and y1 < y2."""
ix1 = max(a[0], b[0])
iy1 = max(a[1], b[1])
ix2 = min(a[2], b[2])
iy2 = 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...
print(iou((0, 0, 10, 10), (0, 0, 10, 10))) # 1.0
print(iou((0, 0, 10, 10), (20, 20, 30, 30))) # 0.0Output:
0.14285714285714285
1.0
0.0Check the first case by hand. Two 10×10 boxes overlap in a 5×5 square. The intersection is 25. Each box has area 100, so the union is 100 + 100 − 25 = 175. The ratio is 25/175 ≈ 0.143.
Two details matter in this function:
- The
max(0.0, ...)calls clamp negative widths and heights. Without them, the third example would give a nonsense positive value. - The
if union > 0guard avoids dividing by zero when both boxes have zero area.
Edge cases
The function above handles the common cases. These are the ones worth testing deliberately.
def iou(a, b):
ix1 = max(a[0], b[0])
iy1 = max(a[1], b[1])
ix2 = min(a[2], b[2])
iy2 = 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
# Boxes that touch along an edge: zero-width intersection.
print(iou((0, 0, 10, 10), (10, 0, 20, 10))) # 0.0
# One box fully inside the other: IoU is the ratio of the areas.
print(iou((0, 0, 10, 10), (2, 2, 6, 6))) # 16 / 100 = 0.16
# Two degenerate boxes with zero area: union is 0, guarded.
print(iou((5, 5, 5, 5), (5, 5, 5, 5))) # 0.0
# Order does not matter.
print(iou((0, 0, 10, 10), (5, 5, 15, 15)) == iou((5, 5, 15, 15), (0, 0, 10, 10))) # TrueOutput:
0.0
0.16
0.0
TrueSome points to notice:
- Touching is not overlapping. Boxes that share only an edge have an intersection of zero area, so IoU is 0.
- Containment is penalized. A small box fully inside a large one has IoU equal to the ratio of the areas. A tiny box inside a huge one scores near zero even though it is "inside".
- IoU is symmetric.
iou(a, b)equalsiou(b, a). It treats prediction and ground truth the same way. It does not tell you which box is too big or too small. - Identical degenerate boxes score 0, not 1. Mathematically the value is undefined, since 0/0. Returning 0.0 is the usual convention. A zero-area box in your data usually signals a labeling or conversion bug, so consider logging it rather than silently scoring it.
Getting the inputs right
IoU is arithmetic on four numbers per box. If those numbers mean something different from what the function expects, the output is still a plausible-looking float in [0, 1]. This makes input mistakes hard to spot.
Corner format versus width-height format
The function above expects (x1, y1, x2, y2). Many datasets, including COCO annotations, store boxes as (x, y, w, h), where (x, y) is the top-left corner. Passing xywh boxes to an xyxy function treats w and h as the bottom-right corner. The result is wrong, and often only slightly wrong, so the bug survives casual checks.
def xywh_to_xyxy(box):
x, y, w, h = box
return (x, y, x + w, y + h)
print(xywh_to_xyxy((10, 20, 30, 40))) # (10, 20, 40, 60)Output:
(10, 20, 40, 60)Normalized versus pixel coordinates
Some detectors, including YOLO-style formats, output coordinates as fractions of image width and height, in the range 0 to 1. IoU is not affected if both boxes use the same normalization and the image is scaled uniformly. But if one box is normalized and the other is in pixels, the intersection is near zero and IoU collapses. Convert both boxes to the same space before comparing.
A subtler issue arises with non-square images. IoU computed in normalized coordinates is not equal to IoU computed in pixels when width and height differ, because the two axes are scaled differently. The overlap fraction is preserved for axis-aligned boxes, because each area is scaled by the same constant W × H. This is only safe if you normalize by the actual image dimensions, not by a padded square from letterboxing. After letterboxing, map boxes back to the original image first.
The "+1" pixel convention
Some older code, including the original Pascal VOC devkit, treats box coordinates as inclusive pixel indices. A box from x=0 to x=9 then has width 10, so width is computed as x2 - x1 + 1. The COCO tooling treats coordinates as continuous values and uses x2 - x1.
For large boxes the difference is negligible. For small boxes it matters. A 4×4 box under the continuous convention has area 16. Under the inclusive convention, the same coordinates give a 5×5 area of 25.
Use one convention across your whole evaluation, and use the one the benchmark you are comparing against uses.
Why IoU is sensitive to size
IoU measures a ratio, not a distance in pixels. The same one-pixel error costs very different amounts depending on box size.
| Box size | Shift | IoU |
|---|---|---|
| 4×4 | 1 px in x | 12 / 20 = 0.600 |
| 10×10 | 1 px in x | 90 / 110 ≈ 0.818 |
| 10×10 | 1 px in x and y | 81 / 119 ≈ 0.681 |
| 100×100 | 1 px in x | 9900 / 10100 ≈ 0.980 |
A one-pixel horizontal shift on a 4×4 box already drops IoU to 0.6. A 4×4 box shifted by two pixels in x has intersection 8 and union 24, so IoU is 0.333 and it fails a 0.5 threshold. The same two-pixel shift on a 100×100 box is nearly invisible. This is why small-object detection scores are systematically lower under IoU-based metrics. It is also why COCO reports results split by object size, a topic for a later chapter.
It helps to know what a threshold means geometrically. Take two equal-size boxes with one shifted sideways by a fraction d of the box width. The intersection is 1 - d and the union is 1 + d, so IoU is (1 - d) / (1 + d).
- IoU = 0.5 gives
d = 1/3. The box can drift by a third of its width. - IoU = 0.75 gives
d = 1/7, about 14% of its width.
Computing many IoUs at once
Evaluation compares every detection to every ground-truth box in an image. A Python double loop works but is slow for large datasets. A vectorized version builds the whole pairwise matrix with broadcasting.
import numpy as np
def iou_matrix(a, b):
"""Pairwise IoU. a has shape (N, 4), b has shape (M, 4), both xyxy.
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) top-left of intersection
rb = np.minimum(a[:, None, 2:], b[None, :, 2:]) # (N, M, 2) bottom-right
wh = np.clip(rb - lt, 0, None) # clamp negative sizes to 0
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 inter / np.where(union > 0, union, 1.0)
preds = [(0, 0, 10, 10), (20, 20, 30, 30)]
gts = [(5, 5, 15, 15), (0, 0, 10, 10), (25, 25, 35, 35)]
print(np.round(iou_matrix(preds, gts), 3))Output:
[[0.143 1. 0. ]
[0. 0. 0.143]]Row i, column j holds the IoU of prediction i and ground truth j. The line np.where(union > 0, union, 1.0) is the vectorized form of the zero-union guard. Where the union is zero, the intersection is also zero, so the result is 0.
This matrix is the input to the matching step in a later chapter. Each detection is assigned to the ground-truth box in its row with the highest IoU, if that value reaches the threshold.
Limits of plain IoU
IoU is a good evaluation measure, but it has two weaknesses you should know about.
First, it carries no information about how far apart two disjoint boxes are. A prediction one pixel away from the target and a prediction on the other side of the image both score exactly 0. For scoring, this is fine. A prediction that misses entirely is a miss. For training a detector with IoU as a loss, it is a problem. A flat zero gives no gradient to pull a non-overlapping box toward the target. The final chapter covers GIoU, DIoU, and CIoU, which patch this.
Second, IoU says nothing about how the boxes differ. Two predictions with IoU 0.6 can be wrong in different ways: one shifted, one too large. Axis-aligned boxes also cannot describe rotated objects tightly. For rotated boxes or polygons, the intersection is harder to compute, and you need a polygon-clipping routine rather than the min/max trick above.
Common mistakes
- Skipping the clamp. Two distant boxes then produce a positive intersection from two negative numbers.
- Mixing box formats.
xywhagainstxyxy, or pixel against normalized, gives smooth but wrong values. - Mixing area conventions. Using
+1for the ground truth and not the predictions, or the reverse. - Unordered corners. The function assumes
x1 < x2andy1 < y2. A box whose corners are swapped yields a negative area. Normalize withminandmaxfirst if your source does not guarantee order. - Not clipping boxes to the image. Detectors can predict boxes that extend past the image border. Whether you clip them before scoring changes IoU. Decide once, and apply the same rule to every box.
Exercise
A ground-truth box is (0, 0, 20, 10). A detector predicts (10, 0, 30, 10). What is the IoU, and does the detection count as correct at an IoU threshold of 0.5?
Show answer
The intersection spans x from 10 to 20 and y from 0 to 10, so it is 10 × 10 = 100. Each box has area 20 × 10 = 200. The union is 200 + 200 − 100 = 300. IoU = 100 / 300 ≈ 0.333. This is below 0.5, so the detection is not correct at that threshold, even though the box is half-overlapping and the right size. The box is shifted by half its width, which is more than the one-third shift that a 0.5 threshold allows.
Exercise
A 6×6 ground-truth box sits at (0, 0, 6, 6). A detector predicts a larger box (0, 0, 12, 12) that fully contains it. What is the IoU, and what does the result tell you about IoU as a measure?
Show answer
The intersection is the whole ground-truth box, 36. The prediction has area 144. The union is 36 + 144 − 36 = 144. IoU = 36 / 144 = 0.25. The prediction covers the target completely and still scores low, because IoU penalizes extra area as heavily as missing area. It also cannot tell you whether the prediction was too big or too small, since the value is symmetric.