Algorithm Search⌘K

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
Properties
randomizednot exactofflineiterative
Origin
Connelly Barnes, Eli Shechtman, Adam Finkelstein, Dan B Goldman, 2009

PatchMatch computes an approximate nearest neighbor field between two images AA and BB: for each patch of AA it finds an offset to a patch of BB that looks alike, measured by the sum of squared differences (SSD). The exact field needs, for each of the nn patches of AA, a search over all patches of BB. 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 AA and BB with integer pixel values, indexed img[y][x]. A patch radius r≥0r \ge 0, so that a patch has p=(2r+1)2p = (2r + 1)^2 pixels. A number of iterations TT and a source of random numbers. Only patches that lie fully inside an image are used. Their centers are the pixels with r≤x<W−rr \le x < W - r and r≤y<H−rr \le y < H - r; there are nn such centers in AA.

Output. An offset field ff that maps each center aa of AA to an offset f(a)f(a) such that a+f(a)a + f(a) is a center of BB, and the distances D(a)=dist⁡(a,a+f(a))D(a) = \operatorname{dist}(a, a + f(a)) with

dist⁡(a,b)=∑∣i∣≤r∑∣j∣≤r(A(ax+i,ay+j)−B(bx+i,by+j))2.\operatorname{dist}(a, b) = \sum_{|i| \le r} \sum_{|j| \le r} \big(A(a_x + i, a_y + j) - B(b_x + i, b_y + j)\big)^2 .

The exact nearest neighbor field has D(a)=min⁡bdist⁡(a,b)D(a) = \min_b \operatorname{dist}(a, b). 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

  1. PATCHMATCH(A, B, r, T)
  2. 1for each center a of A do f[a] ← (a uniformly random center of B) - a; D[a] ← dist(a, a + f[a])
  3. 2for k ← 1 to T do
  4. 3if 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
  5. 4for each center a = (x, y) in that order do
  6. 5for each n in {(x + s, y), (x, y + s)} that is a center of A do
  7. 6b ← 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)
  8. 7v ← a + f[a]
  9. 8ρ ← w ▷ w = the larger side of B
  10. 9while ρ ≥ 1 do
  11. 10b ← a uniformly random center of B with |b_x - v_x| ≤ ρ and |b_y - v_y| ≤ ρ
  12. 11if dist(a, b) < D[a] then f[a] ← b - a; D[a] ← dist(a, b)
  13. 12ρ ← ⌊ρ / 2⌋
  14. 13return 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 nn was visited before aa in this pass, so its offset is already improved; the test asks whether the same offset also fits aa. Lines L7 to L12 are the random search of Barnes et al. (their Eq. 1, ui=v0+wαiRiu_i = v_0 + w \alpha^i R_i with α=1/2\alpha = 1/2). The center vv stays fixed during the search, and the square of half side ρ\rho is cut to the centers of BB. With ww the larger side of BB, a patch gets ⌊log⁡2w⌋+1\lfloor \log_2 w \rfloor + 1 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 D[a]D[a], 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 r=0r = 0, so that a patch is one pixel and the distance is a squared difference. Let A=(5,9,2,7,4,8)A = (5, 9, 2, 7, 4, 8) and B=(1,6,5,9,2,7,4,8,3)B = (1, 6, 5, 9, 2, 7, 4, 8, 3). AA is the part of BB that starts at column 2, so the true offset is +2+2 everywhere. Start from the offsets (+6,+2,−1,+4,−3,+1)(+6, +2, -1, +4, -3, +1). Pixel 1 has the correct offset by chance. To show the propagation alone, turn the random search off.

after ff at x=0,…,5x = 0, \ldots, 5 DD at x=0,…,5x = 0, \ldots, 5
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 +2+2 of pixel 1. B(4)=2=A(2)B(4) = 2 = A(2), 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 +6+6 with D=1D = 1 (A(0)=5A(0) = 5, B(6)=4B(6) = 4). The backward pass visits pixel 0 last and gives it +2+2 from pixel 1. With the random search on, w=9w = 9 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.

  1. Invariants. After every step, D[a]=dist⁡(a,a+f[a])D[a] = \operatorname{dist}(a, a + f[a]) and a+f[a]a + f[a] is a center of BB. D[a]D[a] 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.
  2. Propagation lemma. Let RR be a rectangle of centers of AA and vv an offset such that, for each aa in RR, a+va + v is a center of BB with dist⁡(a,a+v)=0\operatorname{dist}(a, a + v) = 0, and no other offset has distance 0. If any one center of RR has offset vv at the start of a forward pass, then after that pass and the next backward pass every center of RR has offset vv. 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 AA is a pixel whose patch of radius rr lies inside AA, and the same for BB. We write dist⁡(a,b)\operatorname{dist}(a, b) for the SSD of the patch of AA at aa and the patch of BB at bb, so dist⁡(a,b)≥0\operatorname{dist}(a, b) \ge 0.

