Sub topic 5
Matching detections to tracks with the Hungarian algorithm
This chapter assumes you can read NumPy code and know what a bounding box and IoU are. Earlier chapters covered the tracking-by-detection loop and IoU. Here we solve the step in the middle of that loop: deciding which detection in the current frame belongs to which existing track.
The association problem
At frame t you have N tracks, each with a predicted box, and M new detections. You must pair them. Three constraints define the problem:
- A track can take at most one detection.
- A detection can go to at most one track.
- Some tracks get no detection (the object was missed or left the scene), and some detections get no track (a new object appeared, or the detection is a false positive).
This is a bipartite matching problem. The two sides are the tracks and the detections. Every possible pair has a score, and you want the set of pairs with the best total score.
Why greedy matching fails
The obvious approach is to take the highest-IoU pair, remove that track and detection, and repeat. This is fast, but it can make a locally good choice that blocks a better global one.
Consider two tracks and two detections with these IoU values:
| Row | Detection 0 | Detection 1 |
|---|---|---|
| Track 0 | 0.60 | 0.50 |
| Track 1 | 0.55 | 0.00 |
Greedy takes 0.60 first (track 0 with detection 0). Track 1 is then left with detection 1, where the IoU is 0, so it is lost. The alternative pairs track 0 with detection 1 (0.50) and track 1 with detection 0 (0.55). That totals 1.05 against 0.60, and both tracks keep a detection.
The Hungarian algorithm
The Hungarian algorithm (also called Kuhn-Munkres) solves the linear assignment problem. Given a cost matrix, it finds the one-to-one assignment with the minimum total cost. It runs in O(n³) time, which is negligible for the tens or low hundreds of objects in a typical frame.
Because the algorithm minimizes cost, you convert similarity to cost. For IoU the usual choice is cost = 1 - IoU. Minimizing total cost then maximizes total IoU.
SciPy provides this as scipy.optimize.linear_sum_assignment. It accepts rectangular matrices. When N and M differ, it returns min(N, M) pairs, and the leftover rows or columns stay unassigned.
A working implementation
The function below follows the Topic Spine. It builds the IoU matrix, solves the assignment, and rejects pairs below a threshold.
import numpy as np
from scipy.optimize import linear_sum_assignment
def iou_matrix(boxes_a, boxes_b):
"""Pairwise IoU. Boxes are [x1, y1, x2, y2]. Returns an (N, M) array."""
a = np.asarray(boxes_a, dtype=float).reshape(-1, 1, 4)
b = np.asarray(boxes_b, dtype=float).reshape(1, -1, 4)
x1 = np.maximum(a[..., 0], b[..., 0])
y1 = np.maximum(a[..., 1], b[..., 1])
x2 = np.minimum(a[..., 2], b[..., 2])
y2 = np.minimum(a[..., 3], b[..., 3])
inter = np.clip(x2 - x1, 0, None) * np.clip(y2 - y1, 0, None)
area_a = (a[..., 2] - a[..., 0]) * (a[..., 3] - a[..., 1])
area_b = (b[..., 2] - b[..., 0]) * (b[..., 3] - b[..., 1])
union = area_a + area_b - inter
return inter / np.maximum(union, 1e-9)
def match(track_boxes, det_boxes, iou_thresh=0.3):
"""Return (matches, unmatched_track_indices, unmatched_detection_indices)."""
if len(track_boxes) == 0 or len(det_boxes) == 0:
return [], list(range(len(track_boxes))), list(range(len(det_boxes)))
iou = iou_matrix(track_boxes, det_boxes)
rows, cols = linear_sum_assignment(1.0 - iou) # minimise total cost
matches = [(r, c) for r, c in zip(rows, cols) if iou[r, c] >= iou_thresh]
matched_t = {r for r, _ in matches}
matched_d = {c for _, c in matches}
unmatched_t = [i for i in range(len(track_boxes)) if i not in matched_t]
unmatched_d = [j for j in range(len(det_boxes)) if j not in matched_d]
return matches, unmatched_t, unmatched_d
tracks = [[10, 10, 50, 50], [100, 100, 150, 160]]
dets = [[102, 104, 152, 162], [12, 11, 52, 52], [300, 300, 340, 340]]
print(match(tracks, dets))Here track 0 has IoU about 0.84 with detection 1, and track 1 has IoU about 0.84 with detection 0. Detection 2 is far from every track. The result is two matches (0 with 1, and 1 with 0), no unmatched tracks, and detection 2 unmatched. Detection 2 will start a new track. Recent NumPy versions print the indices as np.int64(...), but the values are the same.
The gating threshold
The solver always returns a full assignment, even when a pair makes no physical sense. If track 1 has no good detection, the solver still gives it the least bad leftover. The IoU threshold (often 0.3) is a gate that rejects such pairs. Without it, a track would jump to a detection on the other side of the image.
The threshold trades two errors:
- Too high: fast-moving objects or poor motion predictions fall below the gate. Real matches are rejected, tracks accumulate misses, and new IDs get created (ID switches).
- Too low: a track can latch onto a neighboring object that barely overlaps it, which also causes ID switches.
Filtering after the solve can hide valid matches
The match function above gates after solving. That is simple, but it can lose a valid match. Take the IoU matrix below with a threshold of 0.3:
| Row | Detection 0 | Detection 1 |
|---|---|---|
| Track 0 | 0.35 | 0.20 |
| Track 1 | 0.25 | 0.05 |
The pair (0,0) with (1,1) totals 0.40. The pair (0,1) with (1,0) totals 0.45, so the solver prefers it. Both of its pairs are below 0.3, so post-filtering rejects both, and the valid 0.35 match is lost. The fix is to make forbidden pairs very expensive before solving, so the solver avoids them when it can.
import numpy as np
from scipy.optimize import linear_sum_assignment
def match_post_filter(iou, thresh=0.3):
rows, cols = linear_sum_assignment(1.0 - iou)
return [(int(r), int(c)) for r, c in zip(rows, cols) if iou[r, c] >= thresh]
def match_gated(iou, thresh=0.3, big=1e6):
cost = np.where(iou >= thresh, 1.0 - iou, big) # forbid weak pairs
rows, cols = linear_sum_assignment(cost)
return [(int(r), int(c)) for r, c in zip(rows, cols) if iou[r, c] >= thresh]
iou = np.array([[0.35, 0.20],
[0.25, 0.05]])
print(match_post_filter(iou)) # []
print(match_gated(iou)) # [(0, 0)]The gated version still needs the final filter. Forbidden pairs can still appear in the solver's output when no allowed pair exists for that row, and the filter removes them. Use a large finite number such as 1e6 rather than np.inf. SciPy raises an error when no feasible assignment exists for an infinite-cost matrix, and a finite value avoids that.
Edge cases
- No tracks or no detections. The solver can handle empty input in some SciPy versions, but an explicit early return, as in
match, is clearer. At the first frame every detection is unmatched and becomes a new track. - Ties. When two assignments have equal total cost, the solver picks one deterministically but arbitrarily. Identical overlapping boxes are a real source of ties. Do not rely on tie-breaking.
- Scale of the cost. Hungarian only cares about total cost, so
1 - IoUand-IoUgive the same assignment. A cost built by combining terms, such as motion and appearance, must have terms on comparable scales, or one term will dominate. - Crowds. With heavy overlap, many IoU values are nonzero and similar. Total-cost optimization then gives unstable choices, which is where extra cues such as appearance help (covered in later chapters).
- Speed. The O(n³) cost is rarely a bottleneck, because the detector dominates the runtime. For very large N, specialized solvers such as the
lappackage are faster than SciPy.
What happens after the match
The three outputs drive the track lifecycle covered in the next chapters:
- Matched pairs update the track's state and reset its miss counter.
- Unmatched tracks increment their miss counter. They are deleted after too many consecutive misses.
- Unmatched detections start new tracks, which are usually held as tentative until they match a few times.
Exercise
Two tracks and two detections have this IoU matrix, and the threshold is 0.4: [[0.50, 0.45], [0.48, 0.10]]. What does greedy matching return, what does Hungarian matching on 1 - IoU return, and which one keeps more tracks matched?
Show answer
Greedy takes 0.50 first (track 0 with detection 0). Track 1 then has only detection 1, with IoU 0.10, which is below 0.4, so it is rejected. Greedy keeps one match. Hungarian compares totals: (0,0) plus (1,1) is 0.60, and (0,1) plus (1,0) is 0.93. It picks the second assignment, and both pairs pass the 0.4 gate (0.45 and 0.48). Hungarian keeps two matches against greedy's one.
Exercise
Why does match_gated set weak pairs to a large finite cost instead of removing them, and why does it still filter the output?
Show answer
The solver needs a complete cost matrix, so weak pairs get a large cost that steers it toward allowed pairs when they exist. This avoids the failure where the solver picks an assignment of two sub-threshold pairs and thereby discards a valid match. The output filter is still needed because, when a row has no allowed column, the solver must still assign it something. That assignment carries the large cost and has to be removed.