Self-Driving Cars
Topic 11 · Part 2: Seeing the road · ⏱ about 4 h

A U-Net for Lanes, Road and Distance

One network that labels every pixel (own lane, other lane, markings, vehicles, pedestrians, lights) and estimates how far away each pixel is: semantic segmentation, the encoder–decoder and its skip connections, class weights for rare pixels, IoU per class, depth from one camera, and driving laps steered by your own U-Net.

Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the camera and trained networks project, ready to run.Open
Show:
In this topic
Beginner

In plain words

Instead of boxes, give every pixel a label: my lane, the other lane, a car, a person. The network first shrinks the picture to understand what is in it, then grows it back to full size to say exactly where. It even learns to guess how far away each pixel is.

By the end of this topic you will be able to explain how a U-Net labels every pixel, and drive a lap steered by its idea of your lane.

Start with: the demo Try it: drive with your U-Net.

You do not need to train anything to follow this topic. Every demo comes with an example network that already works. Training your own in Google Colab (the Code sections) is an optional level-up you can do now or later.

Beginner

Every pixel gets an answer

Semantic segmentation gives every pixel a class. For driving, it answers questions that boxes cannot: exactly where the drivable road ends, which lane is ours, where the markings are. Your classic lane finder from Finding lanes the classic way searched for paint colours; a segmentation network learns what "my lane" looks like, in any weather, from your labels.

The simulator labels each pixel as one of 7 classes: background, own lane, other lane, lane marking, vehicle, pedestrian, traffic light. It also knows each pixel's distance. You will train one network that predicts both: that is multi-task learning. The two tasks share most of the network, which saves computation, and often each task helps the other.

Beginner

The U-Net

A plain classifier shrinks the image until only "what" is left. Segmentation needs "what" and "exactly where". The U-Net (Ronneberger et al., 2015, first for medical images) solves this with two halves:

  • The encoder shrinks the image step by step (64 × 128 → 32 × 64 → 16 × 32 → 8 × 16), with more channels at each step. Deep features see a wide area and know what things are.
  • The decoder grows it back. At each size it is joined (concatenated) with the encoder's features of the same size: the skip connections. They bring back the fine detail (exact edges of a lane line) that the shrinking lost.

The final layer gives 8 numbers per pixel: 7 class scores and 1 distance. The loss is cross-entropy for the classes plus twice the L1 error of the distance (scaled to 0–1, so 50 m = 1).

Rare pixels. Pedestrians and lights are under 1% of pixels. Without help, the network can ignore them and still be 99% "accurate". Weighting each class by 1/√(share of pixels) gives rare classes more say, without the instability of full inverse-frequency weights. This is also why accuracy is the wrong score: use IoU per class, the overlap between predicted and true pixels of that class.

Beginner

Distance from a single camera

One camera cannot measure distance directly: a small car near and a large car far can look the same. Yet the network learns good depth, because it uses clues people use too: where an object touches the road (lower in the image means nearer, on flat ground), the known size of cars and lane markings, and how the road narrows towards the horizon. The example U-Net's median error is about 0.5 m within 30 m.

These clues fail when their assumptions fail: on a hill, or for an object of unusual size. Real cars therefore check camera depth against radar or lidar, or use two cameras (stereo), where depth comes from geometry.

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

Code: load and shrink the data

Use the same recordings as for the detector. The network works at 64 × 128, half size, which is about 4 times faster and still sharp enough for lanes.

Python (Colab)
# In Google Colab. Upload two or more recordings at 120 × 240 (the last is kept for testing).
from google.colab import files
import numpy as np

names = list(files.upload())
assert len(names) >= 2, "Upload at least two recordings: the last one is kept for testing."
H, W = 64, 128                                   # the network works at half size, which is about 4 times faster
rows = ((np.arange(H) + 0.5) * 120 / H).astype(int)
cols = ((np.arange(W) + 0.5) * 240 / W).astype(int)
CLASSES = ["background", "own lane", "other lane", "lane marking", "vehicle", "pedestrian", "traffic light"]
DEPTH_MAX = 50.0                                 # metres; anything further (and the sky) counts as 50 m

def load(name):
    d = np.load(name)
    depth = d["depth"][:, rows][:, :, cols].astype(np.float32)
    depth = np.where(depth == 255, DEPTH_MAX, np.minimum(depth * 0.25, DEPTH_MAX)) / DEPTH_MAX      # 0..1
    return d["images"][:, rows][:, :, cols], d["seg"][:, rows][:, :, cols].astype(np.int64), depth, d["weather"]

data = [load(n) for n in names]
X_train, Y_train, D_train = (np.concatenate([d[k] for d in data[:-1]]) for k in range(3))
X_test, Y_test, D_test, W_test = data[-1]
share = np.bincount(Y_train.ravel(), minlength=7) / Y_train.size
print("share of pixels per class:", dict(zip(CLASSES, share.round(3).tolist())))
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).
Code

Code: the U-Net and training

Four encoder blocks, two decoder blocks with skip connections, and a head with 8 outputs per pixel. About 70,000 weights.

Python (Colab)
import torch
import torch.nn as nn
import torch.nn.functional as F

device = "cuda" if torch.cuda.is_available() else "cpu"
mean = X_train.reshape(-1, 3).mean(0) / 255
std = X_train.reshape(-1, 3).std(0) / 255
m = torch.tensor(mean, dtype=torch.float32, device=device).view(1, 3, 1, 1)
s = torch.tensor(std, dtype=torch.float32, device=device).view(1, 3, 1, 1)
raw = lambda X: torch.tensor(X, dtype=torch.float32, device=device).permute(0, 3, 1, 2) / 255

def block(i, o, stride=1):
    return nn.Sequential(nn.Conv2d(i, o, 3, stride, 1), nn.BatchNorm2d(o), nn.ReLU())

