Intersection over Union

Computer VisionEasy+10 XP+10

Intersection over Union

Every object detector is scored with IoU: the overlap between a predicted box and the true box, divided by the total area the two of them cover.

IoU = area of intersection / area of union

Boxes arrive as [x1, y1, x2, y2] — top-left corner, then bottom-right.

Task: write iou(box_a, box_b) returning a float rounded to 4 decimal places.

The whole problem is the intersection rectangle. Its left edge is the rightmost of the two left edges, its right edge is the leftmost of the two right edges — and the same logic vertically. If that leaves a negative width or height, the boxes miss each other entirely and the intersection is 0, not a negative number.

  • Boxes that only touch along an edge overlap by zero area.
  • Remember the union counts the shared region once: area_a + area_b - intersection.
IoU
0.51
offset

Intersection over Union: the shared area divided by the total area covered. 1.0 is perfect, 0 is no overlap.

Examples

box_a = [0.0, 0.0, 2.0, 2.0]
box_b = [1.0, 1.0, 3.0, 3.0]
returns 0.1429
box_a = [0.0, 0.0, 2.0, 2.0]
box_b = [0.0, 0.0, 2.0, 2.0]
returns 1.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run