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

Depth from Cameras: Stereo and Self-Supervised

How far away is everything? Measure depth with two cameras by matching pixels, see why the error grows with the square of the distance, discover how a network can learn depth from a single camera with no depth labels at all, and test a depth foundation model.

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

Your two eyes see a near object jump sideways when you switch from one eye to the other; the bigger the jump, the nearer it is. Two cameras do the same. And a network can even learn depth from one camera, by checking whether its guess lets it redraw the picture the other camera saw.

By the end of this topic you will be able to measure depth with two cameras, explain why errors grow far away, and explain how networks learn depth without labels.

Start with: the demo Try it: a stereo camera on our car.

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.

Intermediate · Maths

Two eyes see depth

Hold a finger in front of your face and close one eye, then the other: the finger jumps sideways against the background, and the nearer it is, the bigger the jump. Two cameras side by side do the same. A point seen at column uLu_L in the left image appears at uRu_R in the right one; the difference is the disparity d=uL−uRd = u_L - u_R. For cameras a baseline BB apart with focal length ff (in pixels):

Z=f Bd Z = \frac{f\,B}{d}

Finding dd for every pixel is the stereo matching problem. The simplest method, block matching, takes a small window around each left pixel and slides it along the same row of the right image, keeping the shift where the pixels differ least. Real systems use smarter matching (semi-global matching, or networks such as RAFT-Stereo), but the geometry is the same.

Because depth is fB/dfB/d, a fixed error in dd costs more and more far away:

ΔZ≈Z2f B Δd \Delta Z \approx \frac{Z^2}{f\,B}\,\Delta d

Double the distance, four times the error. That is why stereo cameras are excellent up close and poor at 50 m, and why cars that rely on cameras put them as far apart as possible.

Try it

Try it: a stereo camera on our car

A second camera 0.5 m to the right of the first. The right picture shows the disparity found by block matching: red near, blue far, dark where no clear match exists (plain sky, smooth road, or a place only one camera can see). The chart compares the real error with the formula.

Interactive: this part runs in your browser.

Code

Code: block matching from scratch

A random-dot pair of images: no shapes at all, yet matching finds the hidden box. This runs in your browser.

Python · NumPy
import numpy as np

rng = np.random.default_rng(0)
H, W, F, B = 40, 100, 100.0, 0.5            # image size, focal length (pixels), distance between the cameras (m)

# A random-dot scene: a far background wall at 25 m, and a box at 5 m in the middle.
depth = np.full((H, W), 25.0)
depth[12:28, 40:62] = 5.0
disparity_true = F * B / depth             # how far each point shifts between the two images, in pixels
texture = rng.random((H, W + 40))           # the pattern painted on everything

left = texture[:, 20:20 + W].copy()
right = left.copy()
for v in range(H):                          # paint each left-image point into the right image, shifted left by its disparity
    for u in sorted(range(W), key=lambda u: disparity_true[v, u]):   # far points first, near points on top
        ur = int(round(u - disparity_true[v, u]))
        if 0 <= ur < W:
            right[v, ur] = left[v, u]

def block_match(L, R, max_d=14, win=2):
    """For each left pixel, the shift d whose small window in the right image matches best (smallest abs difference)."""
    best = np.full(L.shape, np.inf)
    disp = np.zeros(L.shape)
    for d in range(max_d + 1):
        diff = np.full(L.shape, 9.0)
        diff[:, d:] = np.abs(L[:, d:] - R[:, :W - d])
        # sum over the window by adding shifted copies
        cost = sum(np.roll(np.roll(diff, dy, 0), dx, 1) for dy in range(-win, win + 1) for dx in range(-win, win + 1))
        better = cost < best
        best[better], disp[better] = cost[better], d
    return disp

disp = block_match(left, right)
z = F * B / np.maximum(disp, 0.5)
print("depth found (m), every 4th row and column:   (. far wall, # the box)")
for v in range(2, H - 2, 4):
    print("".join("#" if z[v, u] < 10 else "." for u in range(16, W - 2, 2)))