class UNet(nn.Module):
    """A small U-Net: the encoder shrinks the image to find what is there, the decoder grows it back,
    and skip connections bring back fine detail. Output: 7 class scores + 1 depth value per pixel."""
    def __init__(self, n_classes=7):
        super().__init__()
        self.e1, self.e2, self.e3, self.e4 = block(3, 16, 2), block(16, 32, 2), block(32, 48, 2), block(48, 48)
        self.d1, self.d2 = block(48 + 32, 32), block(32 + 16, 16)
        self.head = nn.Conv2d(16, n_classes + 1, 1)
        self.up = nn.Upsample(scale_factor=2, mode="nearest")

    def forward(self, x):
        s1 = self.e1(x)                              # 32 × 64
        s2 = self.e2(s1)                             # 16 × 32
        z = self.e4(self.e3(s2))                     # 8 × 16
        z = self.d1(torch.cat([self.up(z), s2], 1))  # back to 16 × 32, joined with the encoder's detail
        z = self.d2(torch.cat([self.up(z), s1], 1))  # 32 × 64
        return self.up(self.head(z))                 # 64 × 128

net = UNet().to(device)
# rare classes (pedestrians, lights, markings) get more weight; 1/sqrt(share) is a gentle version of "inverse frequency"
cw = torch.tensor(1 / np.sqrt(share + 1e-4), dtype=torch.float32, device=device)
cw = cw / cw.mean()
opt = torch.optim.AdamW(net.parameters(), lr=2e-3, weight_decay=1e-4)
sched = torch.optim.lr_scheduler.StepLR(opt, step_size=6, gamma=0.5)
for epoch in range(15):
    net.train()
    perm = torch.randperm(len(X_train)).numpy()
    total = 0
    for i in range(0, len(perm), 16):
        b = perm[i:i + 16]
        r = (raw(X_train[b]) * torch.empty(len(b), 1, 1, 1, device=device).uniform_(0.7, 1.3)).clamp(0, 1)
        out = net((r - m) / s)
        y = torch.tensor(Y_train[b], device=device)
        d = torch.tensor(D_train[b], device=device)
        loss = F.cross_entropy(out[:, :7], y, weight=cw) + 2 * F.l1_loss(out[:, 7], d)
        opt.zero_grad()
        loss.backward()
        opt.step()
        total += loss.item()
    sched.step()
    print(f"epoch {epoch + 1}: loss {total / (len(perm) / 16):.3f}")
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).
Code

Code: IoU per class and by weather, depth error

Score each class, the own lane in each kind of weather, and the distance error, all on the recording you kept back.

Python (Colab)
import numpy as np
import torch
net.eval()
with torch.no_grad():
    out = np.concatenate([net((raw(X_test[i:i + 40]) - m) / s).cpu().numpy() for i in range(0, len(X_test), 40)])
pred = out[:, :7].argmax(1)
for c, name in enumerate(CLASSES):
    inter, union = ((pred == c) & (Y_test == c)).sum(), ((pred == c) | (Y_test == c)).sum()
    print(f"{name:>13}: IoU {inter / max(union, 1):.2f}")
for k, name in enumerate(["day", "dusk", "night", "rain"]):
    sel = W_test == k
    if sel.any():
        inter = ((pred[sel] == 1) & (Y_test[sel] == 1)).sum(); union = ((pred[sel] == 1) | (Y_test[sel] == 1)).sum()
        print(f"own lane at {name}: IoU {inter / max(union, 1):.2f}")
ground = D_test < 0.999                              # ignore the sky
err = np.abs(out[:, 7] - D_test)[ground] * DEPTH_MAX
print(f"depth: median error {np.median(err):.2f} m")
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).

The example U-Net scores an own-lane IoU of about 0.91 in every kind of weather, including night and rain where the classic lane finder struggled. Its mean IoU over all 7 classes is lower (about 0.64), because thin markings and tiny lights are hard to get pixel-exact. For steering, only the own lane matters most.

Code

Code: export

A U-Net is not a straight line of layers, so the export lists them in order with save and concat steps for the skip connections. Paste the export helpers from the detection topic into this notebook first.

Python (Colab)
from google.colab import files
net = net.eval().cpu()
layers = (layers_of(net.e1) + [dict(type="save", name="s1")] + layers_of(net.e2) + [dict(type="save", name="s2")]
          + layers_of(net.e3) + layers_of(net.e4) + [dict(type="upsample", f=2), dict(type="concat", name="s2")]
          + layers_of(net.d1) + [dict(type="upsample", f=2), dict(type="concat", name="s1")]
          + layers_of(net.d2) + layers_of(net.head) + [dict(type="upsample", f=2)])
save_model(layers, "unet.json", "segment-depth", CLASSES, H, W, mean, std, depth_max=DEPTH_MAX)
files.download("unet.json")
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).
Beginner

From pixels to steering

To steer, the simulator takes the pixels the U-Net calls own lane, projects them onto the road with the camera model, and for each metre of distance from 6 to 15 m takes the middle of the lane. A curve through those points gives the lane centre, and pure pursuit (from Steering) follows it. Fits that bend too sharply are rejected. The distance output gives the range to the car ahead, which you will use for following and braking later in the course.

Try it

Try it: drive with your U-Net

Watch the three views: the camera, what the U-Net thinks each pixel is, and its distance estimate. Switch Steer using between the U-Net and the classic lane finder, and compare them at night and in rain, and at the City track's S-bend. Then load your own model.

Interactive: this part runs in your browser.

Check yourself

Quiz

1. What do the skip connections in a U-Net do?

2. Why is pixel accuracy a poor score for road segmentation?

3. How can one camera estimate distance at all?

4. Why train segmentation and depth in one network?

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