Compute IoU and generalized IoU for box pairs

Why it matters GIoU and its relatives DIoU and CIoU are the box losses in YOLOv5-era detectors and DETR.

Plain IoU is 0 for every pair of boxes that do not touch, so it gives no learning signal there. Generalized IoU adds a penalty based on the smallest box enclosing both.

Write giou(a, b). a and b are (n, 4) arrays of (x1, y1, x2, y2) boxes with positive area, compared row by row (pair i is a[i] with b[i]). Return (iou, g), both (n,) float arrays, where g = iou - (C - U) / C with U the union area and C the area of the smallest axis-aligned box that encloses both.

Signaturedef giou(a, b)

Example

a = [[0, 0, 2, 2]], b = [[3, 0, 5, 2]] gives iou [0] and g [-0.2]: the enclosing box is 5 x 2 = 10 and the union is 8.

Understand the idea

IoU measures overlap: intersection divided by union. If two boxes do not touch, IoU is 0 whether they are 1 pixel apart or across the image, so a model gets no hint which way to move. GIoU looks at the smallest box that contains both. If a lot of that enclosing box is empty, the boxes are far apart and GIoU goes negative. Like judging two people not just by whether they hold hands, but by how much room it takes to fit both in one photo.

Tiny example: boxes (0, 0, 2, 2) and (3, 0, 5, 2). No overlap, union 4 + 4 = 8. Enclosing box (0, 0, 5, 2) has area 10. GIoU = 0 - (10 - 8) / 10 = -0.2.

Rule: GIoU = IoU - (C - U) / C; the loss is 1 - GIoU.

DETR uses a GIoU term in its matching cost and loss.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplegiou([[0.0, 0.0, 2.0, 2.0]], [[3.0, 0.0, 5.0, 2.0]])
  • Sample 2: overlap and containgiou([[0.0, 0.0, 2.0, 2.0], [0.0, 0.0, 4.0, 4.0], [0.0, 0.0, 1.0, 1.0]], [[1.0, 1.0, 3.0, 3.0], [1.0, 1.0, ...