Measuring vehicle speed from a roadside camera: from pixels to km/h
Detect, track, calibrate, measure: the full pipeline for estimating vehicle speed and spotting lane changes in traffic video, with the homography maths, OpenCV code and lessons for placing cameras on mixed-traffic roads.
A camera can measure speed once it knows how pixels map to metres on the road. The pipeline is: detect every vehicle in every frame, track each one so it keeps the same identity, map its position to road coordinates with a homography, and divide the distance travelled by the time elapsed. Lane changes come from the same tracks: a vehicle whose sideways position crosses a lane boundary and stays across it has changed lane.
This was the subject of my MSc thesis, Towards Deep Learning-Based Automated Speed and Lane Change Detection System in the Perspective of Bangladesh (Bangladesh University of Professionals, 2022), which applied deep-learning models to naturalistic traffic footage to detect over-speeding and lane-change manoeuvres, and set out a field-deployment concept: camera selection, roadside installation and adaptation to different road environments. This article explains each stage of that kind of system and the decisions that decide whether it works outside the lab.
Key points
- Speed error comes mostly from calibration and tracking, not from the detector.
- A homography from four known road points maps the image to a bird’s-eye road plane in metres.
- Measure displacement over a window of frames and smooth it; frame-to-frame differences are noisy.
- Camera height, angle, frame rate and shutter speed are design decisions, made before any model is trained.
Step 1: detect vehicles in every frame
A one-stage detector from the YOLO family, or a two-stage detector such as Faster R-CNN, returns a bounding box, a class (car, bus, truck, motorcycle, auto-rickshaw) and a confidence score for each vehicle. For speed, the useful point is not the box centre but the bottom-centre of the box, where the vehicle touches the road, because the calibration maps the road plane, not points in the air.
On mixed-traffic roads, pre-trained detectors often miss local vehicle types such as cycle-rickshaws and CNG auto-rickshaws. Fine-tuning on a few hundred labelled local frames usually matters more than switching architecture.
Step 2: track each vehicle across frames
Speed needs the same vehicle at two moments. A tracker links detections between frames: SORT and its successors (DeepSORT, ByteTrack) predict where each track should be using a Kalman filter with a constant-velocity model, then match new detections to tracks by overlap:
A detection joins the track whose predicted box it overlaps most, above a threshold. ID switches, where two vehicles swap identities during occlusion, are the main source of impossible speeds, so filter tracks that jump.
Step 3: calibrate pixels to metres with a homography
Because the road is close to flat, a 3×3 homography H maps image points (u, v) to road-plane coordinates (X, Y) in metres:
H has eight degrees of freedom, so four image points with known road positions are enough. Lane markings are ideal: the standard lane width and the length and spacing of dashed markings give real distances without closing the road. Measure them on site once rather than trusting nominal values.
import cv2
import numpy as np
# Four points on the road in the image (pixels), e.g. corners of two dashed lane markings
img_pts = np.float32([[612, 705], [868, 702], [742, 431], [835, 430]])
# The same points on the road plane in metres (lane width 3.5 m, 12 m along the road)
road_pts = np.float32([[0.0, 0.0], [3.5, 0.0], [0.0, 12.0], [3.5, 12.0]])
H = cv2.getPerspectiveTransform(img_pts, road_pts)
def to_road(points_px):
"""Map image points (N, 2) to road coordinates in metres."""
pts = np.asarray(points_px, dtype=np.float32).reshape(-1, 1, 2)
return cv2.perspectiveTransform(pts, H).reshape(-1, 2)
Use more than four points with cv2.findHomography and RANSAC when you can; the extra points average out measurement error and reveal a bad point.
Step 4: speed from distance and time
With road positions P(t) for one track, speed over a window of frames is distance over time, converted from metres per second to km/h:
from collections import defaultdict, deque
FPS = 30
WINDOW = 15 # half a second at 30 fps
history = defaultdict(lambda: deque(maxlen=WINDOW))
def update_speed(track_id, frame_idx, box):
x1, y1, x2, y2 = box
foot = ((x1 + x2) / 2, y2) # bottom-centre touches the road
history[track_id].append((frame_idx, to_road([foot])[0]))
if len(history[track_id]) < WINDOW:
return None
(f1, p1), (f2, p2) = history[track_id][0], history[track_id][-1]
metres = float(np.linalg.norm(p2 - p1))
seconds = (f2 - f1) / FPS
return 3.6 * metres / seconds # km/h
Measuring over a window rather than between consecutive frames cuts jitter from the detector’s box edges. Use the video’s real timestamps if the camera drops frames, and flag readings only when several consecutive windows agree.
Step 5: lane changes from sideways movement
The road coordinate X runs across the road, so a vehicle’s lane is simply its X position divided by the lane width w:
A lane change is a change in ℓ that persists, for example for at least half a second, so that a wheel touching the line or a noisy box does not count. Recording the moment of crossing and the lateral speed gives a richer picture: abrupt cuts across lanes are a different behaviour from a gradual merge.
Deploying the camera: decisions made before any training
Most accuracy is won or lost in the field. The questions a deployment plan has to answer:
- Height and angle. A higher camera looking down the road reduces occlusion between vehicles and makes the road plane better conditioned for the homography. Very shallow angles stretch distant pixels over many metres.
- Field of view. The measured stretch must be long enough to hold a full measurement window at the highest speed you care about.
- Frame rate and shutter. Motion blur at night or in low light blurs box edges; a faster shutter and adequate lighting matter as much as resolution.
- Mounting stability. Wind and passing trucks shake poles; a moving camera silently invalidates the calibration. Re-check reference points regularly.
- Local traffic. Mixed traffic with motorcycles, rickshaws, buses and loose lane discipline needs locally trained detectors and tracking settings tuned for dense, overlapping vehicles.
- Re-calibration per site. Every new location needs its own reference points. Plan to measure them during installation.
Camera or radar?
| Roadside camera with deep learning | Radar or lidar speed gun | |
|---|---|---|
| What it measures | Speed, lane, vehicle type and behaviour for many vehicles at once | Speed of the target vehicle |
| Accuracy depends on | Calibration, tracking, frame rate | Beam alignment and cosine angle |
| Cost and coverage | Low-cost hardware; one camera covers several lanes | Higher unit cost; narrower coverage |
| Works at night | Needs lighting or infrared | Yes |
| Extra value | Lane changes, near misses, traffic counts from the same video | Speed only |
Frequently asked questions
How accurate is vehicle speed estimation from video?
It depends mostly on calibration quality, tracking stability, frame rate and camera placement. Accuracy should be checked on site against a reference, such as a GPS-logged test vehicle driven at known speeds, before results are used.
Do I need a calibrated camera to measure speed?
You need to know how image positions map to road distances. A homography from four or more measured road points, such as lane-marking corners, provides this without the camera’s internal parameters.
Can the same system detect lane changes?
Yes. Once each vehicle is tracked in road coordinates, a lane change is a sustained change in its lateral position across a lane boundary.
Why use the bottom of the bounding box for speed?
The homography maps the flat road surface. The bottom-centre of a vehicle’s box is where it meets the road, so it maps correctly; the box centre sits above the road and introduces a height-dependent error.
The thesis and its context are on the speed and lane-change detection project page.
Related articles
Forecasting dengue from open weather data: lags, leakage and lead time
Weather shapes dengue with a delay of weeks, and that delay is what makes early warning possible. How to build lagged weather features, validate a forecaster in time order and judge it by lead time, with Malaysia as the example.
Why AQI models report R² = 0.99, and how to evaluate them honestly
Near-perfect scores in air-quality papers usually say more about the evaluation than the model. Target leakage, random splits and seasonal blind spots explained, with the seasonally stratified set-up from our Dhaka study.
SHAP vs LIME vs feature importance: which explanation should you trust?
SHAP, LIME and built-in feature importance answer different questions. A side-by-side comparison on one decision-tree classifier, with the maths, runnable Python and a table for choosing between them.