Self-Driving Cars
Topic 26 · Part 6: Modern perception (advanced) · ⏱ about 5 h

Lidar and 3D Object Detection

A lidar measures distance with lasers, millions of points a second. Explore a simulated 32-laser lidar, detect objects the classic way (remove the ground, cluster, fit boxes), see where that breaks, then detect cars and pedestrians with a learned bird's-eye-view network, and train a PointPillars-style detector on KITTI's real lidar.

Softmaxima Simulator StudioWrite your car in Python, with as many files and trained networks as it needs, and watch it drive. In your browser, nothing to install.Open
Show:
In this topic
Beginner

In plain words

A lidar is a spinning laser tape measure: it fires thousands of laser pulses a second in every direction and times their echoes, building a 3D picture made of dots. Finding cars in those dots can be done with rules (group nearby dots, measure the group) or with a network that has learned what cars look like as dots.

By the end of this topic you will be able to explain how lidar works, and detect objects in a point cloud with rules and with a neural network.

Start with: the demo Try it: our lidar: drag to turn it.

Beginner

How a lidar sees

A lidar sends out short laser pulses and times their echoes: distance = speed of light × time ÷ 2. A spinning lidar has a column of lasers (16 to 128) and turns many times a second, so each sweep gives tens of thousands to millions of 3D points, a point cloud. Each point also has an intensity: how strongly it reflected. Road paint and number plates reflect strongly; tyres and dark cars weakly.

Strengths: exact distances (a few centimetres), works in the dark, gives true 3D shape. Weaknesses: no colour (it cannot read a traffic light), sparse far away (a car 50 m away may get only a few dozen points), troubled by heavy rain, snow and fog, and historically expensive. Most robotaxis use lidar together with cameras and radar.

Try it

Try it: our lidar, with classic and learned detection

A 32-laser lidar on the roof, one reading per degree all round. Drag to turn the view; colour by height, intensity (look at the lane markings) or what each laser hit. Then compare the two detectors against the true boxes (white).

Interactive: this part runs in your browser.

Beginner

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.

Code

The classic pipeline, and where it breaks

  1. Remove the ground. Fit a plane to the lowest points (RANSAC, below) and drop everything near it.
  2. Cluster the rest: points close to each other belong to one object.
  3. Fit a box to each cluster: the smallest rectangle that contains it, trying every angle.
  4. Classify by size: about 4.5 × 1.8 m is a car, a thin column 1.7 m tall is a person.

It needs no training data and is easy to check, which is why it was used for years and is still used as a safety backup. But watch it fail in the demo: two cars queuing close together merge into one 10-metre "object"; a car seen only from behind looks 1.8 m long, so it is not called a car; a pole and a person look alike; far cars have too few points. A learned detector sees the pattern of points instead of applying fixed rules.

Python · NumPy
import numpy as np

rng = np.random.default_rng(1)
# A lidar-like point cloud: a road that slopes gently uphill, a car, a pedestrian and a post. (x forward, y left, z up)
ground = np.column_stack([rng.uniform(0, 40, 4000), rng.uniform(-10, 10, 4000), np.zeros(4000)])
ground[:, 2] = 0.03 * ground[:, 0] + rng.normal(0, 0.02, 4000)              # a 3% slope: a flat cut-off at z = 0.25 would fail
def box(cx, cy, l, w, h, n):
    p = np.column_stack([rng.uniform(-l / 2, l / 2, n) + cx, rng.uniform(-w / 2, w / 2, n) + cy, rng.uniform(0.2, h, n)])
    p[:, 2] += 0.03 * p[:, 0]
    return p
cloud = np.vstack([ground, box(15, -2, 4.4, 1.8, 1.5, 300), box(22, 4, 0.5, 0.5, 1.8, 80), box(30, -6, 0.3, 0.3, 3.0, 60)])

# 1. RANSAC: guess a plane from 3 random points, count the points within 10 cm of it, keep the best guess.
best_in, best_plane = None, None
for _ in range(200):
    a, b, c = cloud[rng.choice(len(cloud), 3, replace=False)]
    n = np.cross(b - a, c - a)
    if np.linalg.norm(n) < 1e-6:
        continue
    n /= np.linalg.norm(n)
    inliers = np.abs((cloud - a) @ n) < 0.10
    if best_in is None or inliers.sum() > best_in.sum():
        best_in, best_plane = inliers, (n, a)
