Neural Mastery
← Practice
Bounding Box Intersection over Union (IoU)easy

Bounding Box Intersection over Union (IoU)

easy Neural Networks by Hand 15 min

NumPy allowed · plain Python earns 10 bonus points

Compute the Jaccard overlap index between two bounding boxes for object detection evaluation and non-maximum suppression.

Task

Implement iou_bounding_box(box_a, box_b): given two boxes formatted as [x1, y1, x2, y2] (with x1 <= x2 and y1 <= y2), compute the intersection rectangle coordinates: xA = max(x1_a, x1_b), yA = max(y1_a, y1_b), xB = min(x2_a, x2_b), yB = min(y2_a, y2_b). If xB <= xA or yB <= yA, the intersection area is 0.0. Otherwise inter = (xB - xA) * (yB - yA). The union is area_a + area_b - inter. Return inter / union rounded to 4 decimal places.

Function Signature

iou_bounding_box(box_a: list[float], box_b: list[float]) -> float

Examples

Example 1: Identical boxes IoU 1.0
Input: box_a = [0, 0, 10, 10] box_b = [0, 0, 10, 10]
Output: 1
Example 2: Partial overlap
Input: box_a = [0, 0, 2, 2] box_b = [1, 1, 3, 3]
Output: 0.1429
Example 3: Disjoint non-overlapping boxes
Input: box_a = [0, 0, 1, 1] box_b = [5, 5, 6, 6]
Output: 0

Constraints

  • box coordinates are non-negative floats
  • x1 <= x2 and y1 <= y2
Python3Saved ✓
def iou_bounding_box(box_a: list[float], box_b: list[float]) -> float:
"""Calculate Intersection over Union (IoU) between two 2D bounding boxes.

Args:
box_a: [x1, y1, x2, y2] coordinates where (x1, y1) is top-left and (x2, y2) is bottom-right.
box_b: [x1, y1, x2, y2] coordinates.

Returns:
IoU float in [0.0, 1.0] rounded to 4 decimal places.
"""
pass

Case 1: Identical boxes IoU 1.0
Input: box_a = [0, 0, 10, 10] box_b = [0, 0, 10, 10]
Expected: 1
Case 2: Partial overlap
Input: box_a = [0, 0, 2, 2] box_b = [1, 1, 3, 3]
Expected: 0.1429
Case 3: Disjoint non-overlapping boxes
Input: box_a = [0, 0, 1, 1] box_b = [5, 5, 6, 6]
Expected: 0