Algorithm Search⌘K

Algorithmadvanced

Patch-based multi-view stereo

Also called PMVS, Furukawa-Ponce MVS.

Match features into small oriented patches, expand them into neighboring image cells and filter those that break visibility or have few neighbors, giving a dense set of patches on the surface.

Time
O(N^3 F^2 E s + R M N (N E s + k)) worst · averageΩ(N F) best
Space
O(M N) extra
Where
E = the cost evaluations per refinement; F = the number of features per image; M = the number of image cells; N = the number of images; R = the rounds of expansion and filtering; k = the largest number of patches in one cell; s = the number of samples per patch
Properties
deterministicnot exactofflineiterative
Origin
Yasutaka Furukawa, Jean Ponce, 2007

Patch-based multi-view stereo, or PMVS, turns calibrated images into a dense set of small oriented squares, called patches, that lie on the surface of the scene. It starts from a few reliable patches made from matched features. Then it grows the set: each patch tries to put new patches in the neighboring image cells, on its own tangent plane, and keeps those that look the same in several images. A filter step removes patches that break visibility or that do not fit their neighbors. Expansion and filtering alternate a few times. The method of Furukawa and Ponce (2007, 2010) needs no initial shape, no bounding volume and no depth range, and it handles outliers and occlusion well. The result is a quasi-dense oriented point set, which a surface method such as Poisson surface reconstruction can turn into a mesh. It is one answer to the multi-view stereo problem.

In plain words

Think of covering a statue with small square stickers. You first put a few stickers where you are sure: points that look very distinct and that you can find in several photos. Then, next to every sticker, you try a new one that leans the same way as its neighbor, and you nudge it until it looks the same from all cameras. If the nudged sticker looks right in enough photos, it stays. You keep doing this until the stickers cover the statue. Now and then you walk around and pull off stickers that float in front of the statue or that do not line up with the stickers next to them.

The problem

Input.

  • NN gray images I1,…,INI_1, \dots, I_N with known cameras (Ki,Ri,ti)(K_i, R_i, t_i). A point XX maps to the camera frame by RiX+tiR_i X + t_i.
  • Feature points in each image (the paper detects Harris and difference of Gaussian features; the code takes them as input).
  • Parameters: the grid size μ\mu, the cell size β\beta in pixels, the least number γ\gamma of images that must agree, the threshold α\alpha of the discrepancy, the number of rounds RR.

Output. A set of patches. A patch pp has a center c(p)c(p), a unit normal n(p)n(p) that points toward the cameras, a reference image R(p)R(p), the set V(p)V(p) of images that may see it, and the set V∗(p)⊆V(p)V^*(p) \subseteq V(p) of images in which it is photo-consistent. The aim is at least one patch in every cell of β×β\beta \times \beta pixels of every image where the surface is seen, with each patch close to the surface.

Discrepancy. Lay a μ×μ\mu \times \mu grid on the patch, with one step about one pixel of R(p)R(p). Project the grid into an image II and read the image by bilinear interpolation. The discrepancy h(p,I,R(p))h(p, I, R(p)) is one minus the normalized cross-correlation of these values with those of R(p)R(p). The score of a patch is

g∗(p)=1∣V∗(p)∖{R(p)}∣∑I∈V∗(p)∖{R(p)}h(p,I,R(p)),g^*(p) = \frac{1}{|V^*(p) \setminus \{R(p)\}|} \sum_{I \in V^*(p) \setminus \{R(p)\}} h(p, I, R(p)),

and V∗(p)V^*(p) holds R(p)R(p) and the images of V(p)V(p) with h≤αh \le \alpha. This is a photo-consistency measure in scene space.

The algorithm

  1. PMVS(images, cameras, features, R)
  2. 1for each image I_i and each feature f of I_i do ▷ matching
  3. 2if the cell of f in I_i already holds a patch then skip f
  4. 3F ← the features of other images within 2 pixels of the epipolar line of f
  5. 4triangulate f with each f' in F and sort the points by distance from the center of I_i
  6. 5for each point X in that order do p ← patch(c = X, n = unit(O_i - X), R = I_i)
  7. 6if ACCEPT(p) then
  8. 7register p in its cells; go to the next feature
  9. 8repeat R times
  10. 9for each patch p, then each new patch, do ▷ expansion
  11. 10for each I in V*(p) and each cell C next to the cell of p in I that holds no patch do
  12. 11X ← the point where the ray through the center of C meets the plane of p
  13. 12q ← patch(c = X, n = n(p), R = R(p))
  14. 13if ACCEPT(q) and I ∈ V*(q) and q projects into C then
  15. 14register q in its cells; add q to the queue
  16. 15for each patch p do ▷ filtering
  17. 16remove p if fewer than a fraction of the patches in the 3 × 3 cells around p, in the images of V*(p), are neighbors of p
  18. 17return the patches
  19. ACCEPT(p): V(p) ← the images that see c(p) at an angle below a limit; V*(p) ← R(p) and the images of V(p) with h ≤ α;
  20. refine c(p) along the ray of R(p) and the two angles of n(p) to minimize g*(p); recompute V(p) and V*(p);
  21. return |V*(p)| ≥ γ

Matching (L1 to L7). For a feature ff of IiI_i, the candidate matches in the other images lie near its epipolar line (epipolar geometry). Each candidate gives a 3D point by triangulation. The points are tried from the nearest to the farthest from the optical center OiO_i, and the first one that ACCEPT keeps becomes a patch. The normal starts pointing at OiO_i. Line L2 skips features in cells that are already covered, which saves time.

