Stereo depth

With two rectified cameras, depth is inversely proportional to disparity. Finding the disparity is a matching problem along one row.

What you'll learn
  • Derive depth from disparity for a rectified stereo pair
  • Compute a patch matching cost with sub-pixel interpolation
  • Recognise what makes a disparity map noisy, and what fixes it

Lesson 8 recovered geometry from two arbitrary views. A stereo rig makes it much simpler: two cameras side by side, a baseline \(B\) apart, with parallel optical axes (or images rectified to look that way). Then the epipolar lines are the image rows. A point at depth \(Z\) appears at \(x_L\) in the left image and \(x_R\) in the right, on the same row, and similar triangles give

\[d = x_L - x_R = \frac{f\,B}{Z}, \qquad Z = \frac{f\,B}{d}.\]
A rectified pair seen from above (baseline exaggerated). The strip at the top is one image row: where the point lands in the left image (blue) and the right (green). Move Z: near points have large disparity, far points small — and one pixel of disparity error costs ever more depth.

Differentiating gives the depth uncertainty for a one-pixel disparity error, \(\Delta Z \approx Z^2 / (fB)\). With \(f = 700\) px and \(B = 12\) cm, that is 3 mm at half a metre, 4.8 cm at 2 m and 76 cm at 8 m: stereo is precise up close and coarse far away, and a wider baseline helps.

Matching along a row

For each left pixel, try every disparity \(d\) in a range and score how well the patch around \((x, y)\) on the left matches the patch around \((x - d, y)\) on the right. Disparity.cost uses the mean absolute difference over a \((2r + 1)^2\) patch, with linear interpolation for fractional \(d\):

x2 = x1 - d                         # position in the right image
x2_low = int(x2); alpha = x2 - x2_low
interpolated = (1 - alpha) * img2[y1, x2_low] + alpha * img2[y1, x2_low + 1]
cost += np.abs(img1[y1, x1] - interpolated)
...
return cost / patch_size ** 2

Its test (testScore) passes with an error of \(6 \times 10^{-6}\).

computeDisparity then follows the PatchMatch idea: initialise every pixel with random disparities, keep the best, and improve by random search (the propagation step is written but commented out). Run on the Tsukuba pair at half resolution, two problems show:

  • It stores the wrong number. initRandom draws 50 random disparities, builds a cost slice for each, and then sets disp = np.argmin(disparity_maps, axis=2) — the index of the winning sample, 0–49, not the sampled disparity itself (the range was 0–7). The resulting map takes values up to 49. Keeping the drawn values in an array, disp = samples[np.argmin(...)], fixes it.
  • The consistency check erases everything. consistencyCheck computes diff = np.sum(np.abs(dispL - dispR)), a single number for the whole image, then np.argmin of a scalar is 0, and every pixel is set to 0 - 1 = -1. A left–right check compares per pixel instead: keep \(d_L(x, y)\) only if \(\vert d_L(x, y) + d_R(x - d_L(x, y), y)\vert \le 1\).

The summing kernel in initRandom is also unusual — [[1, 1, 1], [1, -1, 1], [1, 1, 1]] subtracts the centre pixel’s difference instead of adding it; np.ones((3, 3)) was surely meant.

Four panels: the Tsukuba left image with head, lamp and shelves; the repository's disparity map, mostly noise; a 5x5 block-matching map where the lamp and head stand out but the background is speckled; and OpenCV SGBM, a clean map with the lamp brightest.
Left image, the repository's map, plain winner-takes-all block matching (5×5 SAD), and OpenCV's semi-global matching. The lamp is nearest: SGBM puts it at a disparity of 14 px, the head at about 10 and the back wall at 5.

The two working maps differ in one idea. Winner-takes-all picks each pixel’s disparity independently, so textureless regions (the wall, the table) are noise. Semi-global matching adds a penalty for disparity jumps between neighbours and aggregates costs along several directions, which fills those regions from their surroundings:

sgbm = cv2.StereoSGBM_create(minDisparity=0, numDisparities=16, blockSize=5,
                             P1=8 * 25, P2=32 * 25, uniquenessRatio=10)
disparity = sgbm.compute(left_gray, right_gray).astype(np.float32) / 16

(SGBM returns fixed-point disparities, hence the division by 16.)

Try it yourself. Fix initRandom to store the sampled disparities and run the pipeline again; then turn the propagation step back on. Compare with SGBM. For the depth formula: with \(f = 700\) px and \(B = 0.12\) m, what disparity corresponds to 1 m, and how far apart are the depths for disparities 10 and 11?

View source on GitHub →