n, a = best_plane
print(f"ground plane found: tilt {np.degrees(np.arccos(abs(n[2]))):.1f} degrees, {best_in.sum()} ground points")

# 2. Cluster what is left: points in neighbouring 0.5 m cells belong to the same object.
obj = cloud[~best_in]
cells = {}
for i, (x, y, _) in enumerate(obj):
    cells.setdefault((int(x // 0.5), int(y // 0.5)), []).append(i)
seen, clusters = set(), []
for start in cells:
    if start in seen:
        continue
    stack, members = [start], []
    seen.add(start)
    while stack:
        cx, cy = stack.pop()
        members += cells[(cx, cy)]
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                nb = (cx + dx, cy + dy)
                if nb in cells and nb not in seen:
                    seen.add(nb)
                    stack.append(nb)
    clusters.append(obj[members])

# 3. A box round each cluster, and a guess from its size.
for c in clusters:
    if len(c) < 10:
        continue
    l, w = np.ptp(c[:, 0]), np.ptp(c[:, 1])
    h = np.max(c[:, 2] - (c[:, 0] * -n[0] / n[2]))                       # height above the (sloping) ground
    kind = "car" if max(l, w) > 2.5 else "pedestrian" if h < 2.2 else "pole or post"
    print(f"object at x {c[:, 0].mean():5.1f} m, y {c[:, 1].mean():5.1f} m: {max(l, w):.1f} x {min(l, w):.1f} m, {h:.1f} m tall -> {kind}")
Open in playground ↗
Beginner

Learned 3D detection: pillars and a bird's-eye view

A neural network wants a regular grid, but a point cloud is an unordered set of points. PointPillars (Lang et al., 2019) solves this neatly:

  • Divide the ground into vertical columns, "pillars" (16 cm square in the paper).
  • For each point, build a small feature vector (position, intensity, offset from its pillar's centre). A tiny shared network (a PointNet) turns each point into a longer vector; the maximum over the points in a pillar gives one vector per pillar. The max makes the result independent of the order and number of points.
  • Place the pillar vectors back on the ground grid: now it is an image seen from above, a bird's-eye view (BEV), and an ordinary 2D CNN can process it.
  • Predict, per cell: is an object's centre here, which class, the exact offset, size and heading. CenterPoint (Yin et al., 2021) predicts a heat map of centres per class and keeps the local peaks, which needs no box overlap rules.

Our in-page network is a simplified version: instead of a learned PointNet it uses four hand-made numbers per pillar (highest point, mean height, how many points, brightest return), then the same CNN and grid outputs as our camera detector, plus the heading. It was trained on 3,600 simulated sweeps and runs on every sweep in the demo. The Colab code below builds the real thing on KITTI.

Code

Code: a PointPillars-style detector on KITTI (Colab)

Three cells: load KITTI's lidar and convert its labels from the camera frame to the lidar frame; build and train the network; detect and evaluate. Training takes a few hours on a free Colab GPU; reduce the number of training scans to try it faster.

Python (Colab)
# In Google Colab with a GPU. A small PointPillars-style detector, trained on real lidar from KITTI.
# 1. Register (free) at https://www.cvlibs.net/datasets/kitti/eval_object.php?obj_benchmark=3d and download
#    "Velodyne point clouds" (29 GB), "camera calibration matrices" (16 MB) and "training labels" (5 MB).
# 2. Put the three zip files in a folder called kitti in your Google Drive, and run this cell.
#    KITTI's licence (CC BY-NC-SA 3.0) allows non-commercial use such as learning.
from google.colab import drive
import os
import zipfile
import numpy as np

drive.mount("/content/drive")
for z in ["data_object_velodyne.zip", "data_object_calib.zip", "data_object_label_2.zip"]:
    if not os.path.exists("kitti3d/" + z):
        zipfile.ZipFile(f"/content/drive/MyDrive/kitti/{z}").extractall("kitti3d")
        open("kitti3d/" + z, "w").close()
ROOT = "kitti3d/training"
X0, X1, Y0, Y1, R = 0.0, 51.2, -25.6, 25.6, 0.16              # the area in front of the car, in 0.16 m pillars: 320 x 320
CLASSES = {"Car": 0, "Pedestrian": 1, "Cyclist": 2}

def calib(i):
    m = {}
    for line in open(f"{ROOT}/calib/{i}.txt"):
        if ":" in line:
            k, v = line.split(":", 1)
            m[k] = np.array(v.split(), np.float64)
    R0 = np.eye(4); R0[:3, :3] = m["R0_rect"].reshape(3, 3)
    Tr = np.eye(4); Tr[:3, :] = m["Tr_velo_to_cam"].reshape(3, 4)
    return np.linalg.inv(R0 @ Tr)                              # rectified camera frame -> lidar frame

def labels(i):
    """KITTI boxes are in the camera frame (x right, y down, z forward); convert to the lidar frame (x forward, y left, z up)."""
    to_lidar, out = calib(i), []
    for line in open(f"{ROOT}/label_2/{i}.txt"):
        p = line.split()
        if p[0] not in CLASSES:
            continue
        h, w, l, x, y, z, ry = map(float, p[8:15])
        c = to_lidar @ np.array([x, y - h / 2, z, 1.0])         # the label gives the bottom centre; we want the middle
        out.append([CLASSES[p[0]], c[0], c[1], c[2], l, w, h, -ry - np.pi / 2])   # heading: camera yaw -> lidar yaw
    return np.array(out).reshape(-1, 8)

def points(i):
    p = np.fromfile(f"{ROOT}/velodyne/{i}.bin", np.float32).reshape(-1, 4)   # x, y, z, reflectance
    keep = (p[:, 0] >= X0) & (p[:, 0] < X1) & (p[:, 1] >= Y0) & (p[:, 1] < Y1) & (p[:, 2] > -3) & (p[:, 2] < 1)
    return p[keep]

ids = sorted(f[:-4] for f in os.listdir(f"{ROOT}/velodyne"))
rng = np.random.default_rng(0)
rng.shuffle(ids)
val_ids, train_ids = ids[:700], ids[700:]
print(len(train_ids), "training scans,", len(val_ids), "validation scans")
This code needs Google Colab (it uploads the dataset file you recorded), which cannot run inside a web page. To run it, press Copy, then paste it into a new notebook in Google Colab ↗ (free; Runtime → Change runtime type → GPU for deep learning).
Python (Colab)
import torch
import torch.nn as nn
import torch.nn.functional as F

device = "cuda"
NX, NY, MAXP, STRIDE = int((X1 - X0) / R), int((Y1 - Y0) / R), 32, 4      # 320 x 320 pillars, at most 32 points each

def pillarise(p):
    """Group points into vertical pillars. Each point gets 9 features: x, y, z, reflectance, its offset from the mean of
    its pillar (3), and its offset from the pillar's centre (2). Returns features (P, MAXP, 9), mask and pillar positions."""
    ix = ((p[:, 0] - X0) / R).astype(int); iy = ((p[:, 1] - Y0) / R).astype(int)
    key = ix * NY + iy
    order = np.argsort(key, kind="stable"); key, p, ix, iy = key[order], p[order], ix[order], iy[order]
    uniq, start, count = np.unique(key, return_index=True, return_counts=True)
    rank = np.arange(len(key)) - np.repeat(start, count)                    # position of each point inside its pillar
    keep = rank < MAXP
    pid = np.repeat(np.arange(len(uniq)), count)[keep]
    feats = np.zeros((len(uniq), MAXP, 9), np.float32); mask = np.zeros((len(uniq), MAXP), np.float32)
    pk = p[keep]
    feats[pid, rank[keep], :4] = pk
    mask[pid, rank[keep]] = 1
    mean = (feats[:, :, :3] * mask[..., None]).sum(1) / mask.sum(1, keepdims=True)
    feats[:, :, 4:7] = (feats[:, :, :3] - mean[:, None]) * mask[..., None]
    cx = X0 + ((uniq // NY) + 0.5) * R; cy = Y0 + ((uniq % NY) + 0.5) * R
    feats[:, :, 7] = (feats[:, :, 0] - cx[:, None]) * mask; feats[:, :, 8] = (feats[:, :, 1] - cy[:, None]) * mask
    return feats, mask, uniq

def targets(lab):
    """CenterPoint-style targets on the output grid (stride 4: 80 x 80 cells of 0.64 m): a Gaussian peak at each object's
    centre per class, plus offset, height, size and heading at the centre cell."""
    gx, gy = NX // STRIDE, NY // STRIDE
    heat = np.zeros((3, gx, gy), np.float32); reg = np.zeros((8, gx, gy), np.float32); m = np.zeros((gx, gy), np.float32)
    cs = R * STRIDE
    for c, x, y, z, l, w, h, yaw in lab:
        fx, fy = (x - X0) / cs, (y - Y0) / cs
        i, j = int(fx), int(fy)
        if not (0 <= i < gx and 0 <= j < gy):
            continue
        sigma = max(0.8, 0.5 * w / cs)
        ii, jj = np.meshgrid(np.arange(gx), np.arange(gy), indexing="ij")
        heat[int(c)] = np.maximum(heat[int(c)], np.exp(-((ii - fx + 0.5) ** 2 + (jj - fy + 0.5) ** 2) / (2 * sigma ** 2)))
        heat[int(c), i, j] = 1
        reg[:, i, j] = [fx - i, fy - j, z, np.log(l), np.log(w), np.log(h), np.sin(yaw), np.cos(yaw)]
        m[i, j] = 1
    return heat, reg, m

class PillarNet(nn.Module):
    def __init__(s):
        super().__init__()
        s.pfn = nn.Sequential(nn.Linear(9, 64), nn.BatchNorm1d(64), nn.ReLU())   # a tiny PointNet applied to every point
        def blk(i, o, st): return nn.Sequential(nn.Conv2d(i, o, 3, st, 1), nn.BatchNorm2d(o), nn.ReLU(), nn.Conv2d(o, o, 3, 1, 1), nn.BatchNorm2d(o), nn.ReLU())
        s.b1, s.b2, s.b3 = blk(64, 64, 2), blk(64, 128, 2), blk(128, 256, 2)        # strides 2, 4, 8
        s.u2, s.u3 = nn.ConvTranspose2d(128, 128, 1, 1), nn.ConvTranspose2d(256, 128, 2, 2)
        s.d1 = nn.Conv2d(64, 128, 3, 2, 1)
        s.head = nn.Sequential(nn.Conv2d(384, 128, 3, 1, 1), nn.ReLU(), nn.Conv2d(128, 3 + 8, 1))
        s.head[-1].bias.data[:3] = -2.2                                             # start by predicting "nothing here"

    def forward(s, feats, mask, uniq):
        P = feats.shape[0]
        x = s.pfn[0](feats.view(-1, 9)); x = s.pfn[2](s.pfn[1](x)).view(P, MAXP, 64)
        x = (x * mask[..., None]).max(1).values                                     # one 64-number vector per pillar
        canvas = torch.zeros(64, NX * NY, device=feats.device)
        canvas[:, uniq] = x.t()                                                     # scatter pillars back to a 2D image
        img = canvas.view(1, 64, NX, NY)
        f1 = s.b1(img); f2 = s.b2(f1); f3 = s.b3(f2)
        f = torch.cat([s.d1(f1), s.u2(f2), s.u3(f3)], 1)                            # all at stride 4
        return s.head(f)[0]

def focal(pred, gt):
    p = pred.sigmoid().clamp(1e-4, 1 - 1e-4); pos = gt == 1
    l = -(pos * (1 - p) ** 2 * p.log() + (~pos) * (1 - gt) ** 4 * p ** 2 * (1 - p).log())
    return l.sum() / pos.sum().clamp(min=1)

def sample(i, train):
    p, lab = points(i), labels(i)
    if train and rng.random() < 0.5:                                 # mirror left-right
        p = p.copy(); p[:, 1] = -p[:, 1]; lab = lab.copy(); lab[:, 2] = -lab[:, 2]; lab[:, 7] = -lab[:, 7]
    f, m, u = pillarise(p)
    h, r, mk = targets(lab)
    T = lambda a: torch.from_numpy(a).to(device)
    return T(f), T(m), torch.from_numpy(u).to(device), T(h), T(r), T(mk)

net = PillarNet().to(device)
opt = torch.optim.AdamW(net.parameters(), lr=2e-3, weight_decay=1e-2)
EPOCHS = 12
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=2e-3, total_steps=EPOCHS * len(train_ids))
for ep in range(EPOCHS):
    net.train(); total = 0
    for k in rng.permutation(len(train_ids)):
        f, m, u, h, r, mk = sample(train_ids[k], True)
        out = net(f, m, u)
        loss = focal(out[:3], h) + 2 * (F.l1_loss(out[3:], r, reduction="none").sum(0) * mk).sum() / mk.sum().clamp(min=1)
        opt.zero_grad(); loss.backward(); opt.step(); sched.step(); total += loss.item()
    print(f"epoch {ep + 1}: loss {total / len(train_ids):.3f}")
torch.save(net.state_dict(), "pillars.pt")
This code needs PyTorch, which cannot run inside a web page. To run it, press Copy, then paste it into a new notebook in Google Colab ↗ (free; Runtime → Change runtime type → GPU for deep learning).
Python (Colab)
import numpy as np
import torch
import torch.nn.functional as F

def detect(i, thr=0.3):
    net.eval()
    with torch.no_grad():
        f, m, u, *_ = sample(i, False)
        out = net(f, m, u).cpu().numpy()
    heat = 1 / (1 + np.exp(-out[:3]))
    peak = F.max_pool2d(torch.from_numpy(heat)[None], 3, 1, 1)[0].numpy() == heat     # keep only local peaks: no need for NMS
    cs, found = R * STRIDE, []
    for c, i0, j0 in zip(*np.where((heat > thr) & peak)):
        dx, dy, z, ll, lw, lh, s, co = out[3:, i0, j0]
        found.append([c, heat[c, i0, j0], X0 + (i0 + dx) * cs, Y0 + (j0 + dy) * cs, np.exp(ll), np.exp(lw), np.arctan2(s, co)])
    return found

# Evaluate in the bird's-eye view: a detection counts if its centre is within 2 m (cars) or 1 m (pedestrians, cyclists)
# of an unmatched object of the same class. (The official KITTI benchmark uses 3D box overlap and difficulty levels;
# this simpler test is enough to compare your own models.)
tp, fp, fn = np.zeros(3), np.zeros(3), np.zeros(3)
for i in val_ids[:300]:
    truth = labels(i); truth = truth[(truth[:, 1] < X1) & (np.abs(truth[:, 2]) < Y1)]; used = set()
    for c, s, x, y, *_ in sorted(detect(i), key=lambda d: -d[1]):
        m = [k for k, t in enumerate(truth) if k not in used and t[0] == c and np.hypot(t[1] - x, t[2] - y) < (2 if c == 0 else 1)]
        if m: used.add(m[0]); tp[c] += 1
        else: fp[c] += 1
    for k, t in enumerate(truth):
        if k not in used: fn[int(t[0])] += 1
for c, name in enumerate(CLASSES):
    print(f"{name:>10}: precision {tp[c] / max(1, tp[c] + fp[c]):.0%}, recall {tp[c] / max(1, tp[c] + fn[c]):.0%}")
This code needs PyTorch, which cannot run inside a web page. To run it, press Copy, then paste it into a new notebook in Google Colab ↗ (free; Runtime → Change runtime type → GPU for deep learning).

For serious work, use a maintained library such as OpenPCDet or MMDetection3D, which include PointPillars, CenterPoint and many others with tested training recipes and the official evaluation. Writing the small version yourself is how you understand what those libraries do.

Check yourself

Quiz

1. Why does PointPillars take the maximum over the points in a pillar?

2. Two cars queue close together. What does a classic cluster-and-box pipeline often do?

3. Which can a camera do that a lidar cannot?

4. Why do lane markings show up in lidar intensity?

Go deeper

📚 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.

Ready