Sub topic 3
Measuring Overlap with Intersection over Union
Assume you know basic Python, image arrays, and object-detection bounding boxes. This chapter uses the corner format (x1, y1, x2, y2), where (x1, y1) is the top-left corner and (x2, y2) is the bottom-right corner. Coordinates are measured in pixels unless stated otherwise.
What IoU measures
Intersection over union, or IoU, measures how much two regions overlap. In object detection, one region is usually the predicted bounding box and the other is the ground-truth box labeled by a human.
The formula is:
IoU = intersection area / union area
The intersection is the shared area. The union is the total area covered by either box. The value ranges from 0 to 1:
| IoU | Meaning |
|---|---|
| 0.0 | The boxes do not overlap |
| 0.5 | The shared area is half of the combined area |
| 1.0 | The boxes are identical |
A detector evaluation often considers a prediction correct when its class is correct and its IoU reaches a chosen threshold, such as 0.5.
Computing IoU from corner coordinates
For boxes A and B, the intersection's top-left corner uses the larger left and top coordinates. Its bottom-right corner uses the smaller right and bottom coordinates. If either resulting width or height is negative, the boxes do not overlap on that axis, so use zero.
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_width = max(0, ix2 - ix1)
inter_height = max(0, iy2 - iy1)
inter = inter_width * inter_height
area_a = max(0, ax2 - ax1) * max(0, ay2 - ay1)
area_b = max(0, bx2 - bx1) * max(0, by2 - by1)
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)))
# 0.14285714285714285Here, the intersection is a 5-by-5 square with area 25. Each original box has area 100, so the union is 100 + 100 - 25 = 175. The IoU is therefore 25 / 175, or about 0.143.
Common errors
- Mixing coordinate systems, such as comparing pixel coordinates with normalized coordinates.
- Treating
(x, y, width, height)as(x1, y1, x2, y2). - Forgetting to clamp a non-overlap width or height to zero.
- Dividing by zero for an invalid or zero-area box.
- Comparing boxes from different images or different image resizing steps.
Exercise
What is the IoU of boxes (0, 0, 10, 10) and (10, 0, 20, 10)?
Show answer
0. They touch at an edge, but their intersection has zero area.