IoU of bounding boxes
Background
Intersection over Union (IoU) measures how well two boxes overlap and is the workhorse metric of object detection. For a predicted box and a ground-truth box, IoU is the area of their intersection divided by the area of their union. A value of 1 means a perfect match; 0 means no overlap. Detectors use IoU thresholds to decide true positives and to suppress duplicate boxes (NMS).
Problem statement
Implement iou(box1, box2) for two axis-aligned boxes in [x1, y1, x2, y2] format (top-left and bottom-right corners):
If the boxes do not overlap, the intersection area is 0. If the union area is 0, return 0.0.
Input
box1,box2— sequences[x1, y1, x2, y2]withx2 >= x1andy2 >= y1.
Output
A float IoU in .
Examples
Example 1
Input: box1 = [0, 0, 2, 2], box2 = [1, 1, 3, 3]
Output: 0.142857... (= 1/7)
Explanation: both boxes have area 4. They overlap in the unit square , so intersection and union , giving .
Constraints
- Intersection width/height are clamped at 0:
max(0, ix2 - ix1)andmax(0, iy2 - iy1). union = area1 + area2 - intersection.- Guard against division by zero (return
0.0when union is 0).
Notes
- Clamping the overlap dimensions to 0 is what makes non-overlapping (or edge-touching) boxes correctly score 0.
- IoU is scale-invariant: scaling both boxes by the same factor leaves the ratio unchanged.
This problem ships 5 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example -> 1/7
- •Identical boxes give IoU 1
- •Disjoint boxes give IoU 0
- •One box fully inside the other
- •Edge-touching boxes have zero overlap