Finding Lanes the Classic Way
A complete lane finder without machine learning: a bird's-eye view, colour thresholds for white and yellow paint, a histogram and sliding windows to trace each line, and a curve fit. Then drive a full lap using only the camera, and find where hand-written rules break.
Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the camera and trained networks project, ready to run.OpenIn plain words
Before deep learning, engineers wrote the rules by hand: lane lines are white or yellow, long and thin, so find those colours, look at the road from above, and fit a curve through them. It works surprisingly well, until the light changes.
By the end of this topic you will be able to follow a lane with hand-written rules and see exactly where such rules break.
Start with: the demo Try it: step through the pipeline.
The pipeline
- Bird's-eye view. Warp the camera image to a top-down grid of the road ahead (the previous topic), so the lane lines are parallel and measured in metres.
- Paint mask. Keep pixels that look like lane paint. Yellow paint has much more red than blue; white paint is among the brightest pixels and has little colour. The thresholds are set relative to the brightest pixel in the view, so they adapt to darker scenes.
- Find where each line starts. Add up the mask down each column of the nearest part of the view (a histogram). Lane lines make peaks. We look for the white edge line about 1.75 m to the left of where the lane centre was in the last frame, and the yellow centre line about 1.75 m to the right.
- Sliding windows. From the start point, move a small window up the image row by row, re-centring it on the paint it finds. Through the gaps between yellow dashes, it keeps going in the same direction. It may only move a little sideways each step, so it does not get pulled along the stripes of a pedestrian crossing.
- Fit a curve. Fit a quadratic, lateral position = a x² + b x + c, through each line's pixels by least squares. Reject fits that are far from where the line should be or bend more sharply than any road.
- The lane centre is halfway between the two lines, or 1.75 m from one line if only one was found. From it come the car's offset, its heading relative to the lane and the road's curvature, which are exactly what the controllers in Part 1 need.
Try it: step through the pipeline
Each press moves the car 1.5 seconds further along. Compare the estimate with the true value, and try the different weather.
Interactive: this part runs in your browser.
Try it: drive using only the camera
Now the car gets no help from the simulator: every steering command comes from the lane finder above, run on each camera frame, plus pure pursuit. If no lines are found, it keeps the last estimate and slows down. By day it completes every track. Then try night and dusk.
Interactive: this part runs in your browser.
Where hand-written rules break
At night the headlights light only the first 20–30 m, the far paint disappears, and the car soon loses the lane. At dusk the warm light makes white paint look yellowish. In rain, streaks add false paint pixels. Each failure can be patched with another rule, but the rules multiply and start to conflict, and every new road, camera or weather needs more of them.
This is why modern systems learn perception from data instead. A segmentation network trained on lane-marking labels in all weathers, which you build in a later topic of this part, learns what lane paint looks like in each condition, without anyone writing the rules. Classic methods still matter: they are fast, easy to understand and check, and make excellent baselines and sanity checks for learned models.
Code: the same lane finder in Python, on your data
Run this in Colab on the dataset you recorded. It builds the bird's-eye view from the camera's geometry, finds both lines in every frame and compares the lane centre 10 m ahead with the simulator's true value (lane10). On daytime data, expect a median error of a few centimetres.
import numpy as np
# In Google Colab: upload the .npz file you recorded in the simulator
from google.colab import files
d = np.load(next(iter(files.upload())))
imgs, lane10 = d["images"], d["lane10"]
N, H, W, _ = imgs.shape
# The simulator's camera (see README.txt in the .npz): 70° field of view, 1.4 m high,
# pitched 4° down, 1.6 m ahead of the rear axle.
FOV, CAM_H, PITCH, FWD = np.radians(70), 1.4, np.radians(4), 1.6
f = (W / 2) / np.tan(FOV / 2)
cx, cy = W / 2, H / 2
def project(X, Y):
"""A point on the road (X metres ahead of the rear axle, Y metres to the left) -> pixel (u, v)."""
px, pz = X - FWD, -CAM_H
x = px * np.cos(PITCH) - pz * np.sin(PITCH) # depth along the camera's axis
z = px * np.sin(PITCH) + pz * np.cos(PITCH)
return cx - f * Y / x, cy - f * z / x
# Bird's-eye grid: 6–30 m ahead, 6 m either side, 0.1 m per cell. Row 0 is the farthest.
xs = np.arange(30, 6, -0.1) - 0.05
ys = np.arange(6, -6, -0.1) - 0.05
Xg, Yg = np.meshgrid(xs, ys, indexing="ij")
U, V = project(Xg, Yg)
U, V = U.astype(int), V.astype(int)
inside = (U >= 0) & (U < W) & (V >= 0) & (V < H)
def birdseye(img):
out = np.zeros(Xg.shape + (3,), np.uint8)
out[inside] = img[V[inside], U[inside]]
return out
def paint_masks(bev):
b = bev.astype(float)
r, g, bl = b[..., 0], b[..., 1], b[..., 2]
brightest = max(r.max(), g.max(), 1)
yellow = (r - bl > 0.5 * r) & (r > 0.45 * brightest) & (g > 0.35 * brightest)
white = ~yellow & (b.max(-1) > 0.72 * brightest) & (b.max(-1) - b.min(-1) < 0.4 * b.max(-1))
return white, yellow
def find_line(mask, guess, windows=12, margin=8):
"""Sliding windows from the nearest row upwards; returns a quadratic fit lateral = a·x² + b·x + c, or None."""
rows, cols = mask.shape
hist = mask[int(rows * 0.4):].sum(axis=0)
c0 = int(round((6 - guess) / 0.1 - 0.5))
lo, hi = max(0, c0 - 13), min(cols, c0 + 13)
if hist[lo:hi].max() < 3:
return None
col = lo + int(hist[lo:hi].argmax())
px, py, wh = [], [], rows // windows
for k in range(windows):
r1 = rows - k * wh
r0, c_start = r1 - wh, max(0, col - margin)
rr, cc = np.nonzero(mask[r0:r1, c_start:col + margin])
px += list(xs[r0 + rr])
py += list(ys[c_start + cc])
if len(cc) > 4: # follow the line, but never jump sideways (that would be a crossing or stop line)
col = int(np.clip(round(c_start + cc.mean()), col - 4, col + 4))
if len(px) < 20:
return None
fit = np.polyfit(px, py, 2)
return fit if abs(np.polyval(fit, 8) - guess) < 1.3 else None
errors = []
for i in range(N):
white, yellow = paint_masks(birdseye(imgs[i]))
w_fit, y_fit = find_line(white, +1.75), find_line(yellow, -1.75)
if w_fit is not None and y_fit is not None:
centre = (np.polyval(w_fit, 10) + np.polyval(y_fit, 10)) / 2 # lane centre 10 m ahead
elif w_fit is not None:
centre = np.polyval(w_fit, 10) - 1.75
elif y_fit is not None:
centre = np.polyval(y_fit, 10) + 1.75
else:
continue
errors.append(abs(centre - lane10[i])) # compare with the simulator's true value
errors = np.array(errors)
print(f"lane found in {len(errors)} of {N} frames")
print(f"lane centre 10 m ahead: median error {np.median(errors):.2f} m, 90% of frames within {np.percentile(errors, 90):.2f} m")Quiz
1. Why is the lane-finding done in a bird's-eye view rather than on the camera image?
2. What does the column histogram of the paint mask show?
3. Why is each sliding window only allowed to move a few pixels sideways?
4. The classic lane finder works by day but fails at night. What is the modern fix?
📚 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.
- OpenCV: Camera calibration ↗ calibrating a real camera with a checkerboard