PIXELBANKv9.1.0
Menu

Intersection over Union (IoU)

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:
  1. Find intersection rectangle:

    • x1_inter = max(0, 5) = 5
    • y1_inter = max(0, 5) = 5
    • x2_inter = min(10, 15) = 10
    • y2_inter = min(10, 15) = 10
    • Intersection = [5, 5, 10, 10]
  2. Calculate areas:

    • Area_intersection = (10-5) Γ— (10-5) = 25
    • Area_box1 = (10-0) Γ— (10-0) = 100
    • Area_box2 = (15-5) Γ— (15-5) = 100
    • Area_union = 100 + 100 - 25 = 175
  3. IoU = 25 / 175 = 0.1429

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
solution.py

Test Results

0/0
Run code to see test results.