Intersection over Union (IoU) measures how well a predicted bounding box or segmented region overlaps with the ground truth โ the foundational metric behind essentially every object detection and segmentation evaluation.
Formula
\(A\) is the predicted region (e.g. a bounding box), \(B\) is the ground-truth region. IoU ranges from 0 (no overlap at all) to 1 (perfect, exact overlap).
Diagram
IoU divides the overlapping region's area by the total combined area both boxes cover together.
Numerical Example
Predicted box: \((x_1,y_1,x_2,y_2) = (10, 10, 50, 50)\) โ a 40ร40 box, area 1600. Ground truth box: \((30,30,70,70)\) โ a 40ร40 box, area 1600. Overlap region: \((30,30,50,50)\) โ a 20ร20 box, area 400.
Code
def iou(boxA, boxB):
# box format: (x1, y1, x2, y2)
x1 = max(boxA[0], boxB[0])
y1 = max(boxA[1], boxB[1])
x2 = min(boxA[2], boxB[2])
y2 = min(boxA[3], boxB[3])
intersection = max(0, x2 - x1) * max(0, y2 - y1)
areaA = (boxA[2]-boxA[0]) * (boxA[3]-boxA[1])
areaB = (boxB[2]-boxB[0]) * (boxB[3]-boxB[1])
union = areaA + areaB - intersection
return intersection / union if union > 0 else 0
print(iou((10,10,50,50), (30,30,70,70))) # approximately 0.143
How IoU Is Used in Practice
A detection is typically counted as a "correct match" (a true positive) only if its IoU with a ground-truth box exceeds a chosen threshold โ commonly 0.5. This threshold-based matching is exactly what feeds into Mean Average Precision, the standard overall object detection metric covered at the end of this category.
Common Mistakes
- Forgetting to subtract the intersection area once when computing the union โ simply adding both boxes' areas double-counts the overlapping region.
- Assuming a single fixed IoU threshold (like 0.5) is universal โ different tasks and benchmarks use different thresholds, or even average performance across multiple thresholds (as mAP often does).
Interview Relevance
Q: "How is IoU used to decide whether an object detection prediction counts as correct?" A predicted bounding box is typically counted as a correct detection (a true positive) only if its IoU with the corresponding ground-truth box exceeds a chosen threshold, commonly 0.5. Predictions with lower overlap are counted as false positives (or the ground-truth object is counted as missed, a false negative), forming the basis for precision/recall-based detection metrics like mean Average Precision.
Practice Question
Two boxes each have area 100, with an overlapping region of area 50. Compute their IoU.