Lemma 1 (invariant). At every point of the run, for every center aa of AA: (a) a+f[a]a + f[a] is a center of BB; (b) D[a]=dist⁡(a,a+f[a])D[a] = \operatorname{dist}(a, a + f[a]); (c) the value of D[a]D[a] is never larger than any earlier value of D[a]D[a].

Proof. After line L1, f[a]=b0−af[a] = b_0 - a for a center b0b_0 of BB, and D[a]=dist⁡(a,b0)D[a] = \operatorname{dist}(a, b_0), so (a) and (b) hold. Only lines L6 and L11 change f[a]f[a] or D[a]D[a]. Line L6 sets f[a]←f[n]f[a] \leftarrow f[n] only after it checks that b=a+f[n]b = a + f[n] is a center of BB, and sets D[a]←dist⁡(a,b)D[a] \leftarrow \operatorname{dist}(a, b) at the same time. Line L10 picks bb among the centers of BB (the square around vv always contains vv, which is a center of BB by (a), so the set is not empty), and line L11 sets f[a]←b−af[a] \leftarrow b - a and D[a]←dist⁡(a,b)D[a] \leftarrow \operatorname{dist}(a, b) together. So (a) and (b) stay true. Both lines change D[a]D[a] only when the new distance is strictly smaller, which gives (c). □\square

Corollary. At the end, D[a]≥min⁡bdist⁡(a,b)D[a] \ge \min_b \operatorname{dist}(a, b) for every aa, where bb ranges over the centers of BB, and the value of D[a]D[a] after TT iterations is at most its value after T′<TT' < T iterations with the same random numbers in the first T′T' iterations.

Proof. The first claim follows from (a) and (b). The second follows from (c), because the run of TT iterations starts with the run of T′T' iterations. □\square

Lemma 2 (propagation). Let R={(x,y):x0≤x≤x1, y0≤y≤y1}R = \{(x, y) : x_0 \le x \le x_1,\ y_0 \le y \le y_1\} be a rectangle of centers of AA, and vv an offset with these properties: for each a∈Ra \in R, a+va + v is a center of BB and dist⁡(a,a+v)=0\operatorname{dist}(a, a + v) = 0, and dist⁡(a,a+u)>0\operatorname{dist}(a, a + u) > 0 for every other offset uu for which a+ua + u is a center of BB. Suppose that at the start of a forward pass (an odd kk) some center q=(xq,yq)∈Rq = (x_q, y_q) \in R has f[q]=vf[q] = v. Then at the end of that pass, f[a]=vf[a] = v for every a=(x,y)∈Ra = (x, y) \in R with x≥xqx \ge x_q and y≥yqy \ge y_q. At the end of the next backward pass, f[a]=vf[a] = v for every a∈Ra \in R. This holds with or without the random search.

Proof. First a remark. If f[a]=vf[a] = v at some time, then D[a]=0D[a] = 0 by Lemma 1, and no later step changes f[a]f[a], because a change needs a strictly smaller distance and distances are not negative. Conversely, if D[a]=0D[a] = 0 for a∈Ra \in R, then f[a]=vf[a] = v by the uniqueness of the zero offset.

Forward pass. The pass visits the centers in row order, and at a=(x,y)a = (x, y) line L5 looks at (x−1,y)(x - 1, y) and (x,y−1)(x, y - 1). We show by induction over the visiting order that, for every a∈Ra \in R with x≥xqx \ge x_q and y≥yqy \ge y_q, f[a]=vf[a] = v right after the visit of aa. For a=qa = q this holds by the remark. For another such aa, either x>xqx > x_q, and then (x−1,y)(x - 1, y) is in RR, satisfies the same two bounds, and is visited earlier in the same row; or x=xqx = x_q and y>yqy > y_q, and then (x,y−1)(x, y - 1) is in RR, satisfies the bounds, and is visited in an earlier row. By the induction hypothesis that neighbor nn has f[n]=vf[n] = v at the visit of aa. Line L6 then considers b=a+vb = a + v, which is a center of BB, with dist⁡(a,b)=0\operatorname{dist}(a, b) = 0. Either D[a]=0D[a] = 0 already, and then f[a]=vf[a] = v by the remark, or D[a]>0D[a] > 0, and then line L6 sets f[a]=vf[a] = v. Line L11 cannot change it afterwards, by the remark.