inner = (slice(14, 26), slice(44, 58))
print("(the wrong cells at the box edges are points only one camera can see: occlusions)")
print(f"box: true 5.0 m, found {np.median(z[inner]):.2f} m · wall: true 25.0 m, found {np.median(z[2:10, 20:90]):.2f} m")
Open in playground ↗
Beginner

Learning depth without depth labels

Our U-Net learned depth from labels the simulator gave for free. Real depth labels need a lidar, are sparse, and are expensive. Self-supervised depth (Monodepth, Godard et al., 2017 and 2019) avoids them with a clever trick:

  1. A network looks at the left image alone and predicts a depth for every pixel.
  2. Using that depth and the known camera geometry, rebuild the left image from the right one: each left pixel fetches the right pixel its depth says it should match.
  3. If the depth is right, the rebuilt image looks like the real one. The difference between them is the loss.

No one ever tells the network a distance. It learns depth because depth is the only thing that makes the rebuilt image match. The same works with one camera and consecutive video frames, if the network also predicts how the camera moved between them.

Try it

Try it: the training signal, by hand

Rebuild the left view from the right one. With "everything at one distance", move the slider: one distance makes the road line up, another the far buildings, another the cars, but never all at once. Only a correct depth for every pixel makes the whole difference image dark. That pressure is all a self-supervised network needs.

Interactive: this part runs in your browser.

Code

Depth foundation models

Since 2023, foundation models for depth, trained on millions of images of every kind (Depth Anything, Metric3D, and others), estimate depth from a single photo of almost any scene without fine-tuning. Two caveats matter for driving:

  • Many output relative depth: correct in shape but in unknown units. One camera alone cannot know the scale of the world. Scale has to come from somewhere else: a known camera height, a second camera, lidar or the car's own motion.
  • They are large and slow compared with a network built for one car's camera, so in a car they are mostly used to label data or as a starting point for fine-tuning.
Python (Colab)
# In Google Colab (a GPU helps but is not needed). A depth "foundation model", trained on millions of images,
# estimates depth from one photo of any scene. We test it on your simulator recording, against the true depth.
!pip install -q transformers
from google.colab import files
import numpy as np
from PIL import Image
from transformers import pipeline

depth_model = pipeline("depth-estimation", model="depth-anything/Depth-Anything-V2-Small-hf")
d = np.load(list(files.upload())[0])          # one recording from the course
errors = []
for f in range(0, len(d["images"]), max(1, len(d["images"]) // 40)):          # 40 frames spread through the drive
    img = Image.fromarray(d["images"][f]).resize((480, 240))                  # bigger input, more detail
    pred = np.array(depth_model(img)["predicted_depth"].squeeze(), dtype=np.float64)
    pred = np.array(Image.fromarray(pred.astype(np.float32)).resize((d["depth"].shape[2], d["depth"].shape[1])), dtype=np.float64)
    true = d["depth"][f].astype(np.float64) * 0.25
    ok = (d["depth"][f] < 255) & (true > 1) & (true < 50)
    # This model gives RELATIVE inverse depth: bigger means nearer, in unknown units. One camera cannot know the scale
    # of the world, so fit a scale and shift (least squares, in inverse depth) to the true depth before comparing.
    A = np.stack([pred[ok], np.ones(ok.sum())], 1)
    s, t = np.linalg.lstsq(A, 1 / true[ok], rcond=None)[0]
    z = 1 / np.clip(s * pred + t, 1e-3, None)
    errors.append(np.median(np.abs(z[ok] - true[ok]) / true[ok]))
print(f"median relative depth error after scale alignment: {np.median(errors):.1%}")
print("Compare: the course's U-Net, trained on this simulator with depth labels, has a median error of about 0.5 m within 30 m.")
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).
Check yourself

Quiz

1. Two cameras 0.5 m apart with f = 170 px see a disparity of 5 px. How far away is the point?

2. The distance doubles. Roughly how does stereo depth error change?

3. How does a self-supervised depth network learn without depth labels?

4. Why do many single-camera depth models output only relative depth?

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