Tracking Objects Between Frames
Detections are a fresh guess every frame; driving needs objects that persist, with an identity and a velocity. Match detections to tracks with IoU, smooth and predict them with a constant-velocity Kalman filter, survive missed frames, and estimate the distance and time to collision with the car ahead.
Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the traffic world project, ready to run.OpenIn plain words
A detector looks at each picture on its own, as if it had never seen the road before. Tracking adds memory: this car is the same one as a moment ago, it is getting closer, and if it disappears behind a truck for a second, it has not vanished.
By the end of this topic you will be able to follow objects from frame to frame, estimate how fast the car ahead is closing in, and work out the time to a collision.
Start with: the demo Try it: tracking in the simulator.
Why a detector is not enough
A detector looks at each frame on its own. It may miss a car for one frame, its boxes jitter by a few pixels, and it cannot say "this is the same car as before". The planner needs more:
- Identity: car #3 is the same car it was a second ago.
- Velocity: is the car ahead slowing down? Is the pedestrian walking towards the road?
- Persistence: a car hidden for a moment behind a truck has not vanished.
Multi-object tracking adds these. The standard recipe, "tracking by detection" (for example SORT, Bewley et al., 2016), repeats three steps every frame: predict where each known object should be now, associate new detections with those predictions, and update each matched track.
Going deeper
The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.
The Kalman filter in one page
Each track keeps a state, the box's centre, width and height, and the centre's velocity, plus a covariance : how unsure it is about each number. Every frame:
moves each box by its velocity; says how much the motion can change unexpectedly; picks out the parts we measure (the box, not the velocity); says how noisy the detector is. The Kalman gain decides how much to trust the new measurement against the prediction. Nobody measures velocity directly: the filter infers it from how the measurements move. Part 3 of the course covers the Kalman filter in full; here you use it.
Association, births and deaths
To match detections with tracks, compute the IoU between every predicted box and every detection, then take pairs best-first, skipping any pair below 0.2 or whose track or detection is already used. (The optimal matching is the Hungarian algorithm; greedy matching is nearly as good when objects are well apart.)
- A detection with no track starts a new track with a new ID.
- A track with no detection keeps its prediction and counts a miss; after 5 misses in a row it is deleted.
Real trackers also use how objects look (an appearance embedding, as in DeepSORT), so two cars crossing do not swap IDs.
Code: a tracker you can run here
This runs in your browser. Two cars, a detector that misses 20% of boxes and adds jitter. Notice that the tracks keep their IDs through the misses, and that the velocity, never measured, is estimated well.
import numpy as np
rng = np.random.default_rng(0)
# Two cars seen by a camera for 40 frames. Each box is [x1, y1, x2, y2] in pixels.
# Car A drifts right and grows (getting closer); car B stays put. The "detector" misses 20% of
# boxes and adds a little jitter, like a real one.
def true_boxes(t):
a = [60 + 1.5 * t, 50, 80 + 2.0 * t, 65 + 0.3 * t]
b = [150, 55, 165, 66]
return [a, b]
def detect(t):
out = []
for box in true_boxes(t):
if rng.random() < 0.2:
continue # missed this frame
out.append(np.array(box) + rng.normal(0, 1.0, 4))
return out
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
class Track:
"""Constant-velocity Kalman filter. State: centre x, centre y, width, height, and the centre's velocity."""
F = np.eye(6); F[0, 4] = F[1, 5] = 1 # each frame: position += velocity
Hm = np.eye(4, 6) # we measure the box, not the velocity
Q = np.diag([1, 1, 1, 1, 0.5, 0.5]) # how much the motion can change unexpectedly
R = np.eye(4) * 4 # how noisy the detector is
next_id = 1
def __init__(self, box):
cx, cy, w, h = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2, box[2] - box[0], box[3] - box[1]
self.x = np.array([cx, cy, w, h, 0, 0], float)
self.P = np.diag([10, 10, 10, 10, 100, 100]).astype(float)
self.id, self.misses = Track.next_id, 0
Track.next_id += 1
def predict(self):
self.x = self.F @ self.x
self.P = self.F @ self.P @ self.F.T + self.Q
def update(self, box):
z = np.array([(box[0] + box[2]) / 2, (box[1] + box[3]) / 2, box[2] - box[0], box[3] - box[1]])
S = self.Hm @ self.P @ self.Hm.T + self.R
K = self.P @ self.Hm.T @ np.linalg.inv(S) # Kalman gain: how much to trust the measurement
self.x = self.x + K @ (z - self.Hm @ self.x)
self.P = (np.eye(6) - K @ self.Hm) @ self.P
self.misses = 0
def box(self):
cx, cy, w, h = self.x[:4]
return [cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2]
tracks = []
for t in range(40):
dets = detect(t)
for tr in tracks:
tr.predict()
# match detections to tracks, best overlap first
pairs = sorted(((iou(tr.box(), d), i, j) for i, tr in enumerate(tracks) for j, d in enumerate(dets)), reverse=True)
used_t, used_d = set(), set()
for score, i, j in pairs:
if score < 0.2 or i in used_t or j in used_d:
continue
tracks[i].update(dets[j]); used_t.add(i); used_d.add(j)
for i, tr in enumerate(tracks):
if i not in used_t:
tr.misses += 1 # not seen: keep the prediction for a few frames
tracks += [Track(d) for j, d in enumerate(dets) if j not in used_d]
tracks = [tr for tr in tracks if tr.misses <= 5]
for tr in tracks:
print(f"track #{tr.id}: centre ({tr.x[0]:.1f}, {tr.x[1]:.1f}), moving {tr.x[4]:+.2f}, {tr.x[5]:+.2f} px per frame")
print("true velocity of car A: +1.75, +0.15 px per frame; car B: 0, 0")Distance and time to collision
For the car ahead in our lane, the camera model turns the bottom of its box (where it touches the road) into a distance . The tracker smooths over time, which gives the closing speed . If the gap is shrinking, the time to collision is
Emergency braking systems act on TTC: a warning at around 2–3 seconds, full braking below about 1 second. A noisy single-frame distance would give wild TTC values; tracking is what makes it usable.
Try it: tracking in the simulator
Boxes come from the simulator's labels with misses and jitter added, as from a real detector. Each colour is one track ID. Raise the misses to 40% and watch the tracks hold. The panel shows the lead car's distance, closing speed and time to collision.
Interactive: this part runs in your browser.
Quiz
1. What does the Kalman filter estimate that the detector never measures?
2. What happens to a track when its object is not detected for one frame?
3. The car ahead is 20 m away and the gap shrinks by 10 m/s. What is the time to collision?
4. In the Kalman update, a larger R (noisier detector) makes the filter…
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- Bewley et al. (2016): Simple Online and Realtime Tracking (SORT) ↗ tracking by detection with a Kalman filter and IoU matching