Measuring vehicle speed from a single camera
Homography calibration, the ground-contact point, windowed displacement and media timestamps: how panoptes turns pixels into km/h, and where error comes in.
A speed figure from a camera tends to be read as a fact. In panoptes it can also raise a speeding event, so it has to survive the question “how do you know?”. This note walks through the chain from pixels to km/h as panoptes builds it: the calibration, the point on the vehicle that is measured, how the estimate is smoothed, which clock it uses, and the error budget, meaning where the number stops being trustworthy. The tracker that links detections to the same vehicle across frames gets a short section at the end; the interactive version is on the lab page.
Pixels are not metres
Perspective compresses distance: the far end of the road gets far fewer pixels per metre than the near end. Speed in pixels per second therefore depends on where in the frame the vehicle is. What makes the problem solvable is that the road is close to a plane. The relation between a plane and its image is a projective transform: a 3×3 matrix H with eight degrees of freedom (the ninth entry is only scale). Each match between a pixel you can see and a road position you have measured fixes two of those eight unknowns, so four points determine H exactly.
panoptes estimates H with the normalised Direct Linear Transform: both point sets are shifted to their centroid and scaled so that their mean distance from it is √2, the linear system is solved with an SVD, and the result is scaled back. With more than four points the same solve becomes least squares. That is what you want: extra survey points do not over-constrain anything, they average out tape-measure error. The minimal survey in the calibration doc is a rectangle: two lane edges and two dash corners, four corners, two measured distances. The doc gives lane widths on Turkish and most European highways as 3.5–3.65 m, and adds that urban roads may differ and that dash patterns should be checked against the road authority’s standard or measured once by hand.
Which point on the vehicle
The homography maps the road plane, so the only part of a vehicle it can place correctly is where the vehicle touches that plane. panoptes always uses the bottom centre of the bounding box. The box centre sits well above the road (the doc estimates about 0.7 m), and projecting it as if it were on the road puts the vehicle metres away from where it is, with an error that grows with distance from the camera. Counting lines and zones use the same anchor for the same reason.
Do not differentiate noise
A detector’s box jitters by a pixel or two from frame to frame even when nothing moves. In the example calibration above, one pixel row at the far edge of the surveyed area is about 11 cm of road. Divide that by a single frame interval at 30 fps and one pixel of jitter becomes 3.3 metres per second, about 12 km/h. Over a one-second baseline the same pixel is 0.4 km/h.
So the estimator never differentiates consecutive frames. It takes the newest ground point and the earlier ground point closest to one window back (window_s, 1.0 s by default), divides the distance between them by the time between them, and smooths the result with an exponential moving average (ema_alpha, 0.35).
# At least two grounded observations inside the window: a track
# re-acquired after a long occlusion must not report a speed
# computed across the gap.
windowed = sum(1 for ts, _, _ in grounded if ts >= window_start)
if windowed < 2:
return
ref_ts, ref_x, ref_y = min(grounded[:-1], key=lambda g: abs(g[0] - window_start))
dt = current.timestamp - ref_ts
if dt <= _MIN_DT_S:
return
dx = current.ground[0] - ref_x
dy = current.ground[1] - ref_y
displacement = math.hypot(dx, dy)
raw_kmh = (displacement / dt) * 3.6
if track.speed_kmh is None:
# EMA warmup: the first estimate IS the raw value; blending
# against an implicit 0 would under-report early speeds.
track.speed_kmh = raw_kmh
else:
alpha = self._speed.ema_alpha
track.speed_kmh = alpha * raw_kmh + (1.0 - alpha) * track.speed_kmh
src/panoptes/motion/estimator.py, lines 150–171Three small decisions in that block carry weight. The first estimate is taken as is; blending it against an implicit zero would under-report the speed for the first second of every track. At least two grounded observations must fall inside the window, so a track re-acquired after an occlusion does not report a speed computed across the gap. And no speed at all is reported for tracks younger than min_track_s (0.7 s).
Distance travelled has its own version of the same problem. Summing every small hop integrates the jitter: a parked vehicle collects phantom metres. The estimator keeps an anchor point and only adds a step once the ground point is at least 15 cm from it; then the anchor moves. A stationary vehicle’s jitter integrates to zero, while slow real motion still adds up. Heading is protected by a similar threshold: below 5 cm of displacement a stopped vehicle keeps its last heading instead of spinning on the spot.
Which clock
Speed is distance over time, and that time has to be the video’s. panoptes uses the stream-relative media presentation timestamp (PTS) for all physics, never the wall clock. The wall clock can step when NTP corrects it or someone resets it; it is attached to events only for display and storage. The tracker follows the same rule: track lifetimes are measured in stream-relative seconds, not frames, so behaviour does not change when the frame governor varies the sampling rate.
Where the error comes from
The estimator’s own error is small and tested. On synthetic constant-velocity tracks (a 10 m square mapped to 100 pixels, a vehicle doing 72 km/h) the golden test holds the result within 2%, and within 3% with ±1 pixel of alternating jitter at 30 fps. Those tests prove the arithmetic, not a camera. The calibration doc says so plainly: real-world agreement is set by calibration quality, not by the estimator. The real sources of error are these:
- Extrapolation. H is most accurate inside the polygon formed by the survey points. Outside it, every pixel covers more road (in the figure, 11 cm at the far edge, 18 cm sixteen metres beyond it) and survey errors are amplified.
- The horizon. Near the vanishing point a single pixel can be metres of road.
- A road that is not flat. One homography is one plane. Crests, dips, banked curves and bridge approaches violate it, and the error grows with the height difference from the calibrated plane.
- Lens distortion. It is not modelled. Wide-angle lenses bend straight lane lines, while the homography assumes they are straight. The fix is to undistort at the camera, or keep the measured area near the centre of the image.
- Survey mistakes. With exactly four points the fit is exact by construction, so
panoptes calibrate checkreports about 0 pixels whatever the tape measure said. Only with more points does the mean reprojection error start to expose mistakes. The doc’s rule of thumb: under 2–3 pixels at 1280 pixels wide; 10 pixels or more means a mislabelled point or a wrong distance. - A camera that moves. A PTZ move, a refocus or a remount invalidates the calibration.
Without a calibration panoptes does not guess. Tracks, counts and zones keep working, but speed, heading and distance stay empty and no speeding event is emitted. A speed figure without a homography behind it is not evidence.
I should also say what the repo does not contain: a field validation. Driving a vehicle with GPS-logged speed through a calibrated view is the check the doc recommends for a real installation. I have not published such a measurement, so I make no accuracy claim beyond the synthetic tests.
Keeping the identity
Everything above assumes the same vehicle keeps the same track ID across frames. panoptes reimplements ByteTrack clean-room, from the algorithm description and not from any existing tracker code. High-score detections are matched first to confirmed tracks by the IoU of their Kalman-predicted boxes. Low-score detections are then matched only to the tracks left over; that keeps a track alive through frames where the detector flickers, without ever starting a track from weak evidence. Instead of the Hungarian algorithm it uses a greedy maximum-IoU matcher: not globally optimal in rare many-to-many overlaps, but deterministic and dependency-free. The Kalman filter is a constant-velocity model in pixel space, with noise scaled to box height so it behaves the same for near and far vehicles.
On the lab page you can try both the calibration (drag the four corners and watch the bird’s-eye view warp) and how low-score detections keep an identity through an occlusion.