Refinement. ACCEPT moves the patch to lower g∗(p)g^*(p) with three free values: the depth of c(p)c(p) along the ray of R(p)R(p) and two angles of n(p)n(p). The paper uses a conjugate gradient method. The code uses a pattern search: it tries a step up and down in each value, keeps any step that helps, and halves the steps when none does. Moving c(p)c(p) along the ray of R(p)R(p) keeps its pixel in R(p)R(p) fixed.

Expansion (L9 to L14). Real surfaces are smooth at the scale of a few pixels, so the plane of a patch is a good guess for its neighbors. Line L11 puts the new patch where the ray of the neighboring cell meets that plane, and ACCEPT corrects it. The test in line L13 that qq still projects into CC keeps one new patch per empty cell; it is a choice of the code. The paper has its own rules for which cells to skip. For example, it skips a cell that already holds a patch which is a neighbor of pp, and it does not expand across a depth discontinuity.

Filtering (L15 and L16). Two patches pp and p′p' are neighbors when ∣(c(p)−c(p′))⋅n(p)∣+∣(c(p)−c(p′))⋅n(p′)∣<2ρ|(c(p) - c(p')) \cdot n(p)| + |(c(p) - c(p')) \cdot n(p')| < 2 \rho, so each lies close to the plane of the other. The paper has three filters. Two of them use visibility: one removes patches that lie outside the surface, in front of patches that the same images see, and one removes patches that too few images see as the nearest surface. The third, of the regularization kind, removes a patch when few of the patches in the cells around it are its neighbors. The code has only a filter of the third kind, with the fraction 0.25 and ρ\rho equal to two pixels of R(p)R(p), and the page gives the paper's filters only in outline.

Example

The test file builds a textured plane Z=4+0.15X−0.1YZ = 4 + 0.15 X - 0.1 Y and three 24×2424 \times 24 images with focal length 40, from cameras at (0,0,0)(0, 0, 0), (0.5,0,0)(0.5, 0, 0) and (0.1,0.45,0)(0.1, 0.45, 0). One pixel at depth 4 covers 0.1 units of the plane. Each image has 8 features: the projections of the 6 points with X∈{−0.5,0,0.5}X \in \{-0.5, 0, 0.5\} and Y∈{−0.4,0.4}Y \in \{-0.4, 0.4\} on the plane, and 2 random points. The parameters are μ=5\mu = 5, β=3\beta = 3, γ=2\gamma = 2, α=0.3\alpha = 0.3 (NCC at least 0.7) and R=3R = 3.

  1. Matching. All 6 true points become patches at the true depth. The random features find no partner that passes ACCEPT. For example, the feature at (16.36,7.61)(16.36, 7.61) of image 1 has a match in image 2 at (11.5,7.61)(11.5, 7.61) on its epipolar line, which triangulates to (0.5,−0.4,4.115)(0.5, -0.4, 4.115), a point of the plane. After refinement its normal is (0.127,−0.089,−0.988)(0.127, -0.089, -0.988), close to the true (0.148,−0.098,−0.984)(0.148, -0.098, -0.984), and g∗=0.001g^* = 0.001.
  2. Expansion. The first round grows the 6 patches to 60. The cells of image 1 that the other cameras also see are covered, except one: 35 of the 36 inner cells hold a patch. The largest distance of a patch center from the plane is 0.074 (under one pixel), and the median is 0.009.
  3. Filtering. The filter removes nothing from this clean set. A patch put by hand at (0,0,3.6)(0, 0, 3.6), 0.4 in front of the plane, has no neighbor among the patches in the cells around it and is removed. The next two rounds add nothing.

Correctness

The full proof is in proofs/correctness.md. It proves what the procedure guarantees, not that the output is the true surface.

  1. Acceptance. Every patch in the output has ∣V∗(p)∣≥γ|V^*(p)| \ge \gamma, R(p)∈V∗(p)R(p) \in V^*(p), and h(p,I,R(p))≤αh(p, I, R(p)) \le \alpha for every I∈V∗(p)I \in V^*(p), as computed at the time it was accepted. Refinement never increases g∗g^*.
  2. Cells. Every patch is registered in the cell of its projection in each image of V∗(p)V^*(p), and each new patch fills a cell that was empty.
  3. Termination. Every accepted patch fills an empty cell, a filter round only removes patches, and the number of cells is finite. So each expansion ends after at most MM new patches, and the whole run ends after RR rounds.
  4. Exact data. On a textured plane with exact images, a patch on the plane with the true normal has h=0h = 0 in every image that sees all of its grid. So the truth passes ACCEPT. The bilinear sampling of the code makes hh small but not zero, as the example shows.
Proof: PMVS keeps only accepted patches in their cells and ends after a finite number of stepsfull

We use the pseudocode of the page and the code that follows it. A cell is a pair (image ii, index CC); there are MM cells in total, a finite number. A patch pp is registered when it is in the list of patches and in the list of the cell of its projection in each image of V∗(p)V^*(p). We write celli(X)\mathrm{cell}_i(X) for the cell of image ii that holds the projection of XX, which is defined only when XX is in front of camera ii and projects inside the image.

Lemma 1 (what ACCEPT guarantees). If ACCEPT(p)(p) returns true, then at that time: R(p)∈V(p)R(p) \in V(p), celli(c(p))\mathrm{cell}_i(c(p)) is defined for every i∈V(p)i \in V(p), R(p)∈V∗(p)⊆V(p)R(p) \in V^*(p) \subseteq V(p), h(p,I,R(p))≤αh(p, I, R(p)) \le \alpha for every I∈V∗(p)∖{R(p)}I \in V^*(p) \setminus \{R(p)\}, and ∣V∗(p)∣≥γ|V^*(p)| \ge \gamma.

Proof. After refinement, ACCEPT computes V(p)V(p) again. It puts an image ii into V(p)V(p) only when celli(c(p))\mathrm{cell}_i(c(p)) is defined, and it returns false when R(p)∉V(p)R(p) \notin V(p). Then it sets V∗(p)V^*(p) to the images of V(p)V(p) that are R(p)R(p) or have h≤αh \le \alpha; if the grid of pp does not project inside R(p)R(p), it sets V∗(p)=∅V^*(p) = \emptyset. In the other case R(p)∈V∗(p)R(p) \in V^*(p) by the definition. ACCEPT returns true only when ∣V∗(p)∣≥γ|V^*(p)| \ge \gamma, and γ≥1\gamma \ge 1, so the empty case returns false. □\square

Lemma 2 (refinement does not make the score worse). Let SS be the set V∗(p)V^*(p) that ACCEPT computes before refinement. The value of g∗g^* over SS at the end of refinement is at most its value at the start.

Proof. The search keeps the current point xx and its cost best=g∗best = g^* over SS. It replaces xx only by a point yy with a strictly smaller cost, and at the end it puts the patch at xx. So the cost at the end is the least cost it has seen, which is at most the cost at the start. If the normal does not face the reference camera, refinement does nothing, and the claim is trivial. □\square

The score that ACCEPT stores at the end is g∗g^* over the new V∗(p)V^*(p), which can differ from SS. Lemma 2 is about SS only.

Lemma 3 (registration). Every patch in the list after MATCH, after each EXPAND and after each FILTER is registered, with the values of V(p)V(p) and V∗(p)V^*(p) that ACCEPT gave it, and no list of a cell holds a patch that is not in the list of patches.

Proof. A patch enters the list only in lines L7 and L14, right after ACCEPT returned true, and the code does not change c(p)c(p), n(p)n(p), V(p)V(p) or V∗(p)V^*(p) after that. Register adds pp to the list of celli(c(p))\mathrm{cell}_i(c(p)) for each i∈V∗(p)i \in V^*(p), and this cell is defined by Lemma 1, since V∗(p)⊆V(p)V^*(p) \subseteq V(p). FILTER removes a patch pp from the list and from the list of celli(c(p))\mathrm{cell}_i(c(p)) for each i∈V∗(p)i \in V^*(p), which are exactly the cells where register put it. Nothing else changes the lists. □\square

Lemma 4 (one new patch per empty cell). In EXPAND, each patch qq that line L14 registers was made for a target cell (i,C)(i, C) that held no patch at line L10, and after line L14 the cell (i,C)(i, C) holds qq. EXPAND removes no patch.

Proof. Line L10 skips (i,C)(i, C) when its list is not empty. Line L13 requires i∈V∗(q)i \in V^*(q) and celli(c(q))=C\mathrm{cell}_i(c(q)) = C, so register puts qq into the list of (i,C)(i, C) by Lemma 3. EXPAND has no step that removes a patch from a list. □\square

Lemma 5 (termination of EXPAND). One call of EXPAND registers at most MM patches and ends.

Proof. By Lemma 4, every registered patch turns one empty cell into a non-empty one, and no cell becomes empty again during the call. There are at most MM empty cells at the start, so at most MM patches are registered. The queue starts with a finite list and grows only when a patch is registered, so it gets at most MM more entries. Each entry is processed once, with at most 4N4 N target cells and one ACCEPT for each. ACCEPT ends because the refinement stops after at most a fixed number of cost evaluations. So EXPAND ends. □\square

Lemma 6 (FILTER). FILTER ends, removes only patches, and removes pp exactly when pp sees at least one other patch in the 3×33 \times 3 cells around its own cell in the images of V∗(p)V^*(p), and fewer than the fraction ff of these patches are neighbors of pp.

Proof. Line L15 visits each patch once and looks at at most 9N9 N finite lists. The decision of line L16 uses only the patches present at the start of the pass, because the removals happen after the loop. So the result does not depend on the order of the patches. □\square

Theorem. PMVS ends. Every patch pp in its output satisfies the conditions of Lemma 1 and is registered as Lemma 3 says. Every patch that expansion added fills a cell that was empty when it was made, and every patch that survived the last filter pass had, at that pass, no other patches in the cells around it or at least the fraction ff of them as neighbors.

Proof. MATCH loops over a finite set of features and a finite list of candidates, and each ACCEPT ends, so MATCH ends. The main loop runs RR rounds; each round ends by Lemmas 5 and 6. The output conditions follow from Lemmas 1, 3, 4 and 6, since the last step of each round is FILTER and a patch that FILTER keeps is not changed. ■\blacksquare

The truth passes the test on exact data. Suppose the images are exact images of a Lambertian textured surface, read with no error at any point, and pp lies on the surface with the true normal, small enough that the surface is flat over its grid. Each grid point is a point of the surface, so every image that sees it records the same value there. Then the samples of pp in R(p)R(p) and in any image that sees the whole grid are equal, their NCC is 1 when the texture is not flat, and h=0≤αh = 0 \le \alpha. So the true patch has every such image in V∗(p)V^*(p) and passes ACCEPT when at least γ\gamma images see it at an angle below the limit. The code reads the images by bilinear interpolation of pixel values, so in the tests hh is small but not zero.

What is not proved. The theorem says nothing about how close the patches are to the true surface. Refinement is a local search, so it can stop at a wrong minimum of g∗g^*, and a repeated texture or a flat region can give a wrong patch a low score. Matching and expansion can miss parts of the surface, for example where no feature is matched or where the expansion cannot reach. The filter of the code is one rule of the regularization kind, with a fraction chosen for the code, and the visibility filters of the paper are not implemented, so outliers that agree with their neighbors are not removed. The proof also does not cover the paper's refinement by the conjugate gradient method.

Complexity

The model is the real RAM. Let s=μ2s = \mu^2, let EE bound the cost evaluations of one refinement, and let MM be the total number of cells in all images, about NWH/β2N W H / \beta^2.

  • One ACCEPT. V(p)V(p) takes O(N)O(N), one g∗g^* takes O(Ns)O(N s), and the refinement takes O(ENs)O(E N s).
  • Matching. Each of the NFN F features gets up to (N−1)F(N - 1) F candidates in the worst case, so matching takes O(N3F2Es)O(N^3 F^2 E s). In practice the epipolar test leaves a few candidates per image and the first good one stops the loop.
  • Expansion. Each accepted patch fills an empty cell, so a round has at most MM patches. Each patch tries at most 4 cells in each of at most NN images, so a round takes O(MN2Es)O(M N^2 E s).
  • Filtering. Each patch looks at 9 cells in at most NN images, with at most kk patches each, so a round takes O(MNk)O(M N k).
  • Space. The patches and their registrations take O(MN)O(M N), besides the images.

The constants are large, and most of the time goes to the cost evaluations of refinement.

Properties

  • No initial shape. Matching needs no bounding box, visual hull or depth range, unlike many volumetric methods in the survey of Seitz et al. (2006).
  • Local and robust. Each patch is tested against the images on its own. Outliers fail ACCEPT or the filters, and occluded images leave V∗(p)V^*(p).
  • Uniform density. The cells set the density: about one patch per β×β\beta \times \beta pixels of each image.
  • Output is oriented points. The output is not a surface. A mesh needs another step.
  • Deterministic. Given the features and the order of the images, the result does not depend on random numbers.

Variants and improvements

  • Software. The PMVS2 program of Furukawa uses by default a window of 7 by 7 samples, a cell size of 2 pixels, an NCC threshold of 0.7 that drops by 0.05 per round, and at least 3 images per patch.
  • Clustering for large scenes. CMVS splits a large photo collection into overlapping clusters of views that PMVS can handle one at a time.
  • Depth map methods. Many later systems compute a depth map per image, for example with PatchMatch stereo in its multi-view form or with a plane sweep, and merge them by depth map fusion. The tutorial of Furukawa and Hernández (2015) compares the two approaches.
  • Mesh refinement. A mesh made from the patches can be refined further with photo-consistency, which gives a smooth surface with finer detail.

When to use it

Use PMVS when you have calibrated images, for example from structure from motion, and want a dense, oriented point set with few outliers and no prior shape. It is a good input to Poisson surface reconstruction. For large photo collections or for a depth map per image, a depth map method with fusion is usually faster and easier to run in parallel.

Pitfalls

  • Normal direction. The normal must point toward the cameras. If refinement lets it turn away, the patch fails the angle test and is lost. Keep it in the half space that faces R(p)R(p), for example with the slope form the code uses.
  • Patch scale. The grid step must match about one pixel of R(p)R(p) at the depth of the patch. A fixed step in scene units gives patches that are too large near the cameras and too small far away.
  • Flat texture. NCC is undefined where the image is flat. Treat a zero variance as a failed match, not as a perfect one.
  • Grid outside an image. If a grid point projects outside an image, that image cannot score the patch. Drop it from V(p)V(p), do not compare a part of the grid.
  • Cells and drift. Refinement can move a new patch out of the cell it was made for. Without a test like line L13, expansion can make patch after patch for the same empty cell.
  • Filter thresholds. A distance ρ\rho that is too small removes good patches on curved surfaces; one that is too large keeps outliers.

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.

patch_based_multi_view_stereo.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/patch-based-multi-view-stereo/. The authors are listed in prov/22G2KD.jsonl.

"""Patch-based multi-view stereo (PMVS): match, expand, filter.

A camera is (K, R, t): a world point X maps to the camera frame by
Xc = R X + t, and to the pixel K Xc divided by its third entry. Images are
lists of rows of gray values, img[v][u]. A patch is a small square in space
with a center c, a unit normal n pointing toward its reference camera, a
reference image ref, a list V of images where it may be visible and a list
Vs of images where it is photo-consistent (Vs holds ref).

The steps follow Furukawa and Ponce (2010). The values of the parameters
and two details are choices of this code: the refinement is a pattern
search instead of conjugate gradient, and the filter is one rule of the
regularization kind (see the page).
"""

import math

INF = float("inf")


# ------------------------------------------------------------ 3D vectors

def add(a, b):
    return [a[0] + b[0], a[1] + b[1], a[2] + b[2]]


def sub(a, b):
    return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]


