Algorithm Search⌘K

Algorithmadvanced

PatchMatch stereo

Also called slanted support window stereo.

Estimate a slanted disparity plane per pixel by PatchMatch propagation and random refinement, so that windows on slanted surfaces match well.

Time
Θ(T W H s log D) worst · average · best
Space
Θ(W H) extra
Where
D = the largest disparity in pixels; H = the image height in pixels; T = the number of iterations; W = the image width in pixels; s = the number of pixels in a window
Properties
randomizednot exactofflineiterative
Origin
Michael Bleyer, Christoph Rhemann, Carsten Rother, 2011

PatchMatch stereo is a local method for stereo matching that gives every pixel its own plane in disparity space, d=ax+by+cd = a x + b y + c, instead of one disparity. The cost of a pixel is computed over a window whose pixels are shifted by the disparities of that plane, so a window on a slanted surface is matched with the slant, and not as a fronto-parallel square. The planes are continuous, so there are infinitely many of them, and an exhaustive search is not possible. Bleyer, Rhemann and Rother (2011) search them with the scheme of PatchMatch: random planes at the start, then propagation of good planes to neighbors, to the other view, and to the next frame, and a random refinement around the current plane. It differs from block matching in the window shape and from semi-global matching in having no smoothness term: neighbors agree only because they share good planes.

In plain words

Usual stereo methods compare a square around each pixel with a square in the other image. On a road or a wall seen at an angle, the square in one image is stretched in the other, so the comparison is poor. PatchMatch stereo lets each pixel guess a tilted plane, so its square can be stretched to fit. There are too many planes to try all of them. So each pixel starts with a random plane, and then the image is swept several times. At each pixel, the program tries the planes of its neighbors, the plane of the matching pixel in the other image, and a few small random changes to its own plane, and keeps whatever matches best. A good plane found anywhere on a surface spreads over the whole surface.

The problem

Input. A rectified pair of images, the left view I0I_0 and the right view I1I_1, of W×HW \times H pixels, the right camera to the right of the left one. Pixel (x,y)(x, y) is img[y][x]. A largest disparity DD, a window radius, and the parameters γ,α,τcol,τgrad\gamma, \alpha, \tau_{col}, \tau_{grad} of the cost.

Output. For each pixel pp of each view, a plane fp=(a,b,c)f_p = (a, b, c) with 0≤dp≤D0 \le d_p \le D, where dp=apx+bpy+cd_p = a p_x + b p_y + c is the disparity of pp. The aim is

fp=arg min⁡fm(p,f),m(p,f)=∑q∈Wpw(p,q) ρ(q, q−(afqx+bfqy+cf)),f_p = \operatorname*{arg\,min}_{f} m(p, f), \qquad m(p, f) = \sum_{q \in W_p} w(p, q)\, \rho\big(q,\ q - (a_f q_x + b_f q_y + c_f)\big),

with WpW_p the square window of pp, the adaptive weight w(p,q)=e−∣I(p)−I(q)∣/γw(p, q) = e^{-|I(p) - I(q)| / \gamma}, and the pixel dissimilarity

ρ(q,q′)=(1−α)min⁡(∣I(q)−I′(q′)∣,τcol)+αmin⁡(∥∇I(q)−∇I′(q′)∥1,τgrad).\rho(q, q') = (1 - \alpha) \min(|I(q) - I'(q')|, \tau_{col}) + \alpha \min(\|\nabla I(q) - \nabla I'(q')\|_1, \tau_{grad}).

Here I′I' is the other view, q′q' has a fractional xx and is read by linear interpolation, and for a pixel of the right view the disparity is added instead of subtracted. The paper uses RGB colors and the L1 color distance; the code on this page uses gray values. The method returns a local optimum of mm per pixel, found by random search, not the exact minimum.

The algorithm

  1. PATCHMATCH-STEREO(I_0, I_1, D, T)
  2. 1for each view v and pixel p do f_v[p] ← the plane through a random z_0 in [0, D] at p with a random unit normal; m_v[p] ← m(p, f_v[p])
  3. 2for k ← 0 to T - 1 do
  4. 3for v ← 0, 1 do ▷ all left pixels, then all right pixels
  5. 4if k is even then scan from the top left and set s ← -1 else from the bottom right and set s ← +1
  6. 5for each pixel p = (x, y) of view v in that order do
  7. 6for q in {(x + s, y), (x, y + s)} inside the image do TRY(p, f_v[q]) ▷ spatial propagation
  8. 7for each pixel p' of view 1 - v whose match rounds to p do TRY(p, TRANSFER(f_{1-v}[p'])) ▷ view propagation
  9. 8Δz ← D / 2; Δn ← 1
  10. 9while Δz ≥ 0.1 do ▷ plane refinement
  11. 10z_0 ← d_p + a random value in [-Δz, Δz]; n ← unit(n_p + a random vector in [-Δn, Δn]^3)
  12. 11TRY(p, the plane through z_0 at p with normal n)
  13. 12Δz ← Δz / 2; Δn ← Δn / 2
  14. 13return f_0, f_1
  15. TRY(p, f): if 0 ≤ f(p) ≤ D and m(p, f) < m_v[p] then f_v[p] ← f; m_v[p] ← m(p, f)

