Algorithmadvanced
PatchMatch
Also called randomized correspondence algorithm.
Find approximate nearest neighbor patches between two images by random initialization, propagation of good offsets to neighbors and random search around them.
- Time
- Θ(n p T log w) worst · average · best
- Space
- Θ(n) extra
- Where
- T = the number of iterations; n = the number of patches of A; p = the number of pixels in a patch; w = the larger side of B in pixels
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Connelly Barnes, Eli Shechtman, Adam Finkelstein, Dan B Goldman, 2009
PatchMatch computes an approximate nearest neighbor field between two images and : for each patch of it finds an offset to a patch of that looks alike, measured by the sum of squared differences (SSD). The exact field needs, for each of the patches of , a search over all patches of . PatchMatch instead starts from random offsets and improves them in a few passes over the image. Each pass tries, at each patch, the offsets of its already visited neighbors (propagation), then a few random offsets at falling distances around the current one (random search). It uses one property of natural images: neighboring patches tend to have neighboring matches, so one good guess spreads over a whole region. The method is a general approximate nearest neighbor search for image patches; PatchMatch stereo uses the same scheme to search over planes per pixel instead of offsets.
In plain words
You want to know, for each small square of picture A, where a similar square is in picture B. Checking every place in B is slow. So give every square a random guess first. Most guesses are bad, but a few are good by luck. Then walk over the picture in reading order. At each square, ask the left and upper neighbors: "your match, moved by one step, is it better than mine?" If yes, take it. A good guess then flows right and down over the whole area that moves together. After that, try a few random places near the current match, first far away and then closer. On the next pass, walk backward so good matches also flow left and up. Four or five passes are usually enough.
The problem
Input. Two grayscale images and with integer pixel values, indexed img[y][x]. A patch radius , so that a patch has pixels. A number of iterations and a source of random numbers. Only patches that lie fully inside an image are used. Their centers are the pixels with and ; there are such centers in .
Output. An offset field that maps each center of to an offset such that is a center of , and the distances with
The exact nearest neighbor field has . PatchMatch gives no such guarantee. Its output is an upper bound on the exact distance at every patch, which gets smaller with more iterations.
The algorithm
PATCHMATCH(A, B, r, T)- 1
for each center a of A do f[a] ← (a uniformly random center of B) - a; D[a] ← dist(a, a + f[a]) - 2
for k ← 1 to T do - 3
if k is odd then visit the centers of A in row order and set s ← -1 else in reverse row order and set s ← +1 - 4
for each center a = (x, y) in that order do - 5
for each n in {(x + s, y), (x, y + s)} that is a center of A do - 6
b ← a + f[n]; if b is a center of B and dist(a, b) < D[a] then f[a] ← f[n]; D[a] ← dist(a, b) - 7
v ← a + f[a] - 8
ρ ← w ▷ w = the larger side of B - 9
while ρ ≥ 1 do - 10
b ← a uniformly random center of B with |b_x - v_x| ≤ ρ and |b_y - v_y| ≤ ρ - 11
if dist(a, b) < D[a] then f[a] ← b - a; D[a] ← dist(a, b) - 12
ρ ← ⌊ρ / 2⌋ - 13
return f, D
Line L1 is the random initialization. Line L3 sets the scan order: odd iterations go from the top left to the bottom right and look at the left and upper neighbors, even iterations go backward and look at the right and lower neighbors. Lines L5 and L6 are the propagation step. Neighbor was visited before in this pass, so its offset is already improved; the test asks whether the same offset also fits . Lines L7 to L12 are the random search of Barnes et al. (their Eq. 1, with ). The center stays fixed during the search, and the square of half side is cut to the centers of . With the larger side of , a patch gets random tries per iteration. Both steps accept a candidate only when it is strictly better.
The code computes the SSD with early termination: the sum stops as soon as it reaches the current , because the candidate then loses anyway. This is one of the speedups of the paper and does not change the result.
Example
Take one-row images with , so that a patch is one pixel and the distance is a squared difference. Let and . is the part of that starts at column 2, so the true offset is everywhere. Start from the offsets . Pixel 1 has the correct offset by chance. To show the propagation alone, turn the random search off.
| after | at | at |
|---|---|---|
| L1 | 6, 2, -1, 4, -3, 1 | 1, 0, 16, 1, 4, 16 |
| iteration 1 (forward) | 6, 2, 2, 2, 2, 2 | 1, 0, 0, 0, 0, 0 |
| iteration 2 (backward) | 2, 2, 2, 2, 2, 2 | 0, 0, 0, 0, 0, 0 |
In the forward pass, pixel 2 tries the offset of pixel 1. , so the distance drops from 16 to 0 and pixel 2 takes it. Pixels 3, 4 and 5 then do the same, one after the other. Pixel 0 comes before pixel 1 in the forward pass, so it keeps with (, ). The backward pass visits pixel 0 last and gives it from pixel 1. With the random search on, gives the radii 9, 4, 2 and 1, so each pixel also gets four random tries per iteration.
Correctness
PatchMatch is a randomized heuristic for an approximate answer, so its correctness has two parts. The full proofs are in proofs/correctness.md.
- Invariants. After every step, and is a center of . never increases, because lines L6 and L11 accept only a strictly smaller distance. So the output is an upper bound on the exact nearest neighbor distance at every patch, and it can only improve with more iterations.
- Propagation lemma. Let be a rectangle of centers of and an offset such that, for each in , is a center of with , and no other offset has distance 0. If any one center of has offset at the start of a forward pass, then after that pass and the next backward pass every center of has offset . This is the remark of Barnes et al. that one correct offset in a coherent region fills the region, made exact.
No step proves how fast random search finds a first correct offset. That part is the probabilistic analysis below, and it holds only under its model.
Proof: PatchMatch keeps valid distances that never increase, and propagation fills a coherent rectangle in two passesfull
We use the pseudocode of the page. A center of is a pixel whose patch of radius lies inside , and the same for . We write for the SSD of the patch of at and the patch of at , so .
Lemma 1 (invariant). At every point of the run, for every center of : (a) is a center of ; (b) ; (c) the value of is never larger than any earlier value of .
Proof. After line L1, for a center of , and , so (a) and (b) hold. Only lines L6 and L11 change or . Line L6 sets only after it checks that is a center of , and sets at the same time. Line L10 picks among the centers of (the square around always contains , which is a center of by (a), so the set is not empty), and line L11 sets and together. So (a) and (b) stay true. Both lines change only when the new distance is strictly smaller, which gives (c).
Corollary. At the end, for every , where ranges over the centers of , and the value of after iterations is at most its value after iterations with the same random numbers in the first iterations.
Proof. The first claim follows from (a) and (b). The second follows from (c), because the run of iterations starts with the run of iterations.
Lemma 2 (propagation). Let be a rectangle of centers of , and an offset with these properties: for each , is a center of and , and for every other offset for which is a center of . Suppose that at the start of a forward pass (an odd ) some center has . Then at the end of that pass, for every with and . At the end of the next backward pass, for every . This holds with or without the random search.
Proof. First a remark. If at some time, then by Lemma 1, and no later step changes , because a change needs a strictly smaller distance and distances are not negative. Conversely, if for , then by the uniqueness of the zero offset.
Forward pass. The pass visits the centers in row order, and at line L5 looks at and . We show by induction over the visiting order that, for every with and , right after the visit of . For this holds by the remark. For another such , either , and then is in , satisfies the same two bounds, and is visited earlier in the same row; or and , and then is in , satisfies the bounds, and is visited in an earlier row. By the induction hypothesis that neighbor has at the visit of . Line L6 then considers , which is a center of , with . Either already, and then by the remark, or , and then line L6 sets . Line L11 cannot change it afterwards, by the remark.
Backward pass. The pass visits the centers in reverse row order, and at looks at and . By the forward pass and the remark, at the start of this pass on the part , and it stays so. We show by induction over the visiting order that every has right after its visit. Take . If this is already true. Else or .
- If (so ), the neighbor is in (since ), and it comes earlier in the reverse order, in the same row. It is in or it was visited before, so there.
- If , the neighbor is in (since ), and it lies in a later row, so the reverse order visits it earlier. Again there.
In both cases line L6 gives as in the forward pass.
Theorem. PATCHMATCH returns a field such that every is a center of and , and the distances never increase from one iteration to the next. If the conditions of Lemma 2 hold on a rectangle and some center of has the offset at the start of an odd iteration with , the result is exact on all of .
Proof. The first part is Lemma 1 and its corollary. The second part is Lemma 2, applied to iterations and . By the remark in its proof the offsets on do not change in the later iterations.
What is not proved. The theorem says nothing about when a first correct offset appears in . That depends on the random initialization and the random search. The estimate of Barnes et al. (Section 3.3, Eqs. 2 and 3) is a probabilistic model under stated assumptions, not a bound for all images.
Complexity
The model is the word RAM: pixel values and SSD sums fit a word, and one random integer costs .
- Time per iteration. Each of the centers computes at most 2 propagation distances and random search distances, each of pixels. So one iteration costs for , and the initialization costs . Early termination lowers the constant but not the worst case.
- Number of iterations. is a parameter. Barnes et al. use 4 to 5 iterations and report that the field changes little after that. The total is .
- Space. The field and the distances take words beyond the images.
- Brute force. The exact field costs , with the number of centers of . The test file has it as the reference.
Analysis of Barnes et al. (Section 3.3). This is a probabilistic model, not a theorem about images. Let be the number of pixels of . A random offset is the best one for a given patch with probability , so among patches the chance that at least one gets its best offset is . If any of offsets near the best one leads to it, a region of pixels that share an offset gets a hit with probability per try (their Eq. 2). The expected number of failed iterations is , which for small is about (their Eq. 3). Their simulation reports, for a region of pixels in an image of pixels, convergence with high probability after 5 iterations. Table 1 of the paper measures a speedup of 20 to 100 times over a kd-tree at similar error, on their test images and hardware (2009).
Properties
- Randomized and approximate. The output depends on the random numbers. It is an upper bound on the exact distance at every patch, never below it.
- Monotone. No patch distance ever increases, in any step.
- Coherence. The method is fast when the true field is piecewise constant. On two unrelated noise images it is much weaker: in the tests, 16 iterations still leave the total distance above the exact one.
- Anytime. The field after each iteration is valid, so the program can stop at any time.
- Order dependent. The result depends on the scan order, since a pass uses the offsets improved earlier in the same pass.
Variants and improvements
- Prior initialization. Barnes et al. also start from a field computed at a coarser level of an image pyramid, and scale it up to the next level.
- GPU version. The paper replaces the sequential scan by a jump flood scheme that updates all pixels in parallel, and reports about 7 times speedup over its CPU code.
- Generalized PatchMatch. Barnes et al. (ECCV 2010) search over rotations and scales too, keep nearest neighbors per patch, and allow any distance.
- Other label spaces. PatchMatch stereo propagates planes of disparity, and multi-view PatchMatch (Galliani et al. 2015, Schönberger et al. 2016) propagates depth and normal per pixel. The structure of propagation and random search stays the same.
- Exact search. For small images or few patches, the brute force or a kd-tree over the patch vectors gives the exact field.
When to use it
Use PatchMatch for dense patch correspondence in image editing (inpainting, retargeting, reshuffling, texture transfer), in dense matching between views of a scene, and wherever the field is coherent. Use an exact search when you need the true nearest neighbor of each patch, and an approximate nearest neighbor index over patch vectors when the queries are scattered and have no image structure.
Pitfalls
- Ties and strict tests. Lines L6 and L11 must use a strict test. With a patch may jump between offsets of equal distance, and the propagation lemma no longer holds.
- Candidates outside . In line L6 the offset of a neighbor can point outside the centers of , at the border. Skip such candidates; do not read pixels outside the image.
- Fixed search center. Line L7 fixes before the loop of line L9, as in Eq. 1 of the paper. Many programs move the center to each improvement; that is a variant, and it changes the results for a fixed seed.
- One scan direction. If every iteration scans forward, good offsets never flow up or left, and the patch in the upper left corner of a region keeps a bad offset. Alternate the order as in line L3.
- Overflow. An SSD sum is at most for -bit pixels. A patch of 8-bit pixels needs at most 22 bits, but large patches of 16-bit pixels need wide integers.
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/. The authors are listed in prov/2WYA23.jsonl.
"""PatchMatch (Barnes, Shechtman, Finkelstein and Goldman 2009).
Images are lists of rows of integers, indexed img[y][x]. A patch has radius r,
so it covers (2 r + 1)^2 pixels. Only patches that lie fully inside an image
are used: their centers are the pixels with r <= x < W - r and r <= y < H - r.
The nearest neighbor field f maps each patch center a of A to an offset
(dx, dy), so that a + f[a] is a patch center of B. The distance is the sum of
squared differences (SSD) of the two patches.
"""
import random
INF = float("inf")
def patch_distance(A, B, ax, ay, bx, by, r, limit=INF):
"""SSD between the patch of A at (ax, ay) and the patch of B at (bx, by).
The sum stops early, and returns a value >= limit, as soon as it reaches limit.
"""
total = 0
for j in range(-r, r + 1):
ra = A[ay + j]
rb = B[by + j]
for i in range(-r, r + 1):
e = ra[ax + i] - rb[bx + i]
total += e * e
if total >= limit:
return total
return total
def _centers(img, r):
h, w = len(img), len(img[0])
return r, w - r - 1, r, h - r - 1 # x range and y range, inclusive
def patchmatch(A, B, r, iters, rng, init=None, search=True, history=None):
"""Return (f, D): the offset field and the patch distances, as dicts keyed by (x, y).
rng is a random.Random. init, if given, is a starting offset field (a dict).
search=False turns off the random search (used to test propagation alone).
history, if a list, gets a copy of D after the initialization and after each iteration.
"""
ax0, ax1, ay0, ay1 = _centers(A, r)
bx0, bx1, by0, by1 = _centers(B, r)
if ax0 > ax1 or ay0 > ay1 or bx0 > bx1 or by0 > by1:
raise ValueError("an image is smaller than one patch")
w = max(len(B), len(B[0]))
f = {}
D = {}
for y in range(ay0, ay1 + 1):
for x in range(ax0, ax1 + 1):
if init is not None:
dx, dy = init[(x, y)]
else:
dx, dy = rng.randint(bx0, bx1) - x, rng.randint(by0, by1) - y
f[(x, y)] = (dx, dy) # @line L1
D[(x, y)] = patch_distance(A, B, x, y, x + dx, y + dy, r)
if history is not None:
history.append(dict(D))
rows = list(range(ay0, ay1 + 1))
cols = list(range(ax0, ax1 + 1))
for k in range(1, iters + 1): # @line L2
if k % 2 == 1: # @line L3
ys, xs, step = rows, cols, -1
else:
ys, xs, step = rows[::-1], cols[::-1], 1
for y in ys:
for x in xs: # @line L4
a = (x, y)
for n in ((x + step, y), (x, y + step)): # @line L5
if n not in f:
continue
dx, dy = f[n]
bx, by = x + dx, y + dy
if bx0 <= bx <= bx1 and by0 <= by <= by1: # @line L6
d = patch_distance(A, B, x, y, bx, by, r, D[a])
if d < D[a]:
f[a], D[a] = (dx, dy), d
if not search:
continue
vx, vy = x + f[a][0], y + f[a][1] # @line L7
rad = w # @line L8
while rad >= 1: # @line L9
bx = rng.randint(max(vx - rad, bx0), min(vx + rad, bx1)) # @line L10
by = rng.randint(max(vy - rad, by0), min(vy + rad, by1))
d = patch_distance(A, B, x, y, bx, by, r, D[a])
if d < D[a]: # @line L11
f[a], D[a] = (bx - x, by - y), d
rad //= 2 # @line L12
if history is not None:
history.append(dict(D))
return f, D # @line L13
def nnf_brute_force(A, B, r):
"""Exact nearest neighbor distances by trying every patch of B, for the tests."""
ax0, ax1, ay0, ay1 = _centers(A, r)
bx0, bx1, by0, by1 = _centers(B, r)
best = {}
for y in range(ay0, ay1 + 1):
for x in range(ax0, ax1 + 1):
m = INF
for by in range(by0, by1 + 1):
for bx in range(bx0, bx1 + 1):
m = min(m, patch_distance(A, B, x, y, bx, by, r, m))
best[(x, y)] = m
return best
def random_image(rng, w, h, levels=256):
return [[rng.randrange(levels) for _ in range(w)] for _ in range(h)]
if __name__ == "__main__":
rng = random.Random(1)
B = random_image(rng, 20, 16)
A = [row[3:15] for row in B[2:12]]
f, D = patchmatch(A, B, 2, 5, random.Random(2))
print(sum(1 for v in f.values() if v == (3, 2)), len(f))
test_patchmatch.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/patchmatch/. The authors are listed in prov/2WYA23.jsonl.
import random
from patchmatch import nnf_brute_force, patch_distance, patchmatch, random_image
def test_example_trace() -> None:
A = [[5, 9, 2, 7, 4, 8]]
B = [[1, 6, 5, 9, 2, 7, 4, 8, 3]]
init = {(x, 0): (d, 0) for x, d in enumerate([6, 2, -1, 4, -3, 1])}
want = {
0: ([6, 2, -1, 4, -3, 1], [1, 0, 16, 1, 4, 16]),
1: ([6, 2, 2, 2, 2, 2], [1, 0, 0, 0, 0, 0]),
2: ([2, 2, 2, 2, 2, 2], [0, 0, 0, 0, 0, 0]),
}
for t, (offs, dists) in want.items():
f, D = patchmatch(A, B, 0, t, random.Random(0), init=init, search=False)
assert [f[(x, 0)][0] for x in range(6)] == offs
assert [D[(x, 0)] for x in range(6)] == dists
def test_patch_distance() -> None:
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[1, 2, 3], [4, 6, 6], [7, 8, 0]]
assert patch_distance(A, B, 1, 1, 1, 1, 1) == 1 + 81
assert patch_distance(A, B, 1, 1, 1, 1, 0) == 1
# Early termination returns a value at or above the limit.
assert patch_distance(A, B, 1, 1, 1, 1, 1, limit=5) >= 5
def test_distances_match_field() -> None:
rng = random.Random(3)
A = random_image(rng, 14, 11)
B = random_image(rng, 17, 13)
r = 1
f, D = patchmatch(A, B, r, 4, random.Random(4))
for (x, y), (dx, dy) in f.items():
bx, by = x + dx, y + dy
assert r <= bx < 17 - r and r <= by < 13 - r
assert D[(x, y)] == patch_distance(A, B, x, y, bx, by, r)
def test_cost_never_increases() -> None:
rng = random.Random(5)
A = random_image(rng, 16, 12, levels=16)
B = random_image(rng, 18, 14, levels=16)
hist = []
patchmatch(A, B, 1, 5, random.Random(6), history=hist)
assert len(hist) == 6
for before, after in zip(hist, hist[1:]):
assert all(after[a] <= before[a] for a in before)
def test_against_brute_force_coherent() -> None:
# B holds a noisy copy of A: the field is coherent, and PatchMatch finds
# the exact nearest neighbor distance of every patch.
rng = random.Random(9)
B = random_image(rng, 24, 20)
A = [[v + rng.randint(-3, 3) for v in row[5:19]] for row in B[4:16]]
r = 1
exact = nnf_brute_force(A, B, r)
f, D = patchmatch(A, B, r, 4, random.Random(10))
assert D == exact
assert all(v == (5, 4) for v in f.values())
def test_against_brute_force_incoherent() -> None:
# Two unrelated noise images: no coherence, so propagation helps little.
# The answer is an upper bound on the exact distance and improves with T.
rng = random.Random(7)
A = random_image(rng, 12, 10, levels=8)
B = random_image(rng, 14, 12, levels=8)
r = 1
exact = nnf_brute_force(A, B, r)
total = []
for t in (1, 4, 16):
_, D = patchmatch(A, B, r, t, random.Random(8))
assert all(D[a] >= exact[a] for a in exact)
total.append(sum(D.values()))
assert total[0] >= total[1] >= total[2]
assert total[2] <= 1.2 * sum(exact.values())
def test_recovers_shifted_copy() -> None:
for seed in (11, 12, 13):
rng = random.Random(seed)
B = random_image(rng, 30, 26)
sx, sy = rng.randint(1, 8), rng.randint(1, 8)
A = [row[sx:sx + 20] for row in B[sy:sy + 16]]
f, D = patchmatch(A, B, 2, 5, random.Random(seed + 100))
assert all(v == (sx, sy) for v in f.values())
assert all(d == 0 for d in D.values())
def test_propagation_fills_region() -> None:
# One correct seed and no random search: a forward and a backward pass
# give every patch the true offset (the lemma of the proof).
rng = random.Random(21)
B = random_image(rng, 22, 18)
A = [row[4:16] for row in B[3:15]]
r = 1
for seed_pos in ((1, 1), (5, 6), (10, 10), (10, 1)):
init = {}
for y in range(r, 12 - r):
for x in range(r, 12 - r):
init[(x, y)] = (rng.randint(-3, 8), rng.randint(-2, 5))
if (x + init[(x, y)][0], y + init[(x, y)][1]) == (x + 4, y + 3):
init[(x, y)] = (-1, -1)
init[seed_pos] = (4, 3)
f, _ = patchmatch(A, B, r, 2, random.Random(0), init=init, search=False)
assert all(v == (4, 3) for v in f.values())
f1, _ = patchmatch(A, B, r, 1, random.Random(0), init=init, search=False)
sx, sy = seed_pos
for (x, y), v in f1.items():
if x >= sx and y >= sy:
assert v == (4, 3)
def test_deterministic() -> None:
rng = random.Random(31)
A = random_image(rng, 10, 9)
B = random_image(rng, 12, 11)
out1 = patchmatch(A, B, 1, 3, random.Random(32))
out2 = patchmatch(A, B, 1, 3, random.Random(32))
assert out1 == out2
History
Barnes, Shechtman, Finkelstein and Goldman (2009) presented PatchMatch at SIGGRAPH as the core of interactive tools for image retargeting, completion and reshuffling. Earlier texture synthesis already copied the matches of neighbors, but PatchMatch combined that propagation with random search at falling scales and analyzed why a few iterations suffice. Barnes et al. (2010) generalized it to neighbors, rotations and scales. Bleyer, Rhemann and Rother (2011) used it to search the infinite space of slanted planes in stereo, and later multi-view stereo systems such as COLMAP adopted the same propagation scheme for depth and normal maps.
References
- 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 (SIGGRAPH 2009), Section 3 (the nearest neighbor field, initialization, propagation with the scan order reversed on even iterations, random search of Eq. 1 with alpha = 1/2, halting after 4 to 5 iterations), Section 3.3 (the convergence analysis, Eqs. 2 and 3) and Table 1 (the comparison with a kd-tree)
- 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 (PatchMatch used to search over the infinite set of planes per pixel)
Where this leads
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 2WYA23 Edit this page History Report an error Markdown