Intersection over union
Intersection over union (IoU)
Intersection over union measures the overlap of two regions divided by their combined area. IoU is 1 for identical nonempty regions and 0 for disjoint regions. It is symmetric. Use the same coordinate system and units for both regions. This lesson uses integer half-open boxes [x1,y1,x2,y2] with x2 > x1 and y2 > y1. Negative positions are mathematically allowed here, but an image annotation pipeline may require clipping or rejecting out-of-image boxes; choose a documented policy before evaluation.
Work through the overlap
A=[0,0,2,2] has area 4; B=[1,0,3,2] also has area 4. Their intersection extends from x=1 to x=2 and y=0 to y=2, so its area is 2. The union is 4+4-2=6, not 8. IoU=2/6=1/3. In general, intersection width is max(0,min(right edges)-max(left edges)); height is analogous. Clamp each dimension separately to zero so disjoint boxes never create a spurious positive intersection. Do not add one to widths in this edge-coordinate convention.
Calculate box IoU
def box_area(box): if len(box) != 4 or any(type(v) is not int for v in box): raise ValueError("expected four integer coordinates") x1, y1, x2, y2 = box if x2 <= x1 or y2 <= y1: raise ValueError("box must have positive area") return (x2 - x1) * (y2 - y1)
def overlap_parts(a, b): area_a, area_b = box_area(a), box_area(b) w = max(0, min(a[2], b[2]) - max(a[0], b[0])) h = max(0, min(a[3], b[3]) - max(a[1], b[1])) intersection = w * h return intersection, area_a + area_b - intersection
def box_iou(a, b): intersection, union = overlap_parts(a, b) return intersection / union
a, b = [0, 0, 2, 2], [1, 0, 3, 2]print(overlap_parts(a, b))print(round(box_iou(a, b), 4))print(box_iou(a, a))print(box_iou(a, [2, 0, 4, 2]))The first tuple is (2,6), the rounded IoU is 0.3333, the identical-box result is 1.0, and boxes touching only at an edge score 0.0. The function rejects zero-area and reversed boxes rather than silently repairing annotation errors. Its integer arithmetic is exact until division.
Detection evaluation is more than overlap
A detector can produce scores and duplicate predictions. At a chosen IoU threshold, a prediction may qualify for matching a ground-truth box if the class agrees and that truth has not already been matched. Evaluation protocols define matching order, treatment of difficult examples, ties, and the aggregation of precision and recall. With IoU 1/3, a threshold of 0.5 rejects the example even when the label is correct. Two predictions covering one object cannot both count as true positives under one-to-one matching. Average precision summarizes a precision-recall curve according to a specified protocol; mAP averages AP over specified classes and sometimes IoU thresholds. One pairwise IoU is not mAP. Non-maximum suppression is a prediction postprocessing technique, not a ground-truth matching rule.
Mask IoU and background imbalance
For binary segmentation masks of the same shape, count pixels that are foreground in both as intersection and pixels that are foreground in either as union. Pixel accuracy counts all matching labels including background. In a 100-cell image with one foreground cell, predicting all background yields 99% pixel accuracy but foreground IoU is 0. If neither mask contains foreground the union is zero, so the ratio is undefined; our policy returns None. Other evaluation implementations may ignore empty masks or assign a conventional score; report the policy and aggregation explicitly.
Compare pixel accuracy and mask IoU
def mask_scores(actual, predicted): if not actual or not actual[0]: raise ValueError("empty image") height, width = len(actual), len(actual[0]) if len(predicted) != height or any( len(row) != width for row in actual + predicted ): raise ValueError("masks must share a rectangular shape") pairs = [(a, b) for r, s in zip(actual, predicted) for a, b in zip(r, s)] if any(a not in (0, 1) or b not in (0, 1) for a, b in pairs): raise ValueError("expected binary masks") intersection = sum(a == b == 1 for a, b in pairs) union = sum(a == 1 or b == 1 for a, b in pairs) accuracy = sum(a == b for a, b in pairs) / len(pairs) return accuracy, intersection / union if union else None
print(mask_scores([[1, 0], [0, 0]], [[0, 0], [0, 0]]))print(mask_scores([[1, 1], [0, 0]], [[1, 0], [1, 0]]))print(mask_scores([[0]], [[0]]))The first result is (0.75,0.0): three background cells are correct and the only foreground cell is missed. The second is (0.5,1/3): one shared foreground, two foreground disagreements and one shared background. The last is (1.0,None), showing why empty-foreground behavior must be documented. These are binary mask metrics, not instance matching or multi-class mean IoU.
Common mistakes and practice
Do not mix inclusive pixel indices, normalized coordinates, center-width-height boxes or edge coordinates without conversion. Do not evaluate resized predictions against original coordinates unless you map both to the same frame. A perfect box overlap does not guarantee the correct class, a calibrated score or a good mask. Report per-class results and failure examples; inspect missed small objects and ambiguous annotations. Practice: calculate the IoU of [0,0,3,3] and [1,1,2,2]. The smaller lies entirely inside the larger: intersection 1, union 9, IoU 1/9. Explain why overlap threshold changes cannot fix a systematic coordinate conversion error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Intersection over union quiz
Apply image representation and overlap concepts.
Using half-open coordinates, what is IoU for [0,0,2,2] and [1,0,3,2]?
What is IoU for two positive-area boxes that only touch along an edge?
Two predictions of the same class exceed the IoU threshold for a single ground-truth object. Under one-to-one matching, how many may match that object?
An image has one foreground cell and 99 background cells; all are predicted background. What is foreground IoU?
In the lesson’s mask_scores function, what is returned for foreground IoU when both nonempty masks are all background?