Planes. A point (x0,y0,z0)(x_0, y_0, z_0) of disparity space and a unit normal nn with nz≠0n_z \ne 0 give the plane a=−nx/nza = -n_x / n_z, b=−ny/nzb = -n_y / n_z, c=(nxx0+nyy0+nzz0)/nzc = (n_x x_0 + n_y y_0 + n_z z_0) / n_z, so that ax0+by0+c=z0a x_0 + b y_0 + c = z_0. Line L1 draws z0z_0 uniformly in the continuous range and nn as a random unit vector. Line L10 uses the same form: it moves the disparity at pp and the normal, and line L11 builds the new plane through the new disparity at pp.

Propagation. Lines L4 to L6 are the propagation of PatchMatch with the scan order reversed on odd iterations. Line L7 is new: a pixel p′p' of the other view with disparity d′d' matches the point (px′±d′,py′)(p'_x \pm d', p'_y) of this view, and every p′p' whose match rounds to pp offers its plane. A right plane (a,b,c)(a, b, c) describes in left coordinates the plane (a,b,c)/(1+a)(a, b, c) / (1 + a), and a left plane describes in right coordinates the plane (a,b,c)/(1−a)(a, b, c) / (1 - a). To see the first, put x=x′+dx = x' + d into d=ax′+by+cd = a x' + b y + c and solve for dd. The paper also has temporal propagation from the previous frame of a video. The code has one frame and leaves it out.

Refinement. Lines L8 to L12 try one random change per scale. The ranges start at D/2D / 2 for the disparity and 1 for each normal component, and halve until the disparity range is below 0.1 pixel. This is the random search of PatchMatch in the space of planes.

Post-processing. After the iterations, the paper (1) marks a left pixel invalid when its disparity differs by more than 1 from the disparity of its match in the right map (left-right check), (2) fills an invalid pixel with the lower of the disparities that the planes of the nearest valid pixels to its left and right give at the pixel, since occluded pixels lie on the background, and (3) smooths the filled pixels with a weighted median filter. The code has (1) and (2).

Example

Planes. At pixel (5,3)(5, 3), take z0=4z_0 = 4 and the normal n=(0.6,0,0.8)n = (0.6, 0, 0.8). Then a=−0.75a = -0.75, b=0b = 0 and c=(0.6⋅5+0.8⋅4)/0.8=7.75c = (0.6 \cdot 5 + 0.8 \cdot 4) / 0.8 = 7.75, and indeed −0.75⋅5+7.75=4-0.75 \cdot 5 + 7.75 = 4. In the right view, the same surface is the plane (−0.75,0,7.75)/1.75=(−0.4286,0,4.4286)(-0.75, 0, 7.75) / 1.75 = (-0.4286, 0, 4.4286). The left pixel x=5x = 5 with disparity 4 matches the right pixel x′=1x' = 1, and the right plane gives −0.4286+4.4286=4-0.4286 + 4.4286 = 4 there, as it must.

A slanted surface. The test file builds a 20×1220 \times 12 pair from a smooth texture on the plane d=0.15x+0.05y+2d = 0.15 x + 0.05 y + 2, with a 7×77 \times 7 window, D=8D = 8, the parameters {γ,α,τcol,τgrad}={10,0.9,10,2}\{\gamma, \alpha, \tau_{col}, \tau_{grad}\} = \{10, 0.9, 10, 2\} of the paper, and seed 3. The sum of the left costs after each step is:

after L1 iteration 1 iteration 2 iteration 3
sum of m0[p]m_0[p] 3992.4 3493.4 3292.5 3239.7

Over the 48 interior pixels, the mean disparity error is 0.047 pixel and the largest is 0.42 pixel. The same code with the normal fixed to (0,0,1)(0, 0, 1), which allows only fronto-parallel windows, has a mean error of 0.21 pixel. The window spans 7 columns, over which the true disparity changes by 0.9 pixel, so a fronto-parallel window cannot fit it.

Correctness

The full proof is in proofs/correctness.md. It has three parts.

  1. Plane algebra. The plane built in lines L1 and L11 has disparity z0z_0 at pp and normal nn. TRANSFER maps a plane of one view to the plane of the same surface in the other view: if dd is the disparity of the left plane at xx, then the right plane has the same disparity dd at x−dx - d. TRANSFER from left to right and back is the identity.
  2. Invariant. At all times mv[p]=m(p,fv[p])m_v[p] = m(p, f_v[p]) and 0≤fv[p](p)≤D0 \le f_v[p](p) \le D, and mv[p]m_v[p] never increases, because TRY accepts only a strictly lower cost.
  3. What is computed. The output is, at each pixel, the best of all planes the run has tried at that pixel. No result bounds the gap to the true minimum of m(p,⋅)m(p, \cdot), which is a nonconvex function of three real parameters.
Proof: PatchMatch stereo builds correct planes, transfers them correctly between views, and never increases a costfull

We use the pseudocode of the page. A plane f=(a,b,c)f = (a, b, c) of a view gives the disparity f(x,y)=ax+by+cf(x, y) = a x + b y + c at the pixel (x,y)(x, y) of that view. A left point (x,y)(x, y) with disparity dd matches the right point (x−d,y)(x - d, y), and a right point (x′,y)(x', y) with disparity dd matches the left point (x′+d,y)(x' + d, y).

Lemma 1 (plane from point and normal). Let n=(nx,ny,nz)n = (n_x, n_y, n_z) with nz≠0n_z \ne 0, and set a=−nx/nza = -n_x / n_z, b=−ny/nzb = -n_y / n_z, c=(nxx0+nyy0+nzz0)/nzc = (n_x x_0 + n_y y_0 + n_z z_0) / n_z. Then ax0+by0+c=z0a x_0 + b y_0 + c = z_0, and the set {(x,y,z):z=ax+by+c}\{(x, y, z) : z = a x + b y + c\} is the plane through (x0,y0,z0)(x_0, y_0, z_0) with normal nn.

Proof. ax0+by0+c=(−nxx0−nyy0+nxx0+nyy0+nzz0)/nz=z0a x_0 + b y_0 + c = (-n_x x_0 - n_y y_0 + n_x x_0 + n_y y_0 + n_z z_0) / n_z = z_0. Multiply z=ax+by+cz = a x + b y + c by nzn_z and rearrange: nx(x−x0)+ny(y−y0)+nz(z−z0)=0n_x (x - x_0) + n_y (y - y_0) + n_z (z - z_0) = 0, which is the plane through the point with normal nn. □\square

So line L1 and line L11 give a plane with disparity z0z_0 at pp. In particular line L1 gives 0≤f(p)≤D0 \le f(p) \le D, since z0∈[0,D]z_0 \in [0, D].

Lemma 2 (transfer). Let f=(a,b,c)f = (a, b, c) be a plane of the right view with 1+a≠01 + a \ne 0, and let g=(a,b,c)/(1+a)g = (a, b, c) / (1 + a). For every right point (x′,y)(x', y) with disparity d=f(x′,y)d = f(x', y), the matching left point x=x′+dx = x' + d has g(x,y)=dg(x, y) = d. Symmetrically, for a left plane ff with 1−a≠01 - a \ne 0 and g=(a,b,c)/(1−a)g = (a, b, c) / (1 - a), every left point (x,y)(x, y) with d=f(x,y)d = f(x, y) has g(x−d,y)=dg(x - d, y) = d. The two maps are inverse to each other.

Proof. Right to left: (1+a) g(x,y)=a(x′+d)+by+c=(ax′+by+c)+ad=d+ad(1 + a)\, g(x, y) = a (x' + d) + b y + c = (a x' + b y + c) + a d = d + a d, so g(x,y)=dg(x, y) = d. Left to right: (1−a) g(x−d,y)=a(x−d)+by+c=d−ad(1 - a)\, g(x - d, y) = a (x - d) + b y + c = d - a d, so g(x−d,y)=dg(x - d, y) = d. For the inverse, apply the right to left map to g=(a,b,c)/(1−a)g = (a, b, c) / (1 - a). Its first entry is a′=a/(1−a)a' = a / (1 - a), and 1+a′=1/(1−a)1 + a' = 1 / (1 - a), so g/(1+a′)=(a,b,c)g / (1 + a') = (a, b, c). The other order is the same computation with −a-a. □\square

So a plane offered in line L7 describes, in the coordinates of view vv, the same set of scene points as the plane of p′p' in the other view. The pixel pp is the rounded match of p′p', so pp lies on that surface up to rounding.

Lemma 3 (invariant). At every point of the run, for each view vv and pixel pp: (a) mv[p]=m(p,fv[p])m_v[p] = m(p, f_v[p]); (b) 0≤fv[p](p)≤D0 \le f_v[p](p) \le D; (c) the value of mv[p]m_v[p] is never larger than an earlier value.

Proof. After line L1, (a) holds by the assignment and (b) by Lemma 1. Only TRY changes fv[p]f_v[p] or mv[p]m_v[p], and it changes both at once, to a plane ff and its cost m(p,f)m(p, f), so (a) stays true. TRY accepts ff only when 0≤f(p)≤D0 \le f(p) \le D, so (b) stays true. It accepts only when m(p,f)<mv[p]m(p, f) < m_v[p], which gives (c). □\square

Theorem. PATCHMATCH-STEREO returns for each pixel pp of each view a plane fv[p]f_v[p] with 0≤fv[p](p)≤D0 \le f_v[p](p) \le D and

m(p,fv[p])=min⁡{ m(p,f):f was passed to TRY at p and 0≤f(p)≤D }∪{m(p,f0)},m(p, f_v[p]) = \min \{\, m(p, f) : f \text{ was passed to TRY at } p \text{ and } 0 \le f(p) \le D \,\} \cup \{ m(p, f_0) \},

where f0f_0 is the plane of line L1. The cost of each pixel does not increase from one iteration to the next.

Proof. By Lemma 3, mv[p]m_v[p] starts at m(p,f0)m(p, f_0) and is replaced by m(p,f)m(p, f) exactly when a valid candidate ff is strictly better. So at the end it is the least value among f0f_0 and all valid candidates, and by Lemma 3 (a) it equals m(p,fv[p])m(p, f_v[p]). The monotone part is Lemma 3 (c). ■\blacksquare

What is not proved. The theorem does not say that fv[p]f_v[p] minimizes m(p,⋅)m(p, \cdot) over all planes. The function is a sum of truncated terms of an interpolated image and is not convex in (a,b,c)(a, b, c); the method finds the best plane among those it tried. How quickly good planes appear depends on the random numbers and on how much of the scene is made of planes, as in the analysis of PatchMatch.

Complexity

The model is the real RAM: plane parameters and costs are real numbers, and exp⁡\exp and linear interpolation cost O(1)O(1). Let ss be the number of pixels in a window.

  • One cost. m(p,f)m(p, f) sums over ss pixels, so it takes Θ(s)\Theta(s) time.
  • One iteration. Each pixel of each view gets 2 spatial candidates and ⌊log⁡2(5D)⌋+1\lfloor \log_2(5 D) \rfloor + 1 refinement candidates (the number of halvings of D/2D/2 down to 0.1). Every pixel of the other view offers its plane to exactly one pixel in line L7, so the view candidates add WHW H per view. One iteration takes Θ(WHslog⁡D)\Theta(W H s \log D) time for D≥1D \ge 1.
  • Number of iterations. TT is a parameter; the paper uses 3. The total is Θ(TWHslog⁡D)\Theta(T W H s \log D), plus Θ(WHs)\Theta(W H s) for the start.
  • Space. Two plane maps and two cost maps, Θ(WH)\Theta(W H). The code also caches the weights of every window, which takes Θ(WHs)\Theta(W H s).

The paper uses a 35×3535 \times 35 window, so s=1225s = 1225, and reports about one minute per Middlebury pair for unoptimized C code (measured, 2011).

Properties

  • Slanted support. The window follows a plane, so slanted surfaces match without the bias of fronto-parallel windows. The plane also gives subpixel disparities with no separate refinement step.
  • Adaptive weights. The weight w(p,q)w(p, q) removes most pixels of other surfaces from the window, as in adaptive support weights. Large windows then help without blurring edges.
  • Randomized. The output depends on the random numbers. The cost of each pixel never increases from one step to the next.
  • No smoothness term. Each pixel minimizes its own cost. Neighbors agree because good planes propagate.
  • Robust cost. The truncation at τcol\tau_{col} and τgrad\tau_{grad} limits the effect of pixels that do not match, for example in occlusions.

Variants and improvements

  • Fronto-parallel windows. Fix n=(0,0,1)n = (0, 0, 1), as the paper notes, and the method searches constant disparities with continuous values. The example above shows what this loses on a slanted plane.
  • Data term for global methods. Section 2.4 of the paper uses the costs of the planes of a pixel and its neighbors as labels in an energy minimized with alpha-expansion.
  • Multi-view PatchMatch. Galliani et al. (2015) and Schönberger et al. (2016) propagate depth and normal per pixel over many views, with view selection, in multi-view stereo.
  • Faster propagation. Galliani et al. (2015) propagate in a red and black checkerboard pattern on the GPU, so that half of the pixels update in parallel.
  • Other costs. The census transform or normalized cross-correlation replaces the color and gradient term when the cameras differ in gain.

When to use it

Use PatchMatch stereo when the scene has large slanted surfaces (roads, walls, floors) and you need subpixel disparities from a local method. It is slower than block matching and semi-global matching with small windows, because each cost covers a large window and many candidates. Use semi-global matching when you need a predictable run time or a smoothness prior over textureless areas.

Pitfalls

  • Sign of the disparity. For the left view the match is at qx−dq_x - d, for the right view at qx+dq_x + d. Mixing them up in the cost or in TRANSFER gives planes that never agree between views.
  • Degenerate planes. A normal with nzn_z near 0 gives huge aa or bb. Reject such normals in line L10, and skip TRANSFER when 1±a=01 \pm a = 0.
  • Disparity range at pp only. TRY checks the range at pp, not over the window. Window pixels can then read the other image outside its border; clamp the interpolation there.
  • Strict acceptance. TRY must use <<, or a pixel can flip between planes of equal cost and the costs are no longer monotone.
  • Stale view map. Line L7 needs the planes of the other view at the time of the pass. Build the map from other-view pixels to the pixels they hit at the start of each pass, after the other view has finished.
  • Fill direction. The fill step takes the lower disparity, which belongs to the background. Taking the higher one smears the foreground over the occluded area.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

patchmatch_stereo.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/patchmatch-stereo/. The authors are listed in prov/G3M5MP.jsonl.

"""PatchMatch stereo (Bleyer, Rhemann and Rother 2011) on grayscale images.

Images are lists of rows of numbers, indexed img[y][x], rectified, with the
right camera to the right of the left one. View 0 is the left view and view 1
the right view. A plane f = (a, b, c) gives the disparity a x + b y + c at the
pixel (x, y) of its own view. A left pixel (x, y) with disparity d matches the
right point (x - d, y); a right pixel (x, y) matches the left point (x + d, y).

Differences from the paper: gray values instead of RGB, so the weight and the
color term use one channel; no temporal propagation (one frame); the weighted
median filter of the post-processing is left out.
"""

import math
import random

INF = float("inf")


# ---------------------------------------------------------------- planes


def plane_from_point_normal(x0, y0, z0, n):
    """Plane (a, b, c) through disparity z0 at pixel (x0, y0) with normal n, n[2] != 0."""
    nx, ny, nz = n
    a = -nx / nz
    b = -ny / nz
    c = (nx * x0 + ny * y0 + nz * z0) / nz
    return (a, b, c)


def normal_of_plane(f):
    """Unit normal (with a positive z part) of the plane (a, b, c)."""
    a, b, _ = f
    s = math.sqrt(a * a + b * b + 1.0)
    return (-a / s, -b / s, 1.0 / s)


def disparity(f, x, y):
    a, b, c = f
    return a * x + b * y + c


def transfer_plane(f, from_view):
    """Express the plane of one view in the coordinates of the other view.

    Left to right: x' = x - d, so d = (a x' + b y + c) / (1 - a).
    Right to left: x = x' + d, so d = (a x + b y + c) / (1 + a).
    Returns None for the degenerate plane with 1 - a = 0 or 1 + a = 0.
    """
    a, b, c = f
    k = 1.0 - a if from_view == 0 else 1.0 + a
    if abs(k) < 1e-12:
        return None
    return (a / k, b / k, c / k)


# ---------------------------------------------------------------- images


def gradient(img):
    """Central difference gradient (gx, gy), one-sided at the border."""
    h, w = len(img), len(img[0])
    gx = [[0.0] * w for _ in range(h)]
    gy = [[0.0] * w for _ in range(h)]
    for y in range(h):
        for x in range(w):
            x0, x1 = max(x - 1, 0), min(x + 1, w - 1)
            y0, y1 = max(y - 1, 0), min(y + 1, h - 1)
            gx[y][x] = (img[y][x1] - img[y][x0]) / (x1 - x0) if x1 > x0 else 0.0
            gy[y][x] = (img[y1][x] - img[y0][x]) / (y1 - y0) if y1 > y0 else 0.0
    return gx, gy


def sample_row(row, x):
    """Linear interpolation in one row, clamped at the ends."""
    w = len(row)
    if x <= 0:
        return row[0]
    if x >= w - 1:
        return row[w - 1]
    i = int(x)
    t = x - i
    return (1.0 - t) * row[i] + t * row[i + 1]


class View:
    """One image with its gradient and the support weights of its windows."""

    def __init__(self, img, radius, gamma):
        self.img = img
        self.h, self.w = len(img), len(img[0])
        self.gx, self.gy = gradient(img)
        self.window = {}
        for y in range(self.h):
            for x in range(self.w):
                ip = img[y][x]
                ws = []
                for qy in range(max(0, y - radius), min(self.h, y + radius + 1)):
                    for qx in range(max(0, x - radius), min(self.w, x + radius + 1)):
                        ws.append((qx, qy, math.exp(-abs(ip - img[qy][qx]) / gamma)))
                self.window[(x, y)] = ws


class Params:
    def __init__(self, radius=3, max_disp=8.0, gamma=10.0, alpha=0.9,
                 tau_col=10.0, tau_grad=2.0, iterations=3, fronto=False):
        self.radius = radius
        self.max_disp = max_disp
        self.gamma = gamma
        self.alpha = alpha
        self.tau_col = tau_col
        self.tau_grad = tau_grad
        self.iterations = iterations
        self.fronto = fronto


def plane_cost(views, v, x, y, f, prm):
    """m(p, f): the weighted sum of rho over the window of p in view v."""
    me, other = views[v], views[1 - v]
    sign = -1.0 if v == 0 else 1.0
    a, b, c = f
    total = 0.0
    for qx, qy, wq in me.window[(x, y)]:
        xq = qx + sign * (a * qx + b * qy + c)
        col = abs(me.img[qy][qx] - sample_row(other.img[qy], xq))
        grad = (abs(me.gx[qy][qx] - sample_row(other.gx[qy], xq))
                + abs(me.gy[qy][qx] - sample_row(other.gy[qy], xq)))
        rho = ((1.0 - prm.alpha) * min(col, prm.tau_col)
               + prm.alpha * min(grad, prm.tau_grad))
        total += wq * rho
    return total


def _random_normal(rng, fronto):
    if fronto:
        return (0.0, 0.0, 1.0)
    while True:
        n = (rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1))
        s = math.sqrt(sum(t * t for t in n))
        if s > 1e-9 and abs(n[2]) / s > 1e-3:
            n = tuple(t / s for t in n)
            return n if n[2] > 0 else tuple(-t for t in n)


def _in_range(f, x, y, prm):
    d = disparity(f, x, y)
    return 0.0 <= d <= prm.max_disp


def patchmatch_stereo(left, right, prm, rng, history=None):
    """Return (planes, costs): two dicts per view, keyed by (x, y).

    history, if a list, gets a copy of the costs of both views after the
    initialization and after each iteration.
    """
    views = [View(left, prm.radius, prm.gamma), View(right, prm.radius, prm.gamma)]
    planes = [{}, {}]
    costs = [{}, {}]
    for v in (0, 1):
        for y in range(views[v].h):
            for x in range(views[v].w):
                z0 = rng.uniform(0.0, prm.max_disp)
                f = plane_from_point_normal(x, y, z0, _random_normal(rng, prm.fronto))  # @line L1
                planes[v][(x, y)] = f
                costs[v][(x, y)] = plane_cost(views, v, x, y, f, prm)
    if history is not None:
        history.append([dict(costs[0]), dict(costs[1])])

    def try_plane(v, x, y, f):
        if f is None or not _in_range(f, x, y, prm):
            return
        m = plane_cost(views, v, x, y, f, prm)
        if m < costs[v][(x, y)]:
            planes[v][(x, y)] = f
            costs[v][(x, y)] = m

    for it in range(prm.iterations):  # @line L2
        for v in (0, 1):  # @line L3
            o = 1 - v
            # Pixels of the other view, grouped by the pixel of view v they hit.
            hits = {}
            for (ox, oy), g in planes[o].items():
                d = disparity(g, ox, oy)
                tx = int(math.floor(ox + (d if o == 1 else -d) + 0.5))
                hits.setdefault((tx, oy), []).append(g)
            h, w = views[v].h, views[v].w
            if it % 2 == 0:  # @line L4
                order = [(x, y) for y in range(h) for x in range(w)]
                step = -1
            else:
                order = [(x, y) for y in range(h - 1, -1, -1) for x in range(w - 1, -1, -1)]
                step = 1
            for x, y in order:  # @line L5
                for nx, ny in ((x + step, y), (x, y + step)):  # @line L6
                    if 0 <= nx < w and 0 <= ny < h:
                        try_plane(v, x, y, planes[v][(nx, ny)])
                for g in hits.get((x, y), ()):  # @line L7
                    try_plane(v, x, y, transfer_plane(g, o))
                dz = prm.max_disp / 2.0  # @line L8
                dn = 1.0
                while dz >= 0.1:  # @line L9
                    f = planes[v][(x, y)]
                    z0 = disparity(f, x, y) + rng.uniform(-dz, dz)  # @line L10
                    n = normal_of_plane(f)
                    if not prm.fronto:
                        n = tuple(t + rng.uniform(-dn, dn) for t in n)
                        s = math.sqrt(sum(t * t for t in n))
                        n = tuple(t / s for t in n) if s > 1e-9 else None
                    if n is not None and n[2] > 1e-3:
                        try_plane(v, x, y, plane_from_point_normal(x, y, z0, n))  # @line L11
                    dz /= 2.0  # @line L12
                    dn /= 2.0
        if history is not None:
            history.append([dict(costs[0]), dict(costs[1])])
    return planes, costs  # @line L13


def disparity_maps(planes, shape):
    h, w = shape
    return [[[disparity(planes[v][(x, y)], x, y) for x in range(w)] for y in range(h)]
            for v in (0, 1)]


def left_right_check(dl, dr, tol=1.0):
    """Mark a left pixel invalid when its match in the right map disagrees by more than tol."""
    h, w = len(dl), len(dl[0])
    valid = [[False] * w for _ in range(h)]
    for y in range(h):
        for x in range(w):
            xr = int(math.floor(x - dl[y][x] + 0.5))
            if 0 <= xr < w and abs(dl[y][x] - dr[y][xr]) <= tol:
                valid[y][x] = True
    return valid


def fill_invalid(dl, valid, planes_left):
    """Fill each invalid pixel with the lower of the disparities that the planes
    of the nearest valid pixels to its left and to its right give at the pixel."""
    h, w = len(dl), len(dl[0])
    out = [row[:] for row in dl]
    for y in range(h):
        for x in range(w):
            if valid[y][x]:
                continue
            cand = []
            for step in (-1, 1):
                k = x + step
                while 0 <= k < w and not valid[y][k]:
                    k += step
                if 0 <= k < w:
                    cand.append(disparity(planes_left[(k, y)], x, y))
            if cand:
                out[y][x] = min(cand)
    return out


def best_fronto_parallel(left, right, prm, step=0.25):
    """Reference: the best constant disparity per window, on a grid of step pixels."""
    views = [View(left, prm.radius, prm.gamma), View(right, prm.radius, prm.gamma)]
    h, w = len(left), len(left[0])
    out = [[0.0] * w for _ in range(h)]
    ds = [i * step for i in range(int(prm.max_disp / step) + 1)]
    for y in range(h):
        for x in range(w):
            best = INF
            for d in ds:
                m = plane_cost(views, 0, x, y, (0.0, 0.0, d), prm)
                if m < best:
                    best, out[y][x] = m, d
    return out


if __name__ == "__main__":
    rng = random.Random(1)
    img = [[rng.randrange(256) for _ in range(12)] for _ in range(8)]
    prm = Params(radius=1, max_disp=3.0)
    planes, _ = patchmatch_stereo(img, img, prm, random.Random(2))
    print(disparity_maps(planes, (8, 12))[0][4])
test_patchmatch_stereo.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/patchmatch-stereo/. The authors are listed in prov/G3M5MP.jsonl.

import math
import random

from patchmatch_stereo import (
    Params,
    View,
    disparity,
    disparity_maps,
    fill_invalid,
    left_right_check,
    normal_of_plane,
    patchmatch_stereo,
    plane_cost,
    plane_from_point_normal,
    transfer_plane,
)


def texture(seed):
    rng = random.Random(seed)
    waves = []
    for _ in range(6):
        period = rng.uniform(3.0, 9.0)
        ang = rng.uniform(0.0, math.pi)
        k = 2.0 * math.pi / period
        waves.append((k * math.cos(ang), k * math.sin(ang), rng.uniform(0.0, 6.3), rng.uniform(15.0, 30.0)))

    def g(x, y):
        return 128.0 + sum(a * math.sin(kx * x + ky * y + ph) for kx, ky, ph, a in waves)

    return g


def slanted_scene(fl, w, h, seed):
    """Left image g(x, y); right image g(x' + d_R(x', y), y) for the plane fl."""
    g = texture(seed)
    fr = transfer_plane(fl, 0)
    left = [[g(x, y) for x in range(w)] for y in range(h)]
    right = [[g(x + disparity(fr, x, y), y) for x in range(w)] for y in range(h)]
    return left, right


def test_example_plane() -> None:
    f = plane_from_point_normal(5, 3, 4.0, (0.6, 0.0, 0.8))
    assert all(abs(u - v) < 1e-12 for u, v in zip(f, (-0.75, 0.0, 7.75)))
    assert abs(disparity(f, 5, 3) - 4.0) < 1e-12
    g = transfer_plane(f, 0)
    assert all(abs(u - v) < 1e-12 for u, v in zip(g, (-0.75 / 1.75, 0.0, 7.75 / 1.75)))
    # The left pixel x = 5 with disparity 4 is the right pixel x' = 1.
    assert abs(disparity(g, 1, 3) - 4.0) < 1e-12


def test_plane_normal_round_trip() -> None:
    rng = random.Random(1)
    for _ in range(200):
        n = [rng.gauss(0, 1) for _ in range(3)]
        n[2] = abs(n[2]) + 0.1
        s = math.sqrt(sum(t * t for t in n))
        n = tuple(t / s for t in n)
        x0, y0, z0 = rng.uniform(0, 30), rng.uniform(0, 20), rng.uniform(0, 10)
        f = plane_from_point_normal(x0, y0, z0, n)
        assert abs(disparity(f, x0, y0) - z0) < 1e-9
        assert all(abs(u - v) < 1e-9 for u, v in zip(normal_of_plane(f), n))


def test_transfer_plane() -> None:
    rng = random.Random(2)
    for _ in range(200):
        f = (rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5), rng.uniform(0, 10))
        for v in (0, 1):
            g = transfer_plane(f, v)
            back = transfer_plane(g, 1 - v)
            assert all(abs(u - w) < 1e-9 for u, w in zip(back, f))
            # A point and its match have the same disparity in both planes.
            x, y = rng.uniform(0, 30), rng.uniform(0, 20)
            d = disparity(f, x, y)
            xm = x - d if v == 0 else x + d
            assert abs(disparity(g, xm, y) - d) < 1e-9
    assert transfer_plane((1.0, 0.0, 2.0), 0) is None


