Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

157. IoU

easy
GeneralGeneral
senior

Compute Intersection over Union (IoU) for two bounding boxes, a common metric in computer vision to measure overlap between a predicted box and a ground-truth box. IoU is defined as:

IoU(A,B)=∣A∩B∣∣A∪B∣=area(intersection)area(A)+area(B)−area(intersection)\text{IoU}(A, B) = \frac{|A \cap B|}{|A \cup B|} = \frac{\text{area}(\text{intersection})}{\text{area}(A) + \text{area}(B) - \text{area}(\text{intersection})}

Requirements

Implement the function

python

Rules:

  • Treat boxes as axis-aligned rectangles using corners [x1, y1, x2, y2].
  • Compute intersection width/height using max(0, ...) so non-overlapping boxes give intersection area 0.
  • Compute union area as area_a + area_b - intersection_area.
  • Return a single float IoU value.
  • Use only NumPy.

Example

python

Output:

python
Input Signature
ArgumentType
box_anp.ndarray
box_bnp.ndarray
Output Signature
Return NameType
valuefloat

Constraints

  • Input boxes are [x1,y1,x2,y2] floats

  • Use NumPy + Python only

  • Return scalar float IoU in [0,1]

Hint 1

Compute the overlap rectangle by taking max of the two top-left corners and min of the two bottom-right corners.

Hint 2

Intersection area is max(0, x_right-x_left) * max(0, y_bottom-y_top) so non-overlaps give 0.

Hint 3

IoU = inter_area / (area_a + area_b - inter_area); guard against zero union if boxes have zero area.

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
intersection-over-union
bounding-box
computational-geometry
numpy
16 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit