v9.1.1
Menu

Intersection over Union (IoU)

mediumFREEObject DetectionDetectionCV: Recognition

You are given two axis-aligned bounding boxes and need to calculate their Intersection over Union (IoU), the standard metric for evaluating object detection accuracy.

Bounding boxes are represented as [x1, y1, x2, y2] where (x1, y1) is the top-left corner and (x2, y2) is the bottom-right corner.

IoU=AreaintersectionAreaunion=AreaintersectionAreaA+AreaB−AreaintersectionIoU = \frac{Area_{intersection}}{Area_{union}} = \frac{Area_{intersection}}{Area_A + Area_B - Area_{intersection}}

The algorithm:

  1. Find the intersection rectangle (if any):
    • x1_inter = max(x1_A, x1_B)
    • y1_inter = max(y1_A, y1_B)
    • x2_inter = min(x2_A, x2_B)
    • y2_inter = min(y2_A, y2_B)
  2. Compute intersection area (0 if boxes don't overlap)
  3. Compute union = Area_A + Area_B - intersection
  4. IoU = intersection / union

IoU ranges from 0 (no overlap) to 1 (perfect overlap).

Example

Input
box1 = [0, 0, 10, 10]
box2 = [5, 5, 15, 15]
Output
0.1429
Reasoning
  • Inputs: box1 and box2 are corner lists [x1,y1,x2,y2][x_1, y_1, x_2, y_2]. box1 covers x∈[0,10]x \in [0, 10], y∈[0,10]y \in [0, 10]; box2 covers x∈[5,15]x \in [5, 15], y∈[5,15]y \in [5, 15]. Each is a 10×1010 \times 10 square, so AreaA=AreaB=100Area_A = Area_B = 100.
  • Overlap along x: the two intervals [0,10][0, 10] and [5,15][5, 15] share only [5,10][5, 10], a width of 55. The y axis is identical, giving a height of 55.
  • Intersection: the shared region is the square from (5,5)(5, 5) to (10,10)(10, 10), so Areaintersection=5×5=25Area_{intersection} = 5 \times 5 = 25.
  • Union: 100+100−25=175100 + 100 - 25 = 175. The overlap is subtracted once because adding both areas counts that 5×55 \times 5 patch twice.
  • IoU: 25175=17≈0.142857\frac{25}{175} = \frac{1}{7} \approx 0.142857, rounded to 4 decimal places gives 0.1429.
  • Notice: the boxes share a quarter of each area, yet IoU is only about 0.140.14, because the union also counts both non-overlapping parts. Sliding box2 until its intervals no longer meet box1's leaves zero width, hence an IoU of 00.

Constraints

  • Boxes are in [x1, y1, x2, y2] format (top-left and bottom-right corners)
  • x2 > x1 and y2 > y1 for valid boxes
  • Coordinates can be any real numbers
  • Return IoU rounded to 4 decimal places

Learn this in

More from CV: Recognition

solution.py

Test results

Sign in to run your code against the test cases.