Problems
Loading...
1 / 1

Intersection over Union (IoU)

Metrics & EvaluationComputer Vision
Easy

Intersection over Union is the standard metric for measuring how well a predicted bounding box overlaps with a ground truth box. It is used everywhere in object detection to evaluate predictions and to filter duplicates.

Given two axis-aligned bounding boxes, each represented as [x1, y1, x2, y2] where (x1, y1) is the top-left corner and (x2, y2) is the bottom-right corner, compute their IoU.

Formula

IoU=Area of IntersectionArea of Union\text{IoU} = \frac{\text{Area of Intersection}}{\text{Area of Union}} Union=Area(A)+Area(B)Intersection\text{Union} = \text{Area}(A) + \text{Area}(B) - \text{Intersection}

If both boxes have zero area (and thus union is zero), return 0.0.

Return the IoU as a float in the range [0, 1].

Loading visualization...

Examples

Input:

box_a = [0, 0, 4, 4] box_b = [2, 2, 6, 6]

Output:

0.142857...

The boxes overlap in a 2x2 region (area 4). Each box has area 16, so union = 16 + 16 - 4 = 28. IoU = 4/28.

Input:

box_a = [0, 0, 2, 2] box_b = [3, 3, 5, 5]

Output:

0.0

The boxes do not overlap at all. Intersection area is zero.

Hint 1

The intersection rectangle's corners can be found using max/min of the input corners. Make sure the width and height cannot be negative.

Hint 2

Union is not just the sum of both areas. You need to subtract the intersection to avoid double-counting.

Requirements

  • Compute the intersection area from the overlap of the two rectangles
  • Compute the union using the inclusion-exclusion principle
  • Handle the case where boxes do not overlap
  • Support floating-point coordinates

Constraints

  • Boxes are [x1, y1, x2, y2] with x1 <= x2 and y1 <= y2
  • Coordinates can be integers or floats
  • -10000 <= coordinates <= 10000
  • Time limit: 300 ms
Try Similar Problems