def test_cost_zero_at_true_shift() -> None:
    rng = random.Random(3)
    w, h, shift = 16, 9, 2
    left = [[rng.randrange(256) for _ in range(w)] for _ in range(h)]
    right = [[left[y][min(x + shift, w - 1)] for x in range(w)] for y in range(h)]
    prm = Params(radius=2, max_disp=5.0)
    views = [View(left, prm.radius, prm.gamma), View(right, prm.radius, prm.gamma)]
    for y in range(h):
        for x in range(shift + 3, w - 3):
            assert plane_cost(views, 0, x, y, (0.0, 0.0, float(shift)), prm) < 1e-9
            assert plane_cost(views, 0, x, y, (0.0, 0.0, shift + 1.0), prm) > 1.0


def test_slanted_plane_and_monotone_cost() -> None:
    fl = (0.15, 0.05, 2.0)
    w, h = 20, 12
    left, right = slanted_scene(fl, w, h, 5)
    inner = [(x, y) for y in range(3, h - 3) for x in range(9, w - 3)]
    errors = {}
    for fronto in (False, True):
        prm = Params(radius=3, max_disp=8.0, fronto=fronto)
        hist = []
        planes, _ = patchmatch_stereo(left, right, prm, random.Random(3), history=hist)
        for before, after in zip(hist, hist[1:]):
            for v in (0, 1):
                assert all(after[v][p] <= before[v][p] for p in before[v])
        dl, _ = disparity_maps(planes, (h, w))
        e = [abs(dl[y][x] - disparity(fl, x, y)) for x, y in inner]
        errors[fronto] = sum(e) / len(e)
        if not fronto:
            assert max(e) < 0.5
    assert errors[False] < 0.1
    assert errors[False] < errors[True]


