Sub topic 3
Measuring overlap with intersection over union
This chapter assumes you can read basic Python, know that a bounding box is stored as four numbers, and have seen the corner format (x1, y1, x2, y2) from the previous chapter. You do not need any deep learning background beyond that.
Why detection needs an overlap measure
A detector predicts a box, and a human labeled a ground-truth box. Both describe the same object, but their coordinates will never match exactly. You need one number that says how well two boxes agree. That number is used in three places in a YOLO workflow:
- Training. Box loss terms compare predicted boxes to ground-truth boxes, and many modern losses are built directly from IoU.
- Non-maximum suppression (NMS). NMS decides whether two predictions describe the same object by checking their overlap.
- Evaluation. A prediction counts as correct only if its overlap with a ground-truth box passes a threshold.
The measure used in all three is intersection over union (IoU), also called the Jaccard index.
The definition
For two boxes A and B:
IoU(A, B) = area(A ∩ B) / area(A ∪ B)
The intersection is the region both boxes cover. The union is the region at least one box covers. Because the union is never smaller than the intersection, IoU always falls between 0 and 1.
- 0 means the boxes do not overlap at all.
- 1 means the boxes are identical.
- Values in between grow as the boxes agree more in both position and size.
The union is not computed by tracing its outline. You use inclusion-exclusion instead: union = area(A) + area(B) − area(A ∩ B). Adding both areas counts the overlap twice, so you subtract it once.
Computing the intersection
With corner-format boxes, the intersection of two axis-aligned boxes is itself an axis-aligned box. Its edges are:
- 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 right edge is left of the left edge, or the bottom edge is above the top edge, the boxes do not overlap. The width or height would then be negative, so you clamp each to zero before multiplying.
def iou(a, b):
# Boxes are (x1, y1, x2, y2) in the same coordinate system.
ax1, ay1, ax2, ay2 = a
bx1, by1, bx2, by2 = b
ix1, iy1 = max(ax1, bx1), max(ay1, by1)
ix2, iy2 = min(ax2, bx2), min(ay2, by2)
inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
union = (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - inter
return inter / union if union > 0 else 0.0
print(iou((0, 0, 10, 10), (5, 5, 15, 15))) # 25 / 175 = 0.142857...Work through the example. Box A covers 0 to 10 in both directions, so its area is 100. Box B covers 5 to 15, so its area is also 100. The intersection runs from 5 to 10 in each direction, which is a 5 by 5 square with area 25. The union is 100 + 100 − 25 = 175. IoU is 25 / 175, about 0.143.
Note the surprise here. Each box is shifted by only half its width and height, yet IoU is below 0.15. IoU drops quickly with small misalignments, which is why thresholds like 0.5 are already fairly demanding.
Reading IoU values
IoU values have no universal meaning, but some rough points help.
| IoU | What the boxes look like |
|---|---|
| 0.0 | Disjoint or only touching |
| 0.1 to 0.3 | Partial overlap, clearly misaligned |
| 0.5 | Substantial overlap, the usual "good enough" match |
| 0.75 | Tight fit, small edge errors |
| 0.9 and above | Almost identical, close to annotation noise |
The 0.5 threshold is the classic PASCAL VOC convention. COCO-style evaluation also averages results over thresholds from 0.5 to 0.95. The metrics chapter covers how that is done.
Edge cases
IoU is simple, but the code can fail in a few specific ways.
Zero-area and invalid boxes
If both boxes have zero area, the union is zero and division fails. The function above returns 0.0 through its union > 0 guard. If you remove the guard, you will see a ZeroDivisionError on degenerate input.
A box with x2 < x1 is invalid. The area formula would give a negative number, and the result is meaningless. Either fix such boxes upstream or clamp widths and heights to zero when computing each area.
Touching boxes
Two boxes that share only an edge have an intersection width or height of exactly zero. The intersection area is zero, so IoU is 0. This is correct, since a shared edge has no area.
Mixed coordinate systems
IoU is only meaningful when both boxes use the same format and scale. Mixing a normalized YOLO box (values 0 to 1) with a pixel box gives a number that looks valid but is wrong. Mixing xywh with xyxy has the same effect, and it will not raise an error. Convert both boxes to the same corner format first.
Pixel-index conventions
Some older codebases treat coordinates as inclusive pixel indices and add 1 to widths and heights. The code here treats coordinates as continuous edges, which is what Ultralytics uses. The two conventions differ slightly for small boxes, so match whichever convention your reference implementation uses when you compare numbers.
Containment
If a small box sits entirely inside a large box, the intersection equals the small box's area, and the union equals the large box's area. IoU is then small-area / large-area, which can be low even though the small box is "inside" the other. IoU measures agreement in size as well as position, not just containment.
Limits of plain IoU
IoU has a known weakness as a training signal. When two boxes do not overlap, IoU is exactly 0 no matter how far apart they are. A loss of 1 - IoU then gives no gradient, so the model cannot tell whether to move the box a little or a lot.
Variants of IoU address this. They are used inside loss functions, not for evaluation.
- GIoU adds a penalty based on the smallest box enclosing both boxes, so distant boxes score worse than near ones.
- DIoU penalizes the distance between box centers.
- CIoU adds a term for aspect-ratio consistency on top of DIoU. Ultralytics YOLO models use CIoU in the box loss by default.
For NMS and for evaluation, plain IoU remains the standard.
Vectorized IoU
Looping over pairs of boxes in Python is slow when you have thousands of predictions. NumPy lets you compute the full matrix of IoUs between two sets of boxes at once.
import numpy as np
def iou_matrix(a, b):
# a: (N, 4) array, b: (M, 4) array, both in xyxy format.
a = np.asarray(a, dtype=float)
b = np.asarray(b, dtype=float)
ix1 = np.maximum(a[:, None, 0], b[None, :, 0])
iy1 = np.maximum(a[:, None, 1], b[None, :, 1])
ix2 = np.minimum(a[:, None, 2], b[None, :, 2])
iy2 = np.minimum(a[:, None, 3], b[None, :, 3])
inter = np.clip(ix2 - ix1, 0, None) * np.clip(iy2 - iy1, 0, None)
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.where(union > 0, union, 1), 0.0)
preds = [(0, 0, 10, 10), (5, 5, 15, 15)]
truth = [(0, 0, 10, 10)]
print(iou_matrix(preds, truth))The output is a 2 by 1 matrix: [[1.], [0.14285714]]. Entry [i, j] is the IoU of prediction i with ground truth j. The None indexing adds an axis so NumPy broadcasts every pair. The inner np.where avoids a divide-by-zero warning when the union is zero.
Common mistakes
- Forgetting to clamp. Without
max(0, ...), two far-apart boxes produce a product of two negative numbers, which is positive. The code then reports overlap that does not exist. - Mixing formats. Always convert to one corner format before calling the function.
- Comparing normalized and pixel boxes. Scale both to the same space.
- Reading IoU as accuracy. An IoU of 0.6 does not mean the model is 60 percent correct. It describes how well one pair of boxes agrees.
Exercise
Box A is (0, 0, 4, 4) and box B is (2, 0, 6, 4). Compute their IoU by hand, then say what IoU you would get if B were shifted to (4, 0, 8, 4).
Show answer
A and B each have area 16. The intersection runs from x = 2 to 4 and y = 0 to 4, so it is 2 by 4 = 8. The union is 16 + 16 - 8 = 24. IoU = 8 / 24 = 0.333. For the shifted B, the boxes share only the edge at x = 4, so the intersection width is 0, the intersection area is 0, and IoU = 0.
Exercise
A ground-truth box is (0, 0, 10, 10). A prediction is (0, 0, 5, 5), fully inside it. What is the IoU, and what does it tell you about the prediction?
Show answer
The intersection is the prediction itself, area 25. The union is the ground-truth area, 100. IoU = 25 / 100 = 0.25. The prediction is positioned correctly but is too small, so it fails a 0.5 threshold. IoU penalizes size mismatch as well as position error.