Sub topic 3
Measuring overlap with IoU
This chapter assumes you know bounding boxes in [x1, y1, x2, y2] form, basic NumPy broadcasting, and the idea of a tracker matching detections to tracks. Intersection over union (IoU) is the similarity score that most trackers use for that matching. It is simple, but its limits shape tracker behavior. Many "mysterious" ID switches come from them.
What IoU computes
IoU compares two boxes by the share of their combined area that they have in common:
IoU(A, B) = area(A ∩ B) / area(A ∪ B)The result lies in [0, 1]. A value of 1 means the boxes are identical. A value of 0 means they do not overlap, or only touch along an edge. The union is computed as area(A) + area(B) - area(A ∩ B), because adding the two areas counts the intersection twice.
For axis-aligned boxes the intersection is itself a box:
- Its left edge is
max(A.x1, B.x1). - Its right edge is
min(A.x2, B.x2). - Its top and bottom edges follow the same pattern with y.
- Its width and height are clipped at zero, so disjoint boxes get zero area instead of a negative one.
A worked case: A is [0, 0, 10, 10] and B is [5, 5, 15, 15]. The intersection is [5, 5, 10, 10], which has area 25. The union is 100 + 100 - 25 = 175. IoU is 25 / 175 ≈ 0.143.
A vectorized implementation
A tracker needs IoU for every track-detection pair in every frame. The pairwise matrix is therefore the useful form, not the scalar function. Broadcasting a (N, 1, 4) array against a (1, M, 4) array produces an (N, M) result with no Python loops.
import numpy as np
def _pairwise(boxes_a, boxes_b):
"""Return broadcast arrays a, b and (N, M) arrays inter and union."""
a = np.asarray(boxes_a, dtype=float).reshape(-1, 1, 4)
b = np.asarray(boxes_b, dtype=float).reshape(1, -1, 4)
iw = np.clip(np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]), 0, None)
ih = np.clip(np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]), 0, None)
inter = iw * ih
area_a = np.clip(a[..., 2] - a[..., 0], 0, None) * np.clip(a[..., 3] - a[..., 1], 0, None)
area_b = np.clip(b[..., 2] - b[..., 0], 0, None) * np.clip(b[..., 3] - b[..., 1], 0, None)
return a, b, inter, area_a + area_b - inter
def iou_matrix(boxes_a, boxes_b):
"""Pairwise IoU for [x1, y1, x2, y2] boxes. Returns an (N, M) array."""
_, _, inter, union = _pairwise(boxes_a, boxes_b)
return inter / np.maximum(union, 1e-9)
def giou_matrix(boxes_a, boxes_b):
"""Generalized IoU: IoU minus the fraction of the enclosing box not covered by the union."""
a, b, inter, union = _pairwise(boxes_a, boxes_b)
cw = np.maximum(a[..., 2], b[..., 2]) - np.minimum(a[..., 0], b[..., 0])
ch = np.maximum(a[..., 3], b[..., 3]) - np.minimum(a[..., 1], b[..., 1])
enclosing = cw * ch
iou = inter / np.maximum(union, 1e-9)
return iou - (enclosing - union) / np.maximum(enclosing, 1e-9)
# Same 3-pixel shift, two object sizes.
print(np.round(iou_matrix([[0, 0, 10, 10]], [[3, 0, 13, 10]]), 3)) # [[0.538]]
print(np.round(iou_matrix([[0, 0, 100, 100]], [[3, 0, 103, 100]]), 3)) # [[0.942]]
# Two disjoint candidates, one near and one far.
near_far = [[20, 0, 30, 10], [40, 0, 50, 10]]
print(iou_matrix([[0, 0, 10, 10]], near_far)) # [[0. 0.]]
print(np.round(giou_matrix([[0, 0, 10, 10]], near_far), 3)) # [[-0.333 -0.6]]Three details in this code matter in practice:
- Clipping at zero. Without
np.clip, two boxes far apart produce a negative width, and two negative sizes multiply into a positive "intersection." This is a classic silent bug. - The
1e-9floor. Zero-area boxes, such as a degenerate detection withx1 == x2, would otherwise divide by zero. Their IoU becomes 0. - Validity of inputs. Clipping the areas hides boxes with
x2 < x1, which score as zero-area. If your detector can emit them, fix the coordinates upstream. Do not rely on IoU to reveal the problem.
Coordinate formats
Detectors disagree on box format, and a format mismatch gives plausible-looking but wrong IoU values. The common formats are:
| Format | Fields | Typical source |
|---|---|---|
| xyxy | left, top, right, bottom | Many detector outputs, the code above |
| xywh | left, top, width, height | COCO annotations, MOT challenge files |
| cxcywh | center x, center y, width, height | YOLO-style normalized labels, Kalman filter state |
Convert once at the boundary of your tracker, and keep one internal format. Normalized coordinates (0 to 1) work for IoU, but only if both boxes use the same image size. Mixing pixels with normalized values gives IoU near 0 for every pair.
What IoU means as a tracking signal
In a tracker, IoU answers one question: how well does this detection fit where I expect the track to be? Two properties follow from the formula.
IoU is scale-sensitive. The same absolute shift costs small boxes much more than large ones. The code above shows that a 3-pixel shift drops a 10-pixel box to IoU 0.538, while a 100-pixel box stays at 0.942. A distant pedestrian that is 12 pixels wide can lose all overlap in one frame at moderate speed. A nearby pedestrian rarely does. A single global threshold therefore treats near and far objects differently.
IoU is zero beyond contact. Once two boxes stop overlapping, IoU is 0 whether they are one pixel apart or the full image apart. The cost surface is flat there, so the matcher has no signal for pairing a fast-moving object with its detection. This is why trackers compare detections against the predicted box from a motion model and not the box from the last frame. Later chapters cover that prediction step.
Turning IoU into an association cost
The Hungarian algorithm minimizes total cost, and IoU is a similarity to maximize. The standard conversion is cost = 1 - IoU. After solving, you reject any assigned pair whose IoU falls below a threshold. This rejection is called gating. Typical thresholds are about 0.3 for SORT-style trackers.
Gating matters because the solver always returns a complete assignment of the smaller side. Without gating, a track with no true match would be paired with whatever detection is left over, even a distant one. Rejecting low-IoU pairs leaves those tracks and detections unmatched, so the track lifecycle logic can handle them.
The choice of threshold trades one error for another:
- A high threshold (for example 0.5) rejects more true matches when objects move fast or detections are noisy. Tracks go unmatched and fragment.
- A low threshold (for example 0.1) accepts more wrong pairings in crowds. This causes identity swaps.
Alternatives when IoU runs out of signal
IoU is not the only box-overlap measure. A few variants address its weak points:
- GIoU subtracts the share of the smallest enclosing box that the union does not cover. As the code above shows, it gives disjoint boxes different values (-0.333 for the near box and -0.6 for the far one) where plain IoU gives 0 for both. It ranges from -1 to 1. For association, you would shift and rescale it before using it as a cost.
- DIoU and CIoU add terms for center distance and aspect ratio. They were designed as training losses for detectors, though some trackers use them for matching.
- Center distance, normalized by box size, gives a nonzero signal for boxes that do not overlap. It is a common fallback for small, fast objects.
- Buffered IoU enlarges both boxes by a margin before computing IoU. A few trackers use it to tolerate fast motion without changing the rest of the pipeline.
None of these replaces appearance cues when objects cross or overlap heavily. If two people occupy nearly the same box region, any geometric overlap score is ambiguous. Later chapters on re-identification address this.
Common errors
- Wrong format. Passing xywh boxes to an xyxy IoU function produces nonsense that still lies in [0, 1]. Check by testing a box against itself, which must return 1.
- Missing clip. Omitting the zero clip yields positive IoU for disjoint boxes in opposite corners.
- Comparing to the stale box. Computing IoU against the last observed box instead of a predicted box makes fast objects drop out of matching.
- Wrong shape. Box lists passed as
(4,)instead of(1, 4). Thereshape(-1, 1, 4)in the code above handles a flat list of one box only if it has exactly four numbers, so always pass a list of boxes. - One threshold for all scales. In scenes with strong perspective, consider a size-aware rule or an additional distance cue.
Exercise
A track's predicted box is [0, 0, 20, 20] and a detection is [5, 0, 25, 20]. Compute the IoU. If the gating threshold is 0.7, is the pair kept?
Show answer
The intersection is [5, 0, 20, 20], with width 15 and height 20, so area 300. Each box has area 400, so the union is 400 + 400 - 300 = 500. IoU is 300 / 500 = 0.6. This is below 0.7, so the pair is rejected, and the track and detection stay unmatched.
Exercise
Two disjoint detections both have IoU 0 with a track's predicted box, but one is 5 pixels away and the other is 500 pixels away. Why can an IoU-based cost matrix not tell them apart, and name one measure that can?
Show answer
Plain IoU is exactly 0 for any non-overlapping pair, so both entries get cost 1 - 0 = 1 and the cost surface is flat. GIoU, or a normalized center distance, gives the nearer box a better score because it depends on how far apart the boxes are.