def test_left_right_check_and_fill() -> None:
    dl = [[2.0, 2.0, 2.0, 2.0, 2.0, 4.0, 2.0, 2.0]]
    dr = [[2.0] * 8]
    valid = left_right_check(dl, dr)
    # x = 0 and x = 1 match outside the right image; x = 5 disagrees by 2.
    assert valid == [[False, False, True, True, True, False, True, True]]
    planes = {(x, 0): (0.0, 0.0, dl[0][x]) for x in range(8)}
    planes[(4, 0)] = (-0.5, 0.0, 4.0)  # 2.0 at x = 4, 1.5 at x = 5
    out = fill_invalid(dl, valid, planes)
    # x = 5 takes the lower of the plane of x = 4 (1.5) and of x = 6 (2.0).
    assert out[0][5] == 1.5
    # x = 0 and x = 1 have a valid pixel only to the right.
    assert out[0][0] == 2.0 and out[0][1] == 2.0
    assert out[0][2:5] == dl[0][2:5]


def test_deterministic() -> None:
    left, right = slanted_scene((0.1, 0.0, 1.0), 10, 6, 9)
    prm = Params(radius=1, max_disp=4.0, iterations=1)
    a = patchmatch_stereo(left, right, prm, random.Random(4))
    b = patchmatch_stereo(left, right, prm, random.Random(4))
    assert a == b

