879. IoU matrix for two sets of boxes
Why it matters IoU matrices drive non-max suppression, anchor matching and detection metrics like mAP. Production detectors compute millions of them per batch.
iou_matrix(a, b) returns the intersection over union between every box in a and every box in b. Boxes are [x1, y1, x2, y2] with x1 <= x2 and y1 <= y2. Intersection width and height are clipped at 0. If the union area is 0, the IoU is 0.0.
Inputs: a is a list or ndarray of shape (n, 4), b of shape (m, 4).
Return an ndarray of floats with shape (n, m). No rounding.
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 50 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def iou_matrix(a, b)Example 1
Input: iou_matrix([[0.0, 0.0, 2.0, 2.0]], [[1.0, 1.0, 3.0, 3.0], [0.0, 0.0, 2.0, 2.0], [5.0, 5.0, 6.0, 6.0]])
Output: [[0.1429, 1.0, 0.0]]
Example 2
Input: a = [[0.0, 0.0, 0.0, 0.0]], b = [[0.0, 0.0, 0.0, 0.0]]
Output: [[0.0]]
Constraints
bhas shape(m, 4)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Index columns with a[:, None, 0] and b[None, :, 0].
Hint 2
Clip intersection width and height at 0.
Hint 3
Use np.where to avoid dividing by zero.
Common mistakes
- Forgetting the clip, so far apart boxes get positive intersection.
- Subtracting the intersection twice in the union.
- Letting 0 / 0 produce nan.
Understand the idea
Broadcast a as (n, 1) and b as (1, m) for each coordinate. The intersection corners are the max of the top-left corners and the min of the bottom-right corners; clip widths and heights at 0 for boxes that do not overlap. Guard the division so zero-area unions give 0.0 instead of nan.
Shapes and data flow
a: (n, 4), b: (m, 4). Every intermediate: (n, m).