Sub topic 6
Predicting motion with a Kalman filter
What this chapter assumes
You should know basic NumPy, matrix multiplication, and Gaussian distributions (mean and variance). You should also know the tracking-by-detection loop: detect objects in each frame, then match detections to existing tracks. This chapter covers the motion model, which gives the matcher a predicted position for each track before the detections are matched.
Why a tracker needs a motion model
Suppose a car was at x = 100 in the last frame and at x = 103 in the frame before that. Without a motion model, the tracker compares the old box with the new detections. That works when objects move slowly. When an object moves quickly, or when a detection is missing for a few frames, the old box no longer overlaps the object, and its IoU with the right detection can fall to zero.
A motion model predicts where each track should be in the current frame. The tracker then matches detections against the prediction instead of the stale box. The Kalman filter is the standard choice. It also tracks how uncertain the prediction is and blends prediction and measurement in proportion to that uncertainty.
The state and the two models
The filter keeps a state vector and a covariance matrix.
- The state
xholds the quantities you want to estimate. Here it is[cx, cy, vx, vy]: the box center and its velocity in pixels per frame. - The covariance
Pis a 4×4 matrix. Its diagonal holds the variance of each state entry, and its off-diagonal entries record how the errors are correlated.
Two linear models connect the state to the world.
| Symbol | Name | Role in the constant-velocity tracker |
|---|---|---|
| `F` | Transition matrix | Moves the center by velocity times `dt` and keeps velocity unchanged |
| `H` | Measurement matrix | Picks `cx, cy` out of the state, because the detector reports no velocity |
| `Q` | Process noise | How much the real motion can deviate from constant velocity per frame |
| `R` | Measurement noise | How noisy the detector's box centers are, in pixels squared |
The velocity is a hidden variable. The detector never reports it, and the filter infers it from how the measured center changes from frame to frame.
The predict step
Before looking at the detections of a new frame, the filter pushes the state forward:
x = F x
P = F P Fᵀ + QThe state moves along its velocity. The covariance grows by Q, and F P Fᵀ also spreads position uncertainty according to velocity uncertainty. A track with a poorly known velocity gets a quickly growing position uncertainty. This is the correct behavior: the longer the filter predicts without a measurement, the less it should trust its own output.
The update step
When a detection is matched to the track, the filter corrects the prediction:
y = z - H x (innovation: measurement minus prediction)
S = H P Hᵀ + R (innovation covariance)
K = P Hᵀ S⁻¹ (Kalman gain)
x = x + K y
P = (I - K H) PThe gain K decides how far to move toward the measurement. If P is large relative to R, the filter trusts the detection and K is large. If R is large, the filter trusts its prediction and K is small. The gain also feeds the position error into the velocity estimate through the correlations in P. That is how the filter learns velocity without ever measuring it.
A working implementation
The code below implements the filter, feeds it three measurements, and then predicts three frames with no measurement. It prints the position variance after each predicted frame so you can watch the uncertainty grow.
import numpy as np
class ConstantVelocityKalman:
"""State is [cx, cy, vx, vy]; the measurement is the box center [cx, cy]."""
def __init__(self, cx, cy, dt=1.0):
self.x = np.array([cx, cy, 0.0, 0.0])
self.P = np.diag([10.0, 10.0, 100.0, 100.0]) # large velocity uncertainty
self.F = np.array([[1, 0, dt, 0],
[0, 1, 0, dt],
[0, 0, 1, 0],
[0, 0, 0, 1]], dtype=float)
self.H = np.array([[1, 0, 0, 0],
[0, 1, 0, 0]], dtype=float)
self.Q = np.eye(4) * 0.01 # process noise
self.R = np.eye(2) * 1.0 # measurement noise
def predict(self):
self.x = self.F @ self.x
self.P = self.F @ self.P @ self.F.T + self.Q
return self.x[:2]
def update(self, z):
y = np.asarray(z, dtype=float) - self.H @ self.x # innovation
S = self.H @ self.P @ self.H.T + self.R
K = self.P @ self.H.T @ np.linalg.inv(S) # Kalman gain
self.x = self.x + K @ y
self.P = (np.eye(4) - K @ self.H) @ self.P
kf = ConstantVelocityKalman(100.0, 50.0)
for z in [(103, 50), (106, 51), (109, 51)]:
kf.predict()
kf.update(z)
print("state after 3 updates:", kf.x) # vx is positive
for frame in range(3): # the detector misses the object for three frames
center = kf.predict()
print("coasting", frame + 1, center, "position variance", kf.P[0, 0])Read the output in two parts. After the three updates, the x velocity is positive and roughly matches the 3 pixels per frame in the data. During coasting, the predicted center keeps advancing at that velocity, and the position variance rises each frame.
Choosing Q, R, and the initial P
These three settings decide how the filter behaves, and none of them has a universal value.
- Initial
P. A new track has no velocity estimate, so the velocity variance starts large (100 in the code, against 10 for position). The first few updates then correct the velocity quickly. If you start it small, the filter will ignore early evidence of motion. R. Set it from the detector's typical center error. LargerRsmooths the track more but lags behind real turns.Q. LargerQlets the filter follow maneuvers such as sudden stops. SmallerQtrusts constant velocity and gives smoother tracks that are slow to react.
The ratio of Q to R matters more than either value alone. Tune it on validation video by watching the ID-switch count, not by eye on one clip.
From centers to boxes
The example tracks only the center. A tracker needs boxes to compute IoU, so the state must also describe the box size. SORT uses a seven-dimensional state: center (u, v), area s, aspect ratio r, and velocities for the first three. The aspect ratio has no velocity term because it is assumed constant. Tracking area and ratio instead of width and height keeps the size dynamics simple and reduces the coupling between them. The predicted box is rebuilt from the state, and that box goes into the IoU matrix.
A common bug is predicting a negative area after a long coast with a negative area velocity. Clamp the predicted area to a small positive number, or zero the area velocity when s + vs would fall below zero.
Coasting and the lifecycle
When no detection matches a track, the tracker skips update and keeps the result of predict. This is called coasting. The track continues to move along its estimated velocity, so when the object reappears it often lands inside the predicted box and the match succeeds. The variance printed in the example shows why coasting cannot go on forever. After enough frames the uncertainty is so large that the prediction carries little information. The lifecycle logic from the previous chapter deletes a track after a fixed number of consecutive misses.
Gotchas
- Constant velocity is an approximation. Pedestrians stop and turn, and vehicles brake. The filter lags at these moments, and the innovation
ybecomes large. If you see many ID switches during maneuvers, raiseQbefore changing anything else. - Camera motion breaks the model. If the camera pans, every object appears to move together, and the learned velocities describe the camera as much as the objects. Trackers that handle this estimate a global image motion between frames and warp the predicted boxes before matching.
- Variable frame rates.
dtmust match the real time between frames. If frames are dropped and you keepdt=1, velocities in pixels per frame are wrong. Either buildFfrom the actual timestamp gap or work in pixels per second. - Numerical stability. The update
P = (I - K H) Pcan lose symmetry or positive definiteness through rounding. Production code often uses the Joseph form,P = (I - K H) P (I - K H)ᵀ + K R Kᵀ, or symmetrizesPafter each step. - Matrix inversion.
np.linalg.inv(S)is fine for a 2×2 matrix. For larger measurement vectors, prefernp.linalg.solve. - Use the prediction, not the filtered state, for matching. The matching step uses the predicted box from this frame's
predict, because the detections of this frame have not been used yet.
How the filter connects to association
The filter supplies the predicted boxes. The matching step compares them with the new detections through the IoU matrix and the Hungarian algorithm, using the same gating threshold as before. Matched pairs call update. Unmatched tracks coast, and unmatched detections create new tracks with a fresh filter. Each of the three parts depends on the others: without prediction the IoU matrix fails on fast objects, and without matching the filter has no measurements to correct itself with.
Exercise
A track has been matched for many frames and then the detector misses the object for 4 frames. Name two things that happen to the filter's state and covariance during those frames, and say why a track that coasts for 40 frames is risky to match against new detections.
Show answer
In each missed frame only predict runs. The center keeps moving at the last estimated velocity, and the covariance P grows because Q is added every frame and velocity uncertainty is spread into position. After 40 frames the position variance is very large and the constant-velocity assumption has probably failed, so the predicted box is likely far from the real object. Matching against it can produce a wrong match or no match, which creates an ID switch. This is why tracks are deleted after a limited number of consecutive misses.
Exercise
You run the filter with R ten times larger and Q unchanged. How does the Kalman gain change, and what is the visible effect on the track?
Show answer
A larger R means the innovation covariance S is larger, so the gain K = P Hᵀ S⁻¹ becomes smaller. The filter trusts each detection less and its own prediction more. The track becomes smoother and less jittery, but it reacts more slowly when the object really changes direction or speed.