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.
- Solves
- Stereo matching
- 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
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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, , 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 and the right view , of pixels, the right camera to the right of the left one. Pixel is img[y][x]. A largest disparity , a window radius, and the parameters of the cost.
Output. For each pixel of each view, a plane with , where is the disparity of . The aim is
with the square window of , the adaptive weight , and the pixel dissimilarity
Here is the other view, has a fractional 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 per pixel, found by random search, not the exact minimum.
The algorithm
PATCHMATCH-STEREO(I_0, I_1, D, T)- 1
for 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]) - 2
for k ← 0 to T - 1 do - 3
for v ← 0, 1 do ▷ all left pixels, then all right pixels - 4
if k is even then scan from the top left and set s ← -1 else from the bottom right and set s ← +1 - 5
for each pixel p = (x, y) of view v in that order do - 6
for q in {(x + s, y), (x, y + s)} inside the image do TRY(p, f_v[q]) ▷ spatial propagation - 7
for each pixel p' of view 1 - v whose match rounds to p do TRY(p, TRANSFER(f_{1-v}[p'])) ▷ view propagation - 8
Δz ← D / 2; Δn ← 1 - 9
while Δz ≥ 0.1 do ▷ plane refinement - 10
z_0 ← d_p + a random value in [-Δz, Δz]; n ← unit(n_p + a random vector in [-Δn, Δn]^3) - 11
TRY(p, the plane through z_0 at p with normal n) - 12
Δz ← Δz / 2; Δn ← Δn / 2 - 13
return f_0, f_1 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 of disparity space and a unit normal with give the plane , , , so that . Line L1 draws uniformly in the continuous range and as a random unit vector. Line L10 uses the same form: it moves the disparity at and the normal, and line L11 builds the new plane through the new disparity at .
Propagation. Lines L4 to L6 are the propagation of PatchMatch with the scan order reversed on odd iterations. Line L7 is new: a pixel of the other view with disparity matches the point of this view, and every whose match rounds to offers its plane. A right plane describes in left coordinates the plane , and a left plane describes in right coordinates the plane . To see the first, put into and solve for . 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 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 , take and the normal . Then , and , and indeed . In the right view, the same surface is the plane . The left pixel with disparity 4 matches the right pixel , and the right plane gives there, as it must.
A slanted surface. The test file builds a pair from a smooth texture on the plane , with a window, , the parameters 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 | 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 , 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.
- Plane algebra. The plane built in lines L1 and L11 has disparity at and normal . TRANSFER maps a plane of one view to the plane of the same surface in the other view: if is the disparity of the left plane at , then the right plane has the same disparity at . TRANSFER from left to right and back is the identity.
- Invariant. At all times and , and never increases, because TRY accepts only a strictly lower cost.
- 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 , 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 of a view gives the disparity at the pixel of that view. A left point with disparity matches the right point , and a right point with disparity matches the left point .
Lemma 1 (plane from point and normal). Let with , and set , , . Then , and the set is the plane through with normal .
Proof. . Multiply by and rearrange: , which is the plane through the point with normal .
So line L1 and line L11 give a plane with disparity at . In particular line L1 gives , since .
Lemma 2 (transfer). Let be a plane of the right view with , and let . For every right point with disparity , the matching left point has . Symmetrically, for a left plane with and , every left point with has . The two maps are inverse to each other.
Proof. Right to left: , so . Left to right: , so . For the inverse, apply the right to left map to . Its first entry is , and , so . The other order is the same computation with .
So a plane offered in line L7 describes, in the coordinates of view , the same set of scene points as the plane of in the other view. The pixel is the rounded match of , so lies on that surface up to rounding.
Lemma 3 (invariant). At every point of the run, for each view and pixel : (a) ; (b) ; (c) the value of is never larger than an earlier value.
Proof. After line L1, (a) holds by the assignment and (b) by Lemma 1. Only TRY changes or , and it changes both at once, to a plane and its cost , so (a) stays true. TRY accepts only when , so (b) stays true. It accepts only when , which gives (c).
Theorem. PATCHMATCH-STEREO returns for each pixel of each view a plane with and
where is the plane of line L1. The cost of each pixel does not increase from one iteration to the next.
Proof. By Lemma 3, starts at and is replaced by exactly when a valid candidate is strictly better. So at the end it is the least value among and all valid candidates, and by Lemma 3 (a) it equals . The monotone part is Lemma 3 (c).
What is not proved. The theorem does not say that minimizes over all planes. The function is a sum of truncated terms of an interpolated image and is not convex in ; 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 and linear interpolation cost . Let be the number of pixels in a window.
- One cost. sums over pixels, so it takes time.
- One iteration. Each pixel of each view gets 2 spatial candidates and refinement candidates (the number of halvings of 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 per view. One iteration takes time for .
- Number of iterations. is a parameter; the paper uses 3. The total is , plus for the start.
- Space. Two plane maps and two cost maps, . The code also caches the weights of every window, which takes .
The paper uses a window, so , 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 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 and limits the effect of pixels that do not match, for example in occlusions.
Variants and improvements
- Fronto-parallel windows. Fix , 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 , for the right view at . Mixing them up in the cost or in TRANSFER gives planes that never agree between views.
- Degenerate planes. A normal with near 0 gives huge or . Reject such normals in line L10, and skip TRANSFER when .
- Disparity range at only. TRY checks the range at , 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.
# 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 window and 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag G3M5MP Edit this page History Report an error Markdown