def mul(a, s):
    return [a[0] * s, a[1] * s, a[2] * s]


def dot(a, b):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def cross(a, b):
    return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]


def unit(a):
    s = math.sqrt(dot(a, a))
    return [a[0] / s, a[1] / s, a[2] / s]


def rmul(R, x):
    return [dot(R[0], x), dot(R[1], x), dot(R[2], x)]


def rtmul(R, x):
    """R^T x."""
    return [R[0][i] * x[0] + R[1][i] * x[1] + R[2][i] * x[2] for i in range(3)]


# --------------------------------------------------------------- cameras

def to_camera(cam, X):
    K, R, t = cam
    return add(rmul(R, X), t)


def project(cam, X):
    """Pixel (u, v) of X, or None if X is not in front of the camera."""
    K = cam[0]
    x = to_camera(cam, X)
    if x[2] <= 1e-12:
        return None
    a, b = x[0] / x[2], x[1] / x[2]
    return (K[0][0] * a + K[0][1] * b + K[0][2], K[1][1] * b + K[1][2])


def camera_matrix(cam):
    """The rows of P = K [R | t]."""
    K, R, t = cam
    Rt = [list(R[i]) + [t[i]] for i in range(3)]
    return [[sum(K[i][k] * Rt[k][j] for k in range(3)) for j in range(4)] for i in range(3)]


