Sub topic 7
Creating, confirming, and deleting tracks
This chapter assumes you know the pieces from the earlier chapters. You should be able to compute IoU between boxes and run the Hungarian matcher with an IoU threshold. You should also know that a Kalman filter predicts each track's next position. Here we cover what a tracker does with the matcher's three outputs: matched pairs, unmatched tracks, and unmatched detections.
Why tracks need a lifecycle
The matcher answers one question per frame: which detections belong to which existing tracks. It cannot decide what an unmatched detection means. The detection could be a new object entering the scene, or it could be a false positive that will vanish next frame. It also cannot decide what an unmatched track means. The object could have left the scene, or it could be hidden behind a pole for a few frames.
A track lifecycle is the set of rules that settles these questions over time. It trades two kinds of error against each other:
- Spurious tracks. If you trust every detection at once, one-frame false positives become tracks. They show up as phantom IDs and inflate false-positive counts.
- Fragmentation and ID switches. If you delete tracks too quickly, a briefly occluded object loses its identity. When it reappears it gets a new ID.
Every parameter in this chapter moves the tracker along that trade-off.
The four states
Most trackers use some version of these states:
| State | Meaning | Reported to the user? |
|---|---|---|
| Tentative | Created from an unmatched detection. Not yet trusted. | No |
| Active (confirmed) | Matched often enough to be believed, and matched in the latest frame. | Yes |
| Coasting (lost) | Confirmed earlier, but missed in recent frames. Position comes from the motion model. | Depends on the implementation |
| Deleted | Removed. Its ID is never reused. | No |
Creation
Every unmatched detection becomes a new tentative track. It gets a fresh ID, one hit, zero misses, and an initial state. In a Kalman-based tracker the position is the detection's box and the velocity starts at zero with a large uncertainty. The earlier Kalman example set the velocity variance to 100 for this reason. The first match or two will correct the velocity quickly.
IDs should come from a counter that only goes up. Reusing a deleted track's ID makes the output look like one object that teleported. It also breaks any downstream code that keys data by ID.
Confirmation
A tentative track is confirmed after n_init matched detections (SORT calls this min_hits, and both default to 3). The rule exists because real objects persist and most false positives do not. A detector's noise rarely lands on the same spot, with a similar size, in three consecutive frames.
A related rule is that tentative tracks are deleted on their first miss. That rule is strict, but it is cheap and works well. A tentative track has no history to justify waiting. Keeping it around only gives it chances to steal a real detection in a later frame.
Confirmation has a price: latency. With n_init = 3, a real object gets no reported ID for its first two frames. For offline evaluation you can backfill those frames after confirmation. For a live system you accept the delay, or you lower n_init and tolerate more phantom tracks.
Coasting and deletion
When a confirmed track has no match, it keeps living, because a missed detection is much more common than a vanished object. Occlusion, motion blur, and a confidence score just under the detector's threshold all produce gaps. The track keeps a misses counter. Any match resets it to zero. Once misses exceeds max_age, the track is deleted.
While coasting, the position comes from the motion model, not from a detection. The Kalman predict() step runs every frame with no update(). Two consequences follow:
- The predicted box drifts along the last estimated velocity. If the object actually stopped or turned, the prediction diverges from reality.
- The covariance
Pgrows with each prediction, so the track's uncertainty grows. Trackers that gate on Mahalanobis distance, like DeepSORT, therefore accept farther-away detections for long-coasting tracks.
SORT and its relatives differ widely in this setting. SORT uses max_age = 1, so it barely coasts at all. DeepSORT uses max_age = 30, and ByteTrack uses a track buffer of 30 frames by default. These are frame counts, so they mean different durations at different frame rates. Thirty frames is one second at 30 fps and about three seconds at 10 fps.
A runnable lifecycle
The code below is self-contained. It repeats the IoU matcher from earlier so you can run it as one file. It then adds the lifecycle states. To keep the focus on state transitions, a coasting track keeps its last box. A real tracker would use the Kalman prediction here.
from itertools import count
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])
return inter / np.maximum(area_a + area_b - inter, 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)
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
class Track:
_ids = count(1) # IDs only increase and are never reused
def __init__(self, box):
self.id = next(Track._ids)
self.box = box
self.hits = 1
self.misses = 0
self.confirmed = False
@property
def state(self):
if not self.confirmed:
return "tentative"
return "coasting" if self.misses > 0 else "active"
def step(tracks, detections, iou_thresh=0.3, n_init=3, max_age=5):
"""Advance the tracker by one frame and return the surviving tracks."""
matches, unmatched_t, unmatched_d = match(
[t.box for t in tracks], detections, iou_thresh
)
for ti, di in matches:
t = tracks[ti]
t.box = detections[di]
t.hits += 1
t.misses = 0
if t.hits >= n_init:
t.confirmed = True
for ti in unmatched_t:
tracks[ti].misses += 1
for di in unmatched_d:
tracks.append(Track(detections[di]))
return [
t for t in tracks
if (t.confirmed and t.misses <= max_age) # coasting allowed
or (not t.confirmed and t.misses == 0) # tentative: no second chance
]
frames = [
[[10, 10, 50, 50]],
[[14, 10, 54, 50]],
[[18, 10, 58, 50]],
[], # missed detection
[[26, 11, 66, 51]], # object is back
[[300, 300, 340, 340]], # one-frame false positive
[],
]
tracks = []
for i, dets in enumerate(frames):
tracks = step(tracks, dets)
print(i, [(t.id, t.state, t.hits, t.misses) for t in tracks])Running it prints:
0 [(1, 'tentative', 1, 0)]
1 [(1, 'tentative', 2, 0)]
2 [(1, 'active', 3, 0)]
3 [(1, 'coasting', 3, 1)]
4 [(1, 'active', 4, 0)]
5 [(1, 'coasting', 4, 1), (2, 'tentative', 1, 0)]
6 [(1, 'coasting', 4, 2)]Track 1 is confirmed at frame 2. It survives the gap at frame 3 and keeps ID 1 when the object returns at frame 4. The false positive at frame 5 becomes tentative track 2 and is deleted at frame 6, before it is ever confirmed.
Choosing the parameters
| Parameter | Raise it to... | Cost of raising it |
|---|---|---|
| `n_init` | Suppress more false positives | More latency before an ID is reported. Short-lived real objects are never confirmed. |
| `max_age` | Survive longer occlusions | More ghost tracks after objects leave. Ghosts can capture new detections near their last position. |
| `iou_thresh` | Reject weak matches | Fast-moving objects fail to match and fragment. |
Three points matter in practice:
- Scale
max_agewith the frame rate. Decide how many seconds of occlusion you want to survive, then multiply by the frame rate. - Match
max_ageto the motion model. A coasting track is only useful if its predicted position stays close to the truth. A constant-velocity prediction is reasonable for about a second of steady motion. It is a poor guess for a pedestrian who stops. Long coasting with a weak motion model produces ID switches. - Exit zones. Objects that leave through the frame edge should not coast for 30 frames. Some systems delete a track right away if its last box touched the image border.
Edge cases to handle
- Two tracks and one detection. The Hungarian algorithm assigns the detection to only one track. The other track gets a miss, even though both may overlap it. This is correct, but it is a common cause of a track flipping to coasting during crossings.
- A track whose box leaves the frame. Clip it or delete it. Otherwise IoU against a box partly outside the image behaves oddly.
- Reporting. Decide whether coasting tracks appear in the output. Reporting them keeps boxes visible through gaps. It also reports positions that no detection supports, and metrics count those as false positives if the object is truly gone.
- Revival. Some trackers keep deleted tracks in a separate pool of lost tracks, so an appearance embedding can revive them later. That is the purpose of re-identification, covered in a later chapter.
Exercise
A camera runs at 25 fps. Pedestrians pass behind a bus stop and can be hidden for up to 1.2 seconds. Using the rule "delete when misses > maxage", what is the smallest maxage that keeps their IDs? Name one downside of setting it much higher.
Show answer
1.2 s × 25 fps = 30 frames, so max_age must be at least 30. A track with 30 consecutive misses still survives, and it is deleted only when misses reaches 31. If the pedestrian reappears on the next frame, the track matches and keeps its ID. Setting it much higher keeps ghost tracks of people who have left, and those ghosts can capture new detections and cause ID switches. It also adds spurious boxes if coasting tracks are reported.
Exercise
In the runnable example, change n_init to 2 and rerun the same frames. At which frame is track 1 first confirmed, and does the one-frame false positive at frame 5 still get deleted?
Show answer
Track 1 is confirmed at frame 1, because it has two hits then. The false positive at frame 5 still creates tentative track 2 with one hit. It has no match at frame 6, so it is deleted. Lowering n_init reduces confirmation latency, but a false positive that repeated for two frames in a row would now be confirmed.