Backward pass. The pass visits the centers in reverse row order, and at (x,y)(x, y) looks at (x+1,y)(x + 1, y) and (x,y+1)(x, y + 1). By the forward pass and the remark, at the start of this pass f=vf = v on the part R′={(x,y)∈R:x≥xq,y≥yq}R' = \{(x, y) \in R : x \ge x_q, y \ge y_q\}, and it stays so. We show by induction over the visiting order that every a∈Ra \in R has f[a]=vf[a] = v right after its visit. Take a=(x,y)∈Ra = (x, y) \in R. If a∈R′a \in R' this is already true. Else x<xqx < x_q or y<yqy < y_q.

  • If y≥yqy \ge y_q (so x<xqx < x_q), the neighbor (x+1,y)(x + 1, y) is in RR (since x+1≤xq≤x1x + 1 \le x_q \le x_1), and it comes earlier in the reverse order, in the same row. It is in R′R' or it was visited before, so f=vf = v there.
  • If y<yqy < y_q, the neighbor (x,y+1)(x, y + 1) is in RR (since y+1≤yq≤y1y + 1 \le y_q \le y_1), and it lies in a later row, so the reverse order visits it earlier. Again f=vf = v there.

In both cases line L6 gives f[a]=vf[a] = v as in the forward pass. □\square

Theorem. PATCHMATCH returns a field ff such that every a+f[a]a + f[a] is a center of BB and D[a]=dist⁡(a,a+f[a])≥min⁡bdist⁡(a,b)D[a] = \operatorname{dist}(a, a + f[a]) \ge \min_b \operatorname{dist}(a, b), and the distances never increase from one iteration to the next. If the conditions of Lemma 2 hold on a rectangle RR and some center of RR has the offset vv at the start of an odd iteration kk with k+1≤Tk + 1 \le T, the result is exact on all of RR.

Proof. The first part is Lemma 1 and its corollary. The second part is Lemma 2, applied to iterations kk and k+1k + 1. By the remark in its proof the offsets on RR do not change in the later iterations. ■\blacksquare

What is not proved. The theorem says nothing about when a first correct offset appears in RR. 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 O(1)O(1).

  • Time per iteration. Each of the nn centers computes at most 2 propagation distances and ⌊log⁡2w⌋+1\lfloor \log_2 w \rfloor + 1 random search distances, each of pp pixels. So one iteration costs Θ(nplog⁡w)\Theta(n p \log w) for w≥2w \ge 2, and the initialization costs Θ(np)\Theta(n p). Early termination lowers the constant but not the worst case.
  • Number of iterations. TT is a parameter. Barnes et al. use 4 to 5 iterations and report that the field changes little after that. The total is Θ(npTlog⁡w)\Theta(n p T \log w).
  • Space. The field and the distances take Θ(n)\Theta(n) words beyond the images.
  • Brute force. The exact field costs Θ(nmp)\Theta(n m p), with mm the number of centers of BB. 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 MM be the number of pixels of BB. A random offset is the best one for a given patch with probability 1/M1/M, so among MM patches the chance that at least one gets its best offset is 1−(1−1/M)M≈1−1/e1 - (1 - 1/M)^M \approx 1 - 1/e. If any of CC offsets near the best one leads to it, a region of mm pixels that share an offset gets a hit with probability p=1−(1−C/M)mp = 1 - (1 - C/M)^m per try (their Eq. 2). The expected number of failed iterations is 1/p−11/p - 1, which for small m/Mm/M is about M/(Cm)−1/2M/(C m) - 1/2 (their Eq. 3). Their simulation reports, for a region of 20220^2 pixels in an image of 200022000^2 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 kk 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 ≤\le a patch may jump between offsets of equal distance, and the propagation lemma no longer holds.
  • Candidates outside BB. In line L6 the offset of a neighbor can point outside the centers of BB, at the border. Skip such candidates; do not read pixels outside the image.
  • Fixed search center. Line L7 fixes vv 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 p(2b−1)2p (2^b - 1)^2 for bb-bit pixels. A 7×77 \times 7 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.

patchmatch.pyI0RawGitHub
# 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 kk 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

  1. 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)
  2. 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.

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
  • at least three sources
  • a scene preset for the example