def center(cam):
    """C = -R^T t."""
    return mul(rtmul(cam[1], cam[2]), -1.0)


def ray(cam, u, v):
    """Unit direction, in the world, of the ray through the pixel (u, v)."""
    K, R, _ = cam
    y = (v - K[1][2]) / K[1][1]
    x = (u - K[0][2] - K[0][1] * y) / K[0][0]
    return unit(rtmul(R, [x, y, 1.0]))


def depth(cam, X):
    return to_camera(cam, X)[2]


def midpoint_triangulate(c1, d1, c2, d2):
    """Midpoint of the common perpendicular of two rays c + s d, or None if
    they are parallel or meet behind a camera."""
    w = sub(c1, c2)
    a, b, c = dot(d1, d1), dot(d1, d2), dot(d2, d2)
    d, e = dot(d1, w), dot(d2, w)
    den = a * c - b * b
    if abs(den) < 1e-12:
        return None
    s = (b * e - c * d) / den
    r = (a * e - b * d) / den
    if s <= 0 or r <= 0:
        return None
    return mul(add(add(c1, mul(d1, s)), add(c2, mul(d2, r))), 0.5)


# --------------------------------------------------------------- patches

class Patch:
    __slots__ = ("c", "n", "ref", "V", "Vs", "g")

    def __init__(self, c, n, ref):
        self.c, self.n, self.ref = c, n, ref
        self.V, self.Vs, self.g = [], [], INF


