IoU of bounding boxesEasy

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):

IoU=area(intersection)area(box1)+area(box2)area(intersection)\text{IoU} = \frac{\text{area}(\text{intersection})}{\text{area}(\text{box1}) + \text{area}(\text{box2}) - \text{area}(\text{intersection})}

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] with x2 >= x1 and y2 >= y1.

Output

A float IoU in [0,1][0, 1].

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 [1,2]×[1,2][1,2]\times[1,2], so intersection =1=1 and union =4+41=7=4+4-1=7, giving 1/71/7.

Constraints

  • Intersection width/height are clamped at 0: max(0, ix2 - ix1) and max(0, iy2 - iy1).
  • union = area1 + area2 - intersection.
  • Guard against division by zero (return 0.0 when 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.
Python
Loading...

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