Sub topic 2
Measuring Box Overlap with IoU
Assume you know basic Python, NumPy, bounding-box coordinates, and the difference between classification and regression. This chapter uses boxes written as (x1, y1, x2, y2), where (x1, y1) is the top-left corner and (x2, y2) is the bottom-right corner.
What IoU measures
Intersection over Union, or IoU, is a number that measures how much two boxes overlap. It divides the area shared by both boxes by the total area covered by either box:
IoU = intersection area / union area
The value is between 0 and 1:
| IoU | Meaning |
|---|---|
| 0.0 | The boxes do not overlap |
| 0.5 | The intersection is half the union |
| 1.0 | The boxes are identical |
The intersection is the rectangular region inside both boxes. The union includes the intersection and the parts that belong to only one box.
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, 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])
intersection = 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 - intersection
return intersection / union if union > 0 else 0.0
box_a = (0, 0, 10, 10)
box_b = (5, 5, 15, 15)
print(iou(box_a, box_b)) # 0.142857...Here, the intersection is a 5 × 5 square with area 25. Each box has area 100, so the union is 100 + 100 - 25 = 175. The IoU is therefore 25 / 175, or about 0.143.
Why IoU matters during detection
During training, a detector needs to decide whether a predicted or reference box matches a ground-truth box. Ground truth is the manually labeled answer. A rule might call a box positive when its IoU is at least 0.5.
During inference, IoU helps remove duplicate predictions. If two boxes predict the same object and have high IoU, a post-processing method such as non-maximum suppression can keep the higher-scoring box and discard the other.
IoU also appears in evaluation. A prediction can count as correct only when its class is correct and its IoU with the ground-truth box reaches the chosen threshold.
Common edge cases
If boxes only touch at an edge, their intersection has zero area, so IoU is 0. If a box has invalid coordinates, such as x2 <= x1, its area is not valid. Production code should validate or reject such boxes before computing IoU.
Exercise
Two boxes have an intersection area of 40. Their individual areas are 100 and 80. What is their IoU?
Show answer
The union is 100 + 80 - 40 = 140. IoU = 40 / 140 ≈ 0.286.