class Params:
    def __init__(self, mu=5, beta=3, gamma=2, alpha=0.3, max_angle=60.0, epipolar=2.0,
                 rounds=3, min_fraction=0.25, max_evals=30):
        self.mu = mu                  # the patch grid is mu x mu
        self.beta = beta              # cells are beta x beta pixels
        self.gamma = gamma            # least size of Vs
        self.alpha = alpha            # h <= alpha means photo-consistent (NCC >= 1 - alpha)
        self.max_angle = max_angle    # largest angle between n and the viewing ray, in degrees
        self.epipolar = epipolar      # largest distance to the epipolar line, in pixels
        self.rounds = rounds          # rounds of expansion and filtering
        self.min_fraction = min_fraction
        self.max_evals = max_evals


class Model:
    """The images, the cameras, the cells and the patches."""

    def __init__(self, images, cams, prm):
        self.images, self.cams, self.prm = images, cams, prm
        self.centers = [center(c) for c in cams]
        self.P = [camera_matrix(c) for c in cams]
        self.patches = []
        self.cells = [dict() for _ in images]   # cells[i][(cx, cy)] = list of patches

    def cell_of(self, i, X):
        p = project(self.cams[i], X)
        if p is None:
            return None
        h, w = len(self.images[i]), len(self.images[i][0])
        if not (0.0 <= p[0] < w and 0.0 <= p[1] < h):
            return None
        b = self.prm.beta
        return (int(p[0]) // b, int(p[1]) // b)

    def cell_count(self, i):
        h, w = len(self.images[i]), len(self.images[i][0])
        b = self.prm.beta
        return (w + b - 1) // b, (h + b - 1) // b

    def register(self, p):
        for i in p.Vs:
            cell = self.cell_of(i, p.c)
            if cell is not None:
                self.cells[i].setdefault(cell, []).append(p)
        self.patches.append(p)

    def unregister(self, p):
        for i in p.Vs:
            cell = self.cell_of(i, p.c)
            if cell is not None and cell in self.cells[i]:
                lst = self.cells[i][cell]
                lst[:] = [q for q in lst if q is not p]
                if not lst:
                    del self.cells[i][cell]

    # ---------------------------------------------- photometric discrepancy

    def spacing(self, p):
        """Size of one grid step: one pixel of the reference image at c."""
        K = self.cams[p.ref][0]
        return depth(self.cams[p.ref], p.c) / K[0][0]

    def grid(self, p):
        cam = self.cams[p.ref]
        yaxis = rtmul(cam[1], [0.0, 1.0, 0.0])
        ex = cross(yaxis, p.n)
        if dot(ex, ex) < 1e-12:
            ex = cross([1.0, 0.0, 0.0], p.n)
        ex = unit(ex)
        ey = cross(p.n, ex)
        s = self.spacing(p)
        m = self.prm.mu
        half = (m - 1) / 2.0
        return [add(p.c, add(mul(ex, (a - half) * s), mul(ey, (b - half) * s)))
                for b in range(m) for a in range(m)]

    def samples(self, i, pts):
        """Bilinear samples of image i at the projections of pts, or None
        if one of them falls outside the image."""
        out = []
        img = self.images[i]
        h, w = len(img), len(img[0])
        (a0, a1, a2, a3), (b0, b1, b2, b3), (c0, c1, c2, c3) = self.P[i]
        for x, y, z in pts:
            zc = c0 * x + c1 * y + c2 * z + c3
            if zc <= 1e-12:
                return None
            u = (a0 * x + a1 * y + a2 * z + a3) / zc
            v = (b0 * x + b1 * y + b2 * z + b3) / zc
            if not (0.0 <= u <= w - 1 and 0.0 <= v <= h - 1):
                return None
            iu, jv = min(int(u), w - 2), min(int(v), h - 2)
            fu, fv = u - iu, v - jv
            r0, r1 = img[jv], img[jv + 1]
            out.append((1 - fu) * (1 - fv) * r0[iu] + fu * (1 - fv) * r0[iu + 1]
                       + (1 - fu) * fv * r1[iu] + fu * fv * r1[iu + 1])
        return out

    def h(self, p, i, pts=None, ref_samples=None):
        """1 - NCC of the patch grid in image i and in the reference image."""
        pts = pts if pts is not None else self.grid(p)
        a = ref_samples if ref_samples is not None else self.samples(p.ref, pts)
        b = self.samples(i, pts)
        if a is None or b is None:
            return 2.0
        m = len(a)
        ma, mb = sum(a) / m, sum(b) / m
        sab = sum((x - ma) * (y - mb) for x, y in zip(a, b))
        saa = sum((x - ma) ** 2 for x in a)
        sbb = sum((y - mb) ** 2 for y in b)
        if saa < 1e-9 or sbb < 1e-9:
            return 1.0
        return 1.0 - sab / math.sqrt(saa * sbb)

    def g_star(self, p, views):
        """Mean discrepancy over the views other than the reference."""
        others = [i for i in views if i != p.ref]
        if not others:
            return INF
        pts = self.grid(p)
        a = self.samples(p.ref, pts)
        if a is None:
            return INF
        return sum(self.h(p, i, pts, a) for i in others) / len(others)

    def visible(self, p):
        """V(p): images that see c inside the image at an angle below max_angle."""
        out = []
        cosmax = math.cos(math.radians(self.prm.max_angle))
        for i, cam in enumerate(self.cams):
            if self.cell_of(i, p.c) is None:
                continue
            if dot(p.n, unit(sub(self.centers[i], p.c))) >= cosmax or i == p.ref:
                out.append(i)
        return out

    def consistent(self, p):
        """V*(p): the reference and the images of V(p) with h <= alpha."""
        pts = self.grid(p)
        a = self.samples(p.ref, pts)
        if a is None:
            return []
        return [i for i in p.V if i == p.ref or self.h(p, i, pts, a) <= self.prm.alpha]

    # ------------------------------------------------------------ refine

    def refine(self, p):
        """Minimize g* over the depth of c along the reference ray and the
        two slopes of n in the reference frame, by pattern search."""
        cam = self.cams[p.ref]
        C = self.centers[p.ref]
        d = unit(sub(p.c, C))
        nc = rmul(cam[1], p.n)             # the normal in the reference frame
        if nc[2] >= -1e-6:
            return
        x = [math.sqrt(dot(sub(p.c, C), sub(p.c, C))), -nc[0] / nc[2], -nc[1] / nc[2]]

        def place(v):
            return add(C, mul(d, v[0])), unit(rtmul(cam[1], [v[1], v[2], -1.0]))

        def cost(v):
            if v[0] <= 0:
                return INF
            p.c, p.n = place(v)
            return self.g_star(p, p.Vs)

        best = cost(x)
        steps = [2.0 * self.spacing(p), 0.25, 0.25]
        evals = 1
        while evals < self.prm.max_evals and steps[1] > 0.01:
            moved = False
            for k in range(3):
                for sgn in (1.0, -1.0):
                    y = list(x)
                    y[k] += sgn * steps[k]
                    cy = cost(y)
                    evals += 1
                    if cy < best:
                        x, best, moved = y, cy, True
                        break
            if not moved:
                steps = [s / 2.0 for s in steps]
        p.c, p.n = place(x)
        p.g = best

    def accept(self, p):
        """Refine p, recompute V and V*, and decide."""
        p.V = self.visible(p)
        p.Vs = self.consistent(p)
        if len(p.Vs) < 2:
            return False
        self.refine(p)
        p.V = self.visible(p)
        if p.ref not in p.V:
            return False
        p.Vs = self.consistent(p)
        p.g = self.g_star(p, p.Vs)
        return len(p.Vs) >= self.prm.gamma


# ------------------------------------------------------------- the steps

def match(model, features):
    """Initial matching. features[i] is a list of pixels (u, v) of image i."""
    prm = model.prm
    for i, feats in enumerate(features):                          # @line L1
        cam_i = model.cams[i]
        for (u, v) in feats:
            b = prm.beta
            if model.cells[i].get((int(u) // b, int(v) // b)):     # @line L2
                continue
            Ci, di = model.centers[i], ray(cam_i, u, v)
            cands = []
            for j, feats_j in enumerate(features):
                if j == i:
                    continue
                e0 = project(model.cams[j], add(Ci, mul(di, 1.0)))
                e1 = project(model.cams[j], add(Ci, mul(di, 100.0)))
                if e0 is None or e1 is None:
                    continue
                lx, ly = e1[0] - e0[0], e1[1] - e0[1]
                ln = math.hypot(lx, ly)
                for (u2, v2) in feats_j:
                    if ln > 0 and abs((u2 - e0[0]) * ly - (v2 - e0[1]) * lx) / ln > prm.epipolar:
                        continue                                   # @line L3
                    X = midpoint_triangulate(Ci, di, model.centers[j], ray(model.cams[j], u2, v2))
                    if X is not None:
                        cands.append(X)
            cands.sort(key=lambda X: dot(sub(X, Ci), sub(X, Ci)))   # @line L4
            for X in cands:
                p = Patch(X, unit(sub(Ci, X)), i)                  # @line L5
                if model.accept(p):                                # @line L6
                    model.register(p)                              # @line L7
                    break


def neighbors(p, q, rho):
    """The relation of the paper: q lies near the plane of p and p near the plane of q."""
    w = sub(p.c, q.c)
    return abs(dot(w, p.n)) + abs(dot(w, q.n)) < 2.0 * rho


def expand(model, start):
    """Expand from the patches in start, then from every new patch."""
    queue = list(start)
    k = 0
    while k < len(queue):                                          # @line L9
        p = queue[k]
        k += 1
        if p not in model.patches:
            continue
        for i in list(p.Vs):
            cell = model.cell_of(i, p.c)
            if cell is None:
                continue
            nx, ny = model.cell_count(i)
            for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                tgt = (cell[0] + dx, cell[1] + dy)
                if not (0 <= tgt[0] < nx and 0 <= tgt[1] < ny):
                    continue
                if model.cells[i].get(tgt):                        # @line L10
                    continue
                b = model.prm.beta
                u = min(tgt[0] * b + (b - 1) / 2.0, len(model.images[i][0]) - 1)
                v = min(tgt[1] * b + (b - 1) / 2.0, len(model.images[i]) - 1)
                Ci, di = model.centers[i], ray(model.cams[i], u, v)
                den = dot(di, p.n)
                if abs(den) < 1e-9:
                    continue
                s = dot(sub(p.c, Ci), p.n) / den                   # @line L11
                if s <= 0:
                    continue
                q = Patch(add(Ci, mul(di, s)), list(p.n), p.ref)  # @line L12
                if model.cell_of(p.ref, q.c) is None:
                    continue
                if model.accept(q) and i in q.Vs and model.cell_of(i, q.c) == tgt:  # @line L13
                    model.register(q)                              # @line L14
                    queue.append(q)


def filter_patches(model):
    """Remove p when few patches in the cells around it in the images of
    V*(p) are its neighbors. Returns the number removed."""
    remove = []
    for p in model.patches:                                        # @line L15
        rho = 2.0 * model.spacing(p)
        seen, near = 0, 0
        others = set()
        for i in p.Vs:
            cell = model.cell_of(i, p.c)
            if cell is None:
                continue
            for dx in (-1, 0, 1):
                for dy in (-1, 0, 1):
                    for q in model.cells[i].get((cell[0] + dx, cell[1] + dy), ()):
                        if q is not p and id(q) not in others:
                            others.add(id(q))
                            seen += 1
                            near += neighbors(p, q, rho)
        if seen > 0 and near < model.prm.min_fraction * seen:      # @line L16
            remove.append(p)
    gone = set(id(p) for p in remove)
    for p in remove:
        model.unregister(p)
    model.patches = [p for p in model.patches if id(p) not in gone]
    return len(remove)


def pmvs(images, cams, features, prm=None):
    """Run match, then rounds of expand and filter. Returns the model."""
    prm = prm or Params()
    model = Model(images, cams, prm)
    match(model, features)
    for _ in range(prm.rounds):                                    # @line L8
        expand(model, model.patches)
        filter_patches(model)
    return model                                                   # @line L17
test_patch_based_multi_view_stereo.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/patch-based-multi-view-stereo/. The authors are listed in prov/22G2KD.jsonl.

import functools
import math
import random

from patch_based_multi_view_stereo import (
    Model,
    Params,
    Patch,
    center,
    dot,
    expand,
    filter_patches,
    match,
    midpoint_triangulate,
    neighbors,
    pmvs,
    project,
    ray,
    sub,
    unit,
)

W = H = 24
K = [[40.0, 0.0, 11.5], [0.0, 40.0, 11.5], [0.0, 0.0, 1.0]]
I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]

# The plane Z = 4 + 0.15 X - 0.1 Y, written as N . X = D with a unit N.
N = unit([-0.15, 0.1, 1.0])
D = 4.0 * N[2]


def texture(seed):
    rng = random.Random(seed)
    waves = []
    for _ in range(5):
        period = rng.uniform(0.3, 0.8)
        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, 25.0)))

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

    return g