History

Slanted windows and plane fitting have a long history in stereo, but earlier methods used a few planes per segment or a discrete set of slants. Bleyer, Rhemann and Rother (2011) let each pixel have its own continuous plane and used PatchMatch of Barnes et al. (2009) to search them. With a 35×3535 \times 35 window and {γ,α,τcol,τgrad}={10,0.9,10,2}\{\gamma, \alpha, \tau_{col}, \tau_{grad}\} = \{10, 0.9, 10, 2\} they reported the best result of the Middlebury table on the Teddy pair at the time (error above 1 pixel, unoccluded regions). The same propagation of depths and normals then became the core of multi-view PatchMatch methods, including COLMAP.

References

  1. Michael Bleyer, Christoph Rhemann and Carsten Rother, PatchMatch Stereo, stereo matching with slanted support windows, British Machine Vision Conference 2011, pages 14.1 to 14.11, Section 2 (the plane model, the cost with adaptive weights and truncated color and gradient terms, the random initialization, spatial, view and temporal propagation, plane refinement, and the post-processing), Section 2.4 (the data term for global methods) and Section 3 (the parameters and the Middlebury results)
  2. Connelly Barnes, Eli Shechtman, Adam Finkelstein and Dan B Goldman, PatchMatch: a randomized correspondence algorithm for structural image editing, ACM Transactions on Graphics 28(3), Article 24, 2009, Section 3 (random initialization, propagation in alternating scan order and random search, which PatchMatch stereo applies to planes)
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (local methods with slanted windows)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example