def camera(c, R=I3):
    t = [-sum(R[i][j] * c[j] for j in range(3)) for i in range(3)]
    return (K, R, t)


def render(cam, tex):
    C = center(cam)
    img = [[0.0] * W for _ in range(H)]
    for v in range(H):
        for u in range(W):
            d = ray(cam, u, v)
            s = (D - dot(N, C)) / dot(N, d)
            X = [C[k] + s * d[k] for k in range(3)]
            img[v][u] = tex(X[0], X[1])
    return img


def scene(extra_features=True):
    tex = texture(1)
    cams = [camera([0.0, 0.0, 0.0]), camera([0.5, 0.0, 0.0]), camera([0.1, 0.45, 0.0])]
    images = [render(c, tex) for c in cams]
    pts = []
    for X in (-0.5, 0.0, 0.5):
        for Y in (-0.4, 0.4):
            pts.append([X, Y, 4.0 + 0.15 * X - 0.1 * Y])
    rng = random.Random(2)
    features = []
    for cam in cams:
        f = [project(cam, X) for X in pts]
        f = [q for q in f if 0 <= q[0] <= W - 1 and 0 <= q[1] <= H - 1]
        if extra_features:
            f += [(rng.uniform(2, W - 3), rng.uniform(2, H - 3)) for _ in range(2)]
        features.append(f)
    return images, cams, features


def on_plane(X):
    return dot(N, X) - D


def test_midpoint_triangulation() -> None:
    rng = random.Random(4)
    for _ in range(50):
        X = [rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(3, 5)]
        c1, c2 = [rng.uniform(-1, 1), 0.0, 0.0], [0.0, rng.uniform(-1, 1), 0.5]
        Y = midpoint_triangulate(c1, unit(sub(X, c1)), c2, unit(sub(X, c2)))
        assert max(abs(a - b) for a, b in zip(X, Y)) < 1e-9


def test_ray_and_project() -> None:
    cam = camera([0.3, -0.2, 0.1])
    C = center(cam)
    for u, v in ((0.0, 0.0), (11.5, 11.5), (20.25, 3.5)):
        d = ray(cam, u, v)
        q = project(cam, [C[k] + 3.0 * d[k] for k in range(3)])
        assert abs(q[0] - u) < 1e-9 and abs(q[1] - v) < 1e-9


@functools.lru_cache(maxsize=None)
def full_run():
    images, cams, features = scene()
    model = Model(images, cams, Params())
    match(model, features)
    matched = len(model.patches)
    for _ in range(model.prm.rounds):
        expand(model, model.patches)
        filter_patches(model)
    return model, matched


def test_discrepancy_is_low_on_the_surface() -> None:
    images, cams, _ = scene()
    model = Model(images, cams, Params())
    X = [0.1, 0.05, 4.0 + 0.015 - 0.005]
    p = Patch(X, [-x for x in N], 0)
    p.V = model.visible(p)
    assert p.V == [0, 1, 2]
    g = {}
    for s in (0.9, 0.95, 1.0, 1.05, 1.1):
        p.c = [x * s for x in X]          # move it along the reference ray
        g[s] = model.g_star(p, p.V)
    assert g[1.0] < 0.01
    assert min(g, key=g.get) == 1.0


def test_reconstruction() -> None:
    model, matched = full_run()
    prm = model.prm
    ps = model.patches
    assert matched == 6
    assert len(ps) >= 40
    errs = sorted(abs(on_plane(p.c)) for p in ps)
    coss = sorted(-dot(p.n, N) for p in ps)
    assert errs[-1] < 0.1 and errs[len(errs) // 2] < 0.03      # 0.1 is one pixel at Z = 4
    assert coss[0] > 0.5 and coss[len(coss) // 2] > 0.95
    for p in ps:
        assert len(p.Vs) >= prm.gamma and p.ref in p.Vs
        assert p.g <= prm.alpha
    # Coverage of the cells of the reference image that the other images also see.
    covered = total = 0
    for cx in range(1, 7):
        for cy in range(1, 7):
            total += 1
            covered += bool(model.cells[0].get((cx, cy)))
    assert covered >= 0.8 * total


def copy_model():
    done, _ = full_run()
    model = Model(done.images, done.cams, Params())
    for p in done.patches:
        q = Patch(list(p.c), list(p.n), p.ref)
        q.V, q.Vs, q.g = list(p.V), list(p.Vs), p.g
        model.register(q)
    return model


def test_filter_keeps_a_clean_model() -> None:
    model = copy_model()
    assert filter_patches(model) == 0


def test_filter_removes_an_outlier() -> None:
    model = copy_model()
    count = len(model.patches)
    # A patch 0.4 in front of the plane, put in by hand into a full region.
    X = [0.0, 0.0, 3.6]
    bad = Patch(X, [0.0, 0.0, -1.0], 0)
    bad.V = bad.Vs = [0, 1, 2]
    model.register(bad)
    removed = filter_patches(model)
    assert bad not in model.patches
    assert removed <= 1 + count // 20
    for i in range(3):
        for lst in model.cells[i].values():
            assert all(q is not bad for q in lst)


def test_neighbors_relation() -> None:
    a = Patch([0.0, 0.0, 4.0], [0.0, 0.0, -1.0], 0)
    b = Patch([0.3, 0.0, 4.0], [0.0, 0.0, -1.0], 0)
    c = Patch([0.3, 0.0, 4.3], [0.0, 0.0, -1.0], 0)
    assert neighbors(a, b, 0.1) and neighbors(b, a, 0.1)
    assert not neighbors(a, c, 0.1)


def test_cells_and_termination() -> None:
    model, _ = full_run()
    # Every patch sits in the cell of its projection in each image of V*,
    # and expanding again from a finished model adds nothing.
    for p in model.patches:
        for i in p.Vs:
            assert any(q is p for q in model.cells[i][model.cell_of(i, p.c)])
    copy = copy_model()
    before = len(copy.patches)
    expand(copy, copy.patches)
    assert len(copy.patches) == before


def test_deterministic() -> None:
    images, cams, features = scene()
    m1 = pmvs(images, cams, features, Params(rounds=1))
    m2, _ = full_run()
    assert [p.c for p in m1.patches] == [p.c for p in m2.patches]

History

Furukawa and Ponce presented the method at CVPR 2007 and gave the full version in IEEE TPAMI in 2010. The TPAMI paper reports results on the Middlebury multi-view benchmark of Seitz et al. (2006), with its accuracy and completeness measures, and on other scenes. In that report the method was at the top for four of the six data sets of the benchmark. This is a benchmark result of that time, and the ranking depends on the version of the benchmark and on the methods submitted. The software, PMVS and later PMVS2 with CMVS for large collections, became a standard tool for dense reconstruction from photo collections.

References

  1. Yasutaka Furukawa and Jean Ponce, Accurate, dense, and robust multiview stereopsis, IEEE Transactions on Pattern Analysis and Machine Intelligence 32(8), pages 1362 to 1376, 2010, the patch model with its reference image and visible images, the photometric discrepancy by normalized cross-correlation, the image cells, and the three steps of matching, expansion and filtering
  2. Yasutaka Furukawa and Carlos Hernández, Multi-view stereo: a tutorial, Foundations and Trends in Computer Graphics and Vision 9(1-2), pages 1 to 148, 2015, the chapter on multi-view stereo algorithms (point cloud reconstruction by patch expansion)
  3. Steven M. Seitz, Brian Curless, James Diebel, Daniel Scharstein and Richard Szeliski, A comparison and evaluation of multi-view stereo reconstruction algorithms, IEEE Conference on Computer Vision and Pattern Recognition 2006, the benchmark data sets and the accuracy and completeness measures

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