Algorithm Search⌘K

Algorithmcore

Plane sweep stereo

Also called Collins plane sweep, space-sweep stereo.

Warp the other images onto a series of planes through the scene by homographies, score photo-consistency at each, and give every pixel the depth of its best plane.

Time
Θ(D N W H) worst · average · best
Space
Θ(W H) extra
Where
D = the number of planes; H = the image height in pixels; N = the number of images; W = the image width in pixels
Properties
deterministicnot exactofflineiterative
Origin
Robert T. Collins, 1996

Plane sweep stereo computes a depth map for one reference image from any number of calibrated images. It moves a plane through the scene in small steps. For each position of the plane, it maps every other image onto the reference image with the homography that the plane induces, and compares the colors pixel by pixel. Where the plane passes through the true surface, the mapped images agree with the reference, so the cost is low. Each pixel takes the plane with the lowest cost over a small window, and its depth is where its ray meets that plane. The costs for all planes form a cost volume, the same object that block matching builds for a rectified pair. Plane sweep needs no rectification and uses all images at once, which is why it is a standard first step of multi-view stereo.

In plain words

Hold a large glass sheet in front of a camera at some distance, and imagine that every camera projects its photo onto the sheet. Where a real object touches the sheet, all the projected photos show the same color at that spot, because they all saw the same point. Where the object is in front of or behind the sheet, the photos land in different places and disagree. Now move the sheet away from the camera step by step and note, for each pixel, the distance at which the photos agreed best. That distance is the depth of the pixel. The work is the same for every step, so a graphics card can do it very fast.

The problem

Input.

  • A reference image I0I_0 and other images I1,…,IN−1I_1, \dots, I_{N-1}, all W×HW \times H gray images. Pixel (u,v)(u, v) is img[v][u].
  • The cameras. Camera 0 is K0[I∣0]K_0 [I \mid 0], so its frame is the frame of the scene. Camera kk maps a point XX to Xk=RkX+tkX_k = R_k X + t_k and has the intrinsic matrix KkK_k (see pinhole camera model).
  • A unit normal nn and offsets d1,…,dD>0d_1, \dots, d_D > 0. Plane jj is the set of points with n⊤X=djn^\top X = d_j. For fronto-parallel planes n=(0,0,1)n = (0, 0, 1) and djd_j is a depth.
  • A window radius rr.

Output. For each reference pixel pp, the index j∗(p)j^*(p) of the plane with the least window cost, and the depth Z(p)Z(p) of the point where the ray of pp meets that plane.

The window cost of plane jj at pp is Sj(p)=∑qej(q)S_j(p) = \sum_{q} e_j(q) over the pixels qq of the (2r+1)×(2r+1)(2r+1) \times (2r+1) window of pp that lie inside the image, where ej(q)e_j(q) is the mean of ∣I0(q)−Ik(Hjkq)∣|I_0(q) - I_k(H_{jk} q)| over the cameras k≥1k \ge 1 in which HjkqH_{jk} q falls inside the image. This is a photo-consistency measure that assumes Lambertian surfaces. Other measures, such as normalized cross-correlation, fit in the same place.

The algorithm

  1. PLANE-SWEEP(I_0, ..., I_{N-1}, cameras, n, d_1..d_D, r)
  2. 1for each pixel p do best[p] ← ∞
  3. 2for j ← 1 to D do
  4. 3for k ← 1 to N - 1 do H_k ← K_k (R_k + t_k n^T / d_j) K_0^-1
  5. 4for each pixel p = (u, v) do
  6. 5e(p) ← mean over the cameras k with H_k p inside I_k of |I_0(p) - I_k(H_k p)|, or a fixed cost if no camera sees p
  7. 6S ← the sum of e over the (2r+1) × (2r+1) window of each pixel
  8. 7for each pixel p do
  9. 8if S(p) < best[p] then best[p] ← S(p); index[p] ← j
  10. 9for each pixel p do depth[p] ← d_index[p] / (n^T K_0^-1 p̃)
  11. 10return index, depth

Line L3, the homography. A point XX on plane jj satisfies n⊤X/dj=1n^\top X / d_j = 1, so Xk=RkX+tk=(Rk+tkn⊤/dj)XX_k = R_k X + t_k = (R_k + t_k n^\top / d_j) X. The reference pixel of XX is p~∼K0X\tilde p \sim K_0 X, so XX is a multiple of K0−1p~K_0^{-1} \tilde p, and the pixel of XX in camera kk is Hkp~H_k \tilde p. Here p~=(u,v,1)\tilde p = (u, v, 1) and ∼\sim means equal up to a scale. The sign of the term tkn⊤/djt_k n^\top / d_j depends on how the plane is written: with n⊤X+d=0n^\top X + d = 0 it becomes a minus. Check the sign with one point before you trust a formula from another source.

Line L5, the warp. Hkp~H_k \tilde p has fractional coordinates, so IkI_k is read by bilinear interpolation. On a GPU the whole image IkI_k is drawn onto the reference view with the texture unit, which is why this step is fast there. The code divides the sum by the number of cameras that see the point. Gallup et al. sum over all cameras and also multiply each image by a gain ratio, to allow for changes of exposure.

Line L6, the window. The window sum takes O(1)O(1) per pixel with an integral image. The window is what makes the result stable: a single pixel matches many wrong planes by chance.

Line L8, the choice. This is winner-takes-all over the cost volume. The strict test keeps the first of two equal costs. A global method, such as semi-global matching or graph cuts, can replace it.

Line L9, the depth. The ray of pp is the set of points sK0−1p~s K_0^{-1} \tilde p. It meets n⊤X=dn^\top X = d at s=d/(n⊤K0−1p~)s = d / (n^\top K_0^{-1} \tilde p), and the third entry of K0−1p~K_0^{-1} \tilde p is 1, so ss is the depth ZZ.

Plane spacing. For a camera at the baseline bb from the reference, a fronto-parallel plane at depth ZZ shifts pixels by the disparity fb/Zf b / Z. Planes that are equally spaced in depth are too dense near the cameras and too sparse far away. Gallup et al. space them so that the image of a point moves by at most one pixel from one plane to the next, which for this case means equal steps of 1/(fb)1 / (f b) in 1/Z1 / Z.

Example

One camera shift. Take fx=fy=50f_x = f_y = 50 and a second camera at the center (0.2,0,0)(0.2, 0, 0) with R=IR = I, so t=(−0.2,0,0)t = (-0.2, 0, 0). For n=(0,0,1)n = (0, 0, 1) the homography is H=K(I+tn⊤/Z)K−1H = K (I + t n^\top / Z) K^{-1}, which moves every pixel by −50⋅0.2/Z=−10/Z-50 \cdot 0.2 / Z = -10 / Z in uu and does not change vv. The four planes at Z=2,2.5,5,10Z = 2, 2.5, 5, 10 move the pixel (7,3)(7, 3) to (2,3)(2, 3), (3,3)(3, 3), (5,3)(5, 3) and (6,3)(6, 3). If the pixel (3,3)(3, 3) of the second image shows the same point as (7,3)(7, 3) of the reference, the plane at Z=2.5Z = 2.5 wins at that pixel.

Plane spacing. With f=500f = 500 pixels and b=0.1b = 0.1 m, the disparity is 50/Z50 / Z. From Z=1Z = 1 m (disparity 50) to Z=10Z = 10 m (disparity 5), steps of one pixel in disparity need 46 planes: Z=1,1.0204,1.0417,…,10Z = 1, 1.0204, 1.0417, \dots, 10. Equal steps in depth with the same step at 1 m, which is about 0.02 m, would need about 440 planes.

Two planes. The test file ray-casts a 24×2024 \times 20 scene for three cameras with f=40f = 40: a textured back plane at Z=4Z = 4 and a textured rectangle at Z=2.5Z = 2.5 in front of it. One camera moves 0.4 to the right, one moves to the left and down (the YY axis points down) and turns slightly. A sweep over the 9 depths {2,2.25,2.5,2.8,3.2,3.6,4,4.5,5}\{2, 2.25, 2.5, 2.8, 3.2, 3.6, 4, 4.5, 5\} with a 3×33 \times 3 window gives the true depth at 453 of the 480 pixels; this map shows the index of the winning plane per pixel (2 is Z=2.5Z = 2.5, 6 is Z=4Z = 4):

000666666666666666666666
666666666666666666666666
666666666666666666666666
666666666666666666666666
666666666666066666666666
666666666666333666666666
666666122222222366666666
666666122222222236666666
666666632222222220666666
666666632222222200666666
666666642222222226666666
666666641222222216666666
666666641222222211666666
666666666222221016666666
666666666666666666666666

(The last five rows are all 6 and are not shown.) The errors lie on the edges of the rectangle, where the window covers both depths and one camera sees the back plane behind the edge, and in the top left corner, which no other camera sees, so all planes tie and the first one wins. With a window of one pixel (r=0r = 0), 113 pixels get a wrong plane.

Correctness

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

  1. The homography lemma. If XX lies on the plane n⊤X=dn^\top X = d and p~∼K0X\tilde p \sim K_0 X, then Hp~∼Kk(RkX+tk)H \tilde p \sim K_k (R_k X + t_k), the image of XX in camera kk. So ej(p)e_j(p) compares the reference with exactly the pixels that see the point where the ray of pp meets plane jj, and line L9 returns the depth of that point.
  2. The choice. After the iteration for plane jj, best[p]=min⁡i≤jSi(p)best[p] = \min_{i \le j} S_i(p) and index[p]index[p] is the first index that reaches it. So the output is the winner-takes-all minimizer of the cost volume, with ties to the first plane.

The method is exact for the cost it defines. Whether the cost has its minimum at the true depth is a property of the scene: it needs texture, Lambertian surfaces, a point that all used cameras see, a window on which the surface is close to the swept plane, and a true depth close to one of the djd_j. None of this is guaranteed, and the example shows the errors when it fails.

Proof: Plane sweep stereo compares the right pixels and returns the winner-takes-all plane of its cost volumefull

We use the pseudocode of the page. Camera 0 is K0[I∣0]K_0 [I \mid 0] and camera kk maps a point XX to Xk=RkX+tkX_k = R_k X + t_k, with the intrinsic matrix KkK_k. A plane is Π={X:n⊤X=d}\Pi = \{X : n^\top X = d\} with d≠0d \ne 0. For a pixel p=(u,v)p = (u, v) we write p~=(u,v,1)⊤\tilde p = (u, v, 1)^\top, and a∼ba \sim b means a=λba = \lambda b for some λ≠0\lambda \ne 0. All KK are invertible upper triangular matrices with last row (0,0,1)(0, 0, 1).

Lemma 1 (the ray of a pixel meets the plane at the depth of line L9). Let m=K0−1p~m = K_0^{-1} \tilde p and suppose n⊤m≠0n^\top m \ne 0. The ray {sm:s>0}\{s m : s > 0\} of pp meets Π\Pi at X=s∗mX = s^* m with s∗=d/(n⊤m)s^* = d / (n^\top m), and the depth of XX in camera 0 is Z=s∗Z = s^*.

Proof. n⊤(sm)=dn^\top (s m) = d holds exactly for s=d/(n⊤m)s = d / (n^\top m). The last row of K0K_0 is (0,0,1)(0, 0, 1), so the last row of K0−1K_0^{-1} is also (0,0,1)(0, 0, 1) and m3=1m_3 = 1. The depth of X=s∗mX = s^* m is its third coordinate, s∗m3=s∗s^* m_3 = s^*. □\square

Lemma 2 (homography). Let H=Kk(Rk+tkn⊤/d)K0−1H = K_k (R_k + t_k n^\top / d) K_0^{-1}. For every point X∈ΠX \in \Pi with p~∼K0X\tilde p \sim K_0 X, we have Hp~∼Kk(RkX+tk)H \tilde p \sim K_k (R_k X + t_k). So if XX is in front of camera kk, HH maps the reference pixel of XX to the pixel of XX in camera kk.

Proof. From p~∼K0X\tilde p \sim K_0 X we get K0−1p~=λXK_0^{-1} \tilde p = \lambda X for some λ≠0\lambda \ne 0. Since n⊤X=dn^\top X = d, we have tkn⊤X/d=tkt_k n^\top X / d = t_k. Then

Hp~=Kk(Rk+tkn⊤d)λX=λKk(RkX+tkn⊤Xd)=λKk(RkX+tk).H \tilde p = K_k \left(R_k + \frac{t_k n^\top}{d}\right) \lambda X = \lambda K_k \left(R_k X + t_k \frac{n^\top X}{d}\right) = \lambda K_k (R_k X + t_k).

The pixel of XX in camera kk is KkXkK_k X_k divided by its third entry, which is the depth of XkX_k and is positive when XX is in front of the camera. □\square

Corollary. In lines L3 to L5 for plane jj, the sample Ik(Hkp~)I_k(H_k \tilde p) is the value of image kk at the projection of the point Xj(p)X_j(p) where the ray of pp meets plane jj (by Lemmas 1 and 2, with λ=1/s∗\lambda = 1 / s^*). So ej(p)e_j(p) is the mean absolute difference between I0(p)I_0(p) and the values that the cameras which see Xj(p)X_j(p) inside their images record there. Line L9 returns the depth of Xindex[p](p)X_{index[p]}(p) by Lemma 1.

The code checks the sign of the third entry of Hkp~H_k \tilde p. With d>0d > 0 and n⊤m>0n^\top m > 0, the factor λ=n⊤m/d\lambda = n^\top m / d is positive, so this sign is the sign of the depth of Xj(p)X_j(p) in camera kk, and points behind camera kk are skipped.

Lemma 3 (window sums). Line L6 sets S(p)=∑e(q)S(p) = \sum e(q) over the pixels qq of the window of pp inside the image.

Proof. The integral image T[v][u]=∑v′<v, u′<ue(v′,u′)T[v][u] = \sum_{v' < v,\, u' < u} e(v', u') is built row by row with T[v+1][u+1]=T[v][u+1]+∑u′≤ue(v,u′)T[v+1][u+1] = T[v][u+1] + \sum_{u' \le u} e(v, u'), which is the definition. For the window rows [v0,v1)[v_0, v_1) and columns [u0,u1)[u_0, u_1) cut at the border, inclusion and exclusion give ∑=T[v1][u1]−T[v0][u1]−T[v1][u0]+T[v0][u0]\sum = T[v_1][u_1] - T[v_0][u_1] - T[v_1][u_0] + T[v_0][u_0]. □\square

Lemma 4 (invariant of lines L2 to L8). After the iteration for plane jj, for every pixel pp: best[p]=min⁡i≤jSi(p)best[p] = \min_{i \le j} S_i(p), and index[p]index[p] is the least i≤ji \le j with Si(p)=best[p]S_i(p) = best[p].

Proof. By induction on jj. Before the first iteration best[p]=∞best[p] = \infty, which is the minimum over the empty set. Suppose the claim holds after plane j−1j - 1. If Sj(p)<best[p]S_j(p) < best[p], line L8 sets best[p]=Sj(p)best[p] = S_j(p), which is now the strict minimum, and index[p]=jindex[p] = j is the only index that reaches it. Otherwise Sj(p)≥min⁡i<jSi(p)S_j(p) \ge \min_{i < j} S_i(p), so the minimum does not change, and the least index that reaches it is still the old one, since jj is larger. □\square

Theorem. PLANE-SWEEP returns, for every pixel pp, the least index j∗j^* that minimizes the window cost Sj(p)S_j(p) over all planes, and the depth at which the ray of pp meets plane j∗j^*. The cost Sj(p)S_j(p) is the window sum of the mean absolute differences between the reference and the cameras that see the point where the ray of each window pixel meets plane jj.

Proof. Lemma 4 with j=Dj = D gives the index, Lemma 3 and the corollary give the meaning of SjS_j, and Lemma 1 gives the depth. ■\blacksquare

What is not proved. The theorem is about the cost, not the scene. The minimum of Sj(p)S_j(p) lies at the true depth only when the surface is Lambertian and textured near pp, when all cameras used see it, when the surface is close to the swept plane over the whole window, and when a plane passes near the true depth. None of these holds everywhere in real images, so plane sweep is an estimator and has no error bound in general.

Complexity

The model is the real RAM: the homography, the bilinear sample and the absolute difference each cost O(1)O(1).

  • One plane. Line L3 costs O(N)O(N). Lines L4 and L5 cost Θ(NWH)\Theta(N W H). Line L6 costs Θ(WH)\Theta(W H) with an integral image, independent of rr. Lines L7 and L8 cost Θ(WH)\Theta(W H).
  • All planes. Θ(DNWH)\Theta(D N W H) time in every case, since no step depends on the data.
  • Space. The arrays best, index, ee and SS take Θ(WH)\Theta(W H). The code never stores the whole cost volume, which would take Θ(DWH)\Theta(D W H); keep it only if a later step, such as subpixel refinement or a global method, needs it.

The work for one plane is a texture warp and a box filter for each image, which a GPU does for every pixel in parallel. This is how Yang and Pollefeys, and later Gallup et al., ran the sweep in real time.

Properties

  • Any number of images, no rectification. The homography handles any camera pose. Adding an image adds one warp per plane.
  • Deterministic and data independent. The same steps run for every plane and pixel.
  • Discrete depths. The output depth is one of the planes. The error is at most half the spacing of the planes, unless a refinement step follows.
  • Fronto-parallel bias. The window assumes that the surface is parallel to the plane over the window. A slanted surface makes the window cost high at every plane. Sweeping planes with the normal of the surface removes this bias.
  • No occlusion model. A pixel that one camera does not see adds a high cost for the right plane.

Variants and improvements

  • Feature space sweep. Collins (1996) swept a plane through the scene and, at each position, back-projected the features of all images onto the plane and counted how many met in each cell. Cells with many votes are 3D features. It was made for sparse features.
  • Dense sweep on the GPU. Yang and Pollefeys made the dense version above run in real time by doing the warps with graphics hardware, as Gallup et al. describe.
  • Several sweep directions. Gallup et al. (2007) find the main surface normals of an urban scene (ground and facades) from sparse 3D points of structure from motion, sweep once for each normal, and pick per pixel the best depth and normal over all sweeps, with best cost or with a graph cut. This removes the fronto-parallel bias on planar scenes.
  • Occlusion. Following Kang et al., Gallup et al. compute the cost once with the cameras on the left and once with those on the right of the reference, and keep the lower one, since the visibility of a point usually changes only once along a row of cameras.
  • Plane priors. Gallup et al. also use the sparse points to sweep planes only near depths where the points suggest a surface, which saves time and helps on textureless walls.
  • Per-pixel planes. PatchMatch stereo and its multi-view successors give every pixel its own plane and search the planes at random instead of sweeping a fixed set.
  • Fusion. One sweep gives one depth map. Depth map fusion combines the maps of many reference views into one model.

When to use it

Use plane sweep when you have several calibrated images, for example frames of a video with known poses, and need a depth map fast, in particular on a GPU. It is the multi-view form of block matching and fails in the same places: textureless areas, occlusions and slanted surfaces. For a rectified pair, block matching on the disparity is the same computation with a cheaper warp. When quality matters more than speed, use a per-pixel plane search such as PatchMatch stereo or a global method on the cost volume.

Pitfalls

  • Plane sign convention. n⊤X=dn^\top X = d and n⊤X+d=0n^\top X + d = 0 give opposite signs in the homography. Test the homography by mapping one point of the plane before you sweep.
  • Which frame. The plane must be given in the frame of the reference camera, and Rk,tkR_k, t_k must map that frame to camera kk. If the poses are given in a world frame, convert them first.
  • Equal steps in depth. They waste planes near the cameras and miss depths far away. Space the planes in inverse depth, or by the pixel motion they cause.
  • Points behind a camera. A homography also maps points behind camera kk into the image. Skip a sample when the third coordinate of Hkp~H_k \tilde p is not positive.
  • Cameras that do not see the point. Averaging over only the cameras that see the sample, as the code does, keeps the cost comparable between pixels. A plain sum gives low costs to pixels near the border that few cameras see.
  • Gain changes. The absolute difference assumes equal exposure. Use a gain ratio, as Gallup et al. do, or a measure like NCC.

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.

cvgeom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Camera geometry and synthetic scenes for the computer vision pages.

Conventions (prompts of the area, also stated on the pages):
- The camera frame has X to the right, Y down and Z forward. A point is in
  front of the camera if Z > 0.
- K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]] in pixels.
- A world point Xw maps to the camera frame by Xc = R Xw + t. The camera
  matrix is P = K [R | t], and the center is C = -R^T t.
- Rotations are active and right-handed. Quaternions are (w, x, y, z) in the
  Hamilton convention.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import math
import random
from typing import Dict, List, Optional, Sequence, Tuple

from cvla import det, matvec, mul, solve, transpose

Matrix = List[List[float]]
Vector = List[float]


def to_h(x: Sequence[float]) -> Vector:
    """Append a 1: the homogeneous vector of a point."""
    return [float(v) for v in x] + [1.0]


def from_h(x: Sequence[float]) -> Vector:
    """Divide by the last entry and drop it. Raises ValueError if the last
    entry is zero (a point at infinity)."""
    w = x[-1]
    if w == 0:
        raise ValueError("from_h: point at infinity")
    return [v / w for v in x[:-1]]


def make_K(fx: float, fy: float, cx: float, cy: float, s: float = 0.0) -> Matrix:
    """The intrinsic matrix [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
    return [[float(fx), float(s), float(cx)],
            [0.0, float(fy), float(cy)],
            [0.0, 0.0, 1.0]]


def camera_matrix(K: Sequence[Sequence[float]], R: Sequence[Sequence[float]],
                  t: Sequence[float]) -> Matrix:
    """The 3 x 4 camera matrix P = K [R | t]."""
    rt = [list(R[i]) + [t[i]] for i in range(3)]
    return mul(K, rt)


def project(P: Sequence[Sequence[float]], X):
    """Pixel coordinates (u, v) of a point X under the camera P.

    X is a 3D point (3 entries) or a homogeneous point (4 entries). If X is
    a list of points, the result is the list of their projections."""
    if len(X) > 0 and isinstance(X[0], (list, tuple)):
        return [project(P, x) for x in X]
    xh = to_h(X) if len(X) == 3 else list(X)
    return from_h(matvec(P, xh))


def camera_center(P: Sequence[Sequence[float]]) -> Vector:
    """The center C of a finite camera P = [M | p4]: C = -M^-1 p4, so that
    P (C, 1) = 0."""
    m = [list(row[:3]) for row in P]
    p4 = [row[3] for row in P]
    return [-v for v in solve(m, p4)]


def rot_x(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the X axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def axis_angle_to_R(axis: Sequence[float], theta: Optional[float] = None) -> Matrix:
    """Rotation by theta (radians) about the axis, by the right-hand rule
    (Rodrigues formula). The axis need not be a unit vector. If theta is
    None, axis is the rotation vector w = theta a, with theta = ||w||."""
    n = math.sqrt(sum(float(v) * float(v) for v in axis))
    if theta is None:
        theta = n
    if n == 0.0 or theta == 0.0:
        return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    x, y, z = (float(v) / n for v in axis)
    c, s = math.cos(theta), math.sin(theta)
    d = 1.0 - c
    return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
            [y * x * d + z * s, c + y * y * d, y * z * d - x * s],
            [z * x * d - y * s, z * y * d + x * s, c + z * z * d]]


def quat_to_R(q: Sequence[float]) -> Matrix:
    """Rotation matrix of the quaternion q = (w, x, y, z), Hamilton
    convention. q is normalized first; q and -q give the same matrix."""
    n = math.sqrt(sum(float(v) * float(v) for v in q))
    if n == 0.0:
        raise ValueError("quat_to_R: zero quaternion")
    w, x, y, z = (float(v) / n for v in q)
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def random_rotation(rng: random.Random) -> Matrix:
    """A rotation drawn from the uniform (Haar) distribution: a uniform
    random unit quaternion by the method of Shoemake (1992)."""
    u1, u2, u3 = rng.random(), rng.random(), rng.random()
    a, b = math.sqrt(1.0 - u1), math.sqrt(u1)
    q = (b * math.cos(2 * math.pi * u3), a * math.sin(2 * math.pi * u2),
         a * math.cos(2 * math.pi * u2), b * math.sin(2 * math.pi * u3))
    return quat_to_R(q)


def _small_rotation(rng: random.Random, max_angle: float) -> Matrix:
    axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
    return axis_angle_to_R(axis, rng.uniform(0.0, max_angle))


def random_scene(rng: random.Random, n: int = 20, n_cams: int = 2,
                 K: Optional[Sequence[Sequence[float]]] = None,
                 cams: Optional[Sequence[Tuple]] = None,
                 radius: float = 1.0, distance: float = 5.0,
                 max_angle: float = 0.3, planar: bool = False,
                 first_identity: bool = False,
                 size: Optional[Tuple[float, float]] = None,
                 min_depth: float = 0.1) -> Dict[str, list]:
    """A synthetic scene with known cameras and points.

    Cameras: if cams is given, it is a list of (K, R, t) and is used as it
    is. Otherwise n_cams cameras look at the world origin from the distance
    `distance`. Each one is the camera at center (0, 0, -distance) with
    R = I, turned about the origin by a random rotation of angle at most
    max_angle (radians). K defaults to make_K(800, 800, 320, 240). With
    first_identity, the world frame is moved to the frame of camera 0, so
    that camera 0 has R = I and t = 0 (the points move with it).

    Points: n points drawn uniformly in the cube [-radius, radius]^3 (with
    Z = 0 if planar, before any move of the world frame). A point is kept
    only if its depth is at least min_depth in every camera, and, if size =
    (W, H) is given, if its projection lies in [0, W] x [0, H] in every
    camera. Raises ValueError if 1000 n draws are not enough.

    Returns a dict with lists "K", "R", "t", "P" (one entry per camera),
    "X" (the 3D points) and "x" (x[i][j] is the pixel of point j in
    camera i, without noise)."""
    if cams is not None:
        Ks = [[list(r) for r in c[0]] for c in cams]
        Rs = [[list(r) for r in c[1]] for c in cams]
        ts = [list(c[2]) for c in cams]
    else:
        k0 = [list(r) for r in K] if K is not None else make_K(800, 800, 320, 240)
        Ks, Rs, ts = [], [], []
        c0 = [0.0, 0.0, -float(distance)]
        for _ in range(n_cams):
            q = _small_rotation(rng, max_angle)
            r = transpose(q)
            center = matvec(q, c0)
            Ks.append([list(row) for row in k0])
            Rs.append(r)
            ts.append([-v for v in matvec(r, center)])
    pts: List[Vector] = []
    tries = 0
    while len(pts) < n:
        tries += 1
        if tries > 1000 * max(n, 1):
            raise ValueError("random_scene: cannot place the points")
        x = [rng.uniform(-radius, radius) for _ in range(3)]
        if planar:
            x[2] = 0.0
        ok = True
        for k, r, t in zip(Ks, Rs, ts):
            xc = [a + b for a, b in zip(matvec(r, x), t)]
            if xc[2] < min_depth:
                ok = False
                break
            if size is not None:
                u = (k[0][0] * xc[0] + k[0][1] * xc[1]) / xc[2] + k[0][2]
                v = k[1][1] * xc[1] / xc[2] + k[1][2]
                if not (0.0 <= u <= size[0] and 0.0 <= v <= size[1]):
                    ok = False
                    break
        if ok:
            pts.append(x)
    if first_identity and Rs:
        r0, t0 = Rs[0], ts[0]
        pts = [[a + b for a, b in zip(matvec(r0, x), t0)] for x in pts]
        r0t = transpose(r0)
        newR, newt = [], []
        for r, t in zip(Rs, ts):
            rr = mul(r, r0t)
            newR.append(rr)
            newt.append([a - b for a, b in zip(t, matvec(rr, t0))])
        Rs, ts = newR, newt
        Rs[0] = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
        ts[0] = [0.0, 0.0, 0.0]
    Ps = [camera_matrix(k, r, t) for k, r, t in zip(Ks, Rs, ts)]
    xs = [[project(p, x) for x in pts] for p in Ps]
    return {"K": Ks, "R": Rs, "t": ts, "P": Ps, "X": pts, "x": xs}


def add_noise(rng: random.Random, pts: Sequence[Sequence[float]], sigma: float) -> List[Vector]:
    """A copy of the points with independent Gaussian noise of standard
    deviation sigma added to every coordinate."""
    return [[float(v) + rng.gauss(0.0, sigma) for v in p] for p in pts]


def self_test() -> None:
    """Check random_scene and quat_to_R. Raises AssertionError."""
    rng = random.Random(11)
    scene = random_scene(rng, n=30, n_cams=4)
    for r, t in zip(scene["R"], scene["t"]):
        for x in scene["X"]:
            assert matvec(r, x)[2] + t[2] > 0.0
    for _ in range(5):
        q = [rng.gauss(0.0, 1.0) for _ in range(4)]
        r = quat_to_R(q)
        rtr = mul(transpose(r), r)
        assert all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) <= 1e-12
                   for i in range(3) for j in range(3))
        assert abs(det(r) - 1.0) <= 1e-12


if __name__ == "__main__":
    self_test()
cvla.py 494 lines
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import cmath
import math
from typing import List, Sequence, Tuple

Matrix = List[List[float]]
Vector = List[float]

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


# ---------------------------------------------------------------- basics

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """The cross product a x b of two 3-vectors."""
    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 skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


# ---------------------------------------------------------- polynomials

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
plane_sweep_stereo.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plane-sweep-stereo/. The authors are listed in prov/8EH0Z3.jsonl.

"""Plane sweep stereo with plane-induced homographies.

Coordinates are those of the reference camera 0: K_0 [I | 0]. Camera k maps a
point X of the reference frame to X_k = R_k X + t_k and has intrinsics K_k.
A sweep plane is n^T X = d with a unit normal n and d > 0. Images are lists of
rows of gray values, indexed img[v][u].
"""

from cvla import inv, matvec, mul

INF = float("inf")


def plane_homography(K0, Kk, R, t, n, d):
    """H = K_k (R + t n^T / d) K_0^-1, which maps reference pixels on the plane n^T X = d to camera k."""
    A = [[R[i][j] + t[i] * n[j] / d for j in range(3)] for i in range(3)]
    return mul(mul(Kk, A), inv(K0))


def bilinear(img, u, v):
    """Bilinear sample at (u, v), or None outside [0, W-1] x [0, H-1]."""
    h, w = len(img), len(img[0])
    if not (0.0 <= u <= w - 1 and 0.0 <= v <= h - 1):
        return None
    i, j = min(int(u), w - 2), min(int(v), h - 2)
    a, b = u - i, v - j
    r0, r1 = img[j], img[j + 1]
    return ((1 - a) * (1 - b) * r0[i] + a * (1 - b) * r0[i + 1]
            + (1 - a) * b * r1[i] + a * b * r1[i + 1])


def pixel_costs(images, cams, n, d, miss):
    """Mean absolute difference between the reference and the warped images, per pixel.

    cams[k] = (K_k, R_k, t_k) for k >= 1; cams[0] holds K_0. A pixel that no
    other camera sees on this plane gets the cost miss.
    """
    ref = images[0]
    h, w = len(ref), len(ref[0])
    K0 = cams[0][0]
    Hs = [plane_homography(K0, cams[k][0], cams[k][1], cams[k][2], n, d)  # @line L3
          for k in range(1, len(images))]
    e = [[miss] * w for _ in range(h)]
    for v in range(h):
        for u in range(w):  # @line L4
            total, count = 0.0, 0
            for k, H in enumerate(Hs, start=1):
                x = matvec(H, [u, v, 1.0])
                if x[2] <= 0.0:
                    continue
                s = bilinear(images[k], x[0] / x[2], x[1] / x[2])
                if s is not None:
                    total += abs(ref[v][u] - s)
                    count += 1
            if count:
                e[v][u] = total / count  # @line L5
    return e


def box_sum(e, r):
    """Sum of e over the (2r+1) x (2r+1) window, cut at the image border, by an integral image."""
    h, w = len(e), len(e[0])
    S = [[0.0] * (w + 1) for _ in range(h + 1)]
    for v in range(h):
        acc = 0.0
        for u in range(w):
            acc += e[v][u]
            S[v + 1][u + 1] = S[v][u + 1] + acc
    out = [[0.0] * w for _ in range(h)]
    for v in range(h):
        v0, v1 = max(v - r, 0), min(v + r + 1, h)
        for u in range(w):
            u0, u1 = max(u - r, 0), min(u + r + 1, w)
            out[v][u] = S[v1][u1] - S[v0][u1] - S[v1][u0] + S[v0][u0]
    return out


def plane_sweep(images, cams, n, ds, r, miss=255.0):
    """Return (index, depth): the winning plane index and the depth Z per reference pixel.

    ds is the list of plane offsets d (the planes n^T X = d). Ties go to the
    first plane in the list.
    """
    ref = images[0]
    h, w = len(ref), len(ref[0])
    Kinv = inv(cams[0][0])
    best = [[INF] * w for _ in range(h)]  # @line L1
    index = [[-1] * w for _ in range(h)]
    for j, d in enumerate(ds):  # @line L2
        S = box_sum(pixel_costs(images, cams, n, d, miss), r)  # @line L6
        for v in range(h):
            for u in range(w):  # @line L7
                if S[v][u] < best[v][u]:  # @line L8
                    best[v][u] = S[v][u]
                    index[v][u] = j
    depth = [[0.0] * w for _ in range(h)]
    for v in range(h):
        for u in range(w):
            ray = matvec(Kinv, [u, v, 1.0])
            depth[v][u] = ds[index[v][u]] / sum(a * b for a, b in zip(n, ray))  # @line L9
    return index, depth  # @line L10


def inverse_depth_planes(z_near, z_far, f, b):
    """Fronto-parallel plane depths from z_near to z_far, spaced so that the
    disparity f b / Z changes by at most one pixel from one plane to the next."""
    q_near, q_far = 1.0 / z_near, 1.0 / z_far
    step = 1.0 / (f * b)
    count = int((q_near - q_far) / step) + 1
    if (q_near - q_far) / step > count - 1:
        count += 1
    return [1.0 / (q_near - (q_near - q_far) * i / (count - 1)) for i in range(count)]


if __name__ == "__main__":
    zs = inverse_depth_planes(1.0, 10.0, 500.0, 0.1)
    print(len(zs), zs[:3], zs[-1])
test_plane_sweep_stereo.py 221 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plane-sweep-stereo/. The authors are listed in prov/8EH0Z3.jsonl.

import math
import random

from cvgeom import camera_matrix, make_K, project, random_rotation, rot_x, rot_y
from cvla import inv, matvec, mul, transpose
from plane_sweep_stereo import (
    bilinear,
    box_sum,
    inverse_depth_planes,
    pixel_costs,
    plane_homography,
    plane_sweep,
)

W, H = 24, 20
K = make_K(40.0, 40.0, 11.5, 9.5)


def texture(seed):
    rng = random.Random(seed)
    waves = []
    for _ in range(5):
        period = rng.uniform(0.25, 0.7)
        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(center, R):
    """(K, R, t) of a camera with the given center (in the reference frame) and rotation."""
    t = [-x for x in matvec(R, center)]
    return (K, R, t)


def render(cam, surfaces):
    """Ray cast an image. surfaces: list of (n, d, inside(X), texture(X))."""
    Kk, R, t = cam
    Rt = transpose(R)
    C = [-x for x in matvec(Rt, t)]
    Kinv = inv(Kk)
    img = [[0.0] * W for _ in range(H)]
    for v in range(H):
        for u in range(W):
            ray = matvec(Rt, matvec(Kinv, [u, v, 1.0]))
            best, val = math.inf, 128.0
            for n, d, inside, tex in surfaces:
                den = sum(a * b for a, b in zip(n, ray))
                if abs(den) < 1e-12:
                    continue
                s = (d - sum(a * b for a, b in zip(n, C))) / den
                X = [c + s * r for c, r in zip(C, ray)]
                if 0.0 < s < best and inside(X):
                    best, val = s, tex(X)
            img[v][u] = val
    return img


def two_plane_scene():
    back = texture(1)
    front = texture(2)
    surfaces = [
        ((0.0, 0.0, 1.0), 4.0, lambda X: True, lambda X: back(X[0], X[1])),
        ((0.0, 0.0, 1.0), 2.5, lambda X: abs(X[0]) <= 0.3 and abs(X[1]) <= 0.25,
         lambda X: front(X[0], X[1])),
    ]
    I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    cams = [camera([0.0, 0.0, 0.0], I3),
            camera([0.4, 0.0, 0.0], I3),
            camera([-0.3, 0.25, 0.0], mul(rot_y(0.02), rot_x(-0.02)))]
    images = [render(c, surfaces) for c in cams]
    return images, cams


def test_example_spacing() -> None:
    zs = inverse_depth_planes(1.0, 10.0, 500.0, 0.1)
    assert len(zs) == 46
    assert abs(zs[0] - 1.0) < 1e-12 and abs(zs[-1] - 10.0) < 1e-9
    disp = [500.0 * 0.1 / z for z in zs]
    assert all(abs((a - b) - 1.0) < 1e-9 for a, b in zip(disp, disp[1:]))


def test_example_shift() -> None:
    # A camera moved by b = 0.2 along X with fx = 50: the fronto-parallel
    # plane at depth Z shifts pixels by 10 / Z to the left.
    K1 = make_K(50.0, 50.0, 10.0, 10.0)
    I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    for Z, shift in ((2.0, 5.0), (2.5, 4.0), (5.0, 2.0), (10.0, 1.0)):
        Hm = plane_homography(K1, K1, I3, [-0.2, 0.0, 0.0], (0.0, 0.0, 1.0), Z)
        x = matvec(Hm, [7.0, 3.0, 1.0])
        assert abs(x[0] / x[2] - (7.0 - shift)) < 1e-12
        assert abs(x[1] / x[2] - 3.0) < 1e-12


def test_homography_lemma() -> None:
    rng = random.Random(5)
    for _ in range(100):
        K0 = make_K(rng.uniform(300, 900), rng.uniform(300, 900), rng.uniform(0, 640), rng.uniform(0, 480))
        Kk = make_K(rng.uniform(300, 900), rng.uniform(300, 900), rng.uniform(0, 640), rng.uniform(0, 480), rng.uniform(-2, 2))
        R = random_rotation(rng)
        t = [rng.uniform(-1, 1) for _ in range(3)]
        n = [rng.gauss(0, 1) for _ in range(3)]
        s = math.sqrt(sum(x * x for x in n))
        n = [x / s for x in n]
        d = rng.uniform(0.5, 5.0)
        Hm = plane_homography(K0, Kk, R, t, n, d)
        u, v = rng.uniform(0, 640), rng.uniform(0, 480)
        ray = matvec(inv(K0), [u, v, 1.0])
        den = sum(a * b for a, b in zip(n, ray))
        if abs(den) < 1e-3:
            continue
        X = [d / den * r for r in ray]  # the reference ray meets the plane at X
        Xk = [a + b for a, b in zip(matvec(R, X), t)]
        if abs(Xk[2]) < 1e-3:
            continue
        want = project(camera_matrix(Kk, R, t), X)
        got = matvec(Hm, [u, v, 1.0])
        scale = max(1.0, abs(want[0]), abs(want[1]))
        assert abs(got[0] / got[2] - want[0]) < 1e-8 * scale
        assert abs(got[1] / got[2] - want[1]) < 1e-8 * scale


def costs_by_back_projection(images, cams, n, d, miss):
    """Reference: back-project each pixel to the plane and project it with P_k."""
    Kinv = inv(cams[0][0])
    Ps = [camera_matrix(*c) for c in cams]
    out = [[miss] * W for _ in range(H)]
    near_border = set()
    for v in range(H):
        for u in range(W):
            ray = matvec(Kinv, [u, v, 1.0])
            X = [d / sum(a * b for a, b in zip(n, ray)) * r for r in ray]
            total, count = 0.0, 0
            for k in range(1, len(images)):
                Xh = matvec(Ps[k], X + [1.0])
                if Xh[2] <= 0:
                    continue
                x, y = Xh[0] / Xh[2], Xh[1] / Xh[2]
                if min(abs(x), abs(x - (W - 1)), abs(y), abs(y - (H - 1))) < 1e-6:
                    near_border.add((u, v))  # rounding decides inside or outside
                s = bilinear(images[k], x, y)
                if s is not None:
                    total += abs(images[0][v][u] - s)
                    count += 1
            if count:
                out[v][u] = total / count
    return out, near_border


def test_costs_match_back_projection() -> None:
    images, cams = two_plane_scene()
    for n, d in (((0.0, 0.0, 1.0), 2.5), ((0.0, 0.0, 1.0), 4.0), ((0.1, -0.2, 0.97), 3.0)):
        a = pixel_costs(images, cams, n, d, 255.0)
        b, skip = costs_by_back_projection(images, cams, n, d, 255.0)
        assert len(skip) < W * H // 4
        assert all(abs(a[v][u] - b[v][u]) < 1e-6 for v in range(H) for u in range(W) if (u, v) not in skip)


def test_box_sum() -> None:
    rng = random.Random(3)
    e = [[rng.randrange(10) for _ in range(7)] for _ in range(5)]
    s = box_sum(e, 1)
    for v in range(5):
        for u in range(7):
            want = sum(e[j][i] for j in range(max(v - 1, 0), min(v + 2, 5))
                       for i in range(max(u - 1, 0), min(u + 2, 7)))
            assert s[v][u] == want


def test_two_planes() -> None:
    images, cams = two_plane_scene()
    ds = [2.0, 2.25, 2.5, 2.8, 3.2, 3.6, 4.0, 4.5, 5.0]
    _, depth = plane_sweep(images, cams, (0.0, 0.0, 1.0), ds, 1)
    # The front square covers u in 11.5 +- 4.8 and v in 9.5 +- 4.0 in the reference.
    good = total = 0
    for v in range(H):
        for u in range(W):
            du = max(abs(u - 11.5) - 4.8, 0.0)
            dv = max(abs(v - 9.5) - 4.0, 0.0)
            inside = du == 0.0 and dv == 0.0
            edge = min(abs(abs(u - 11.5) - 4.8), abs(abs(v - 9.5) - 4.0))
            if inside and edge < 2.0:
                continue
            if not inside and max(du, dv) < 4.0:
                continue  # near the edge, or occluded in another view
            if u < 2 or u > W - 3:
                continue  # leaves the other images
            total += 1
            good += abs(depth[v][u] - (2.5 if inside else 4.0)) < 1e-9
    assert total > 100
    assert good >= 0.95 * total


def test_slanted_plane_any_direction() -> None:
    # One slanted plane, swept with its own normal: every pixel finds its d.
    n = (0.2, -0.1, 1.0)
    s = math.sqrt(sum(x * x for x in n))
    n = tuple(x / s for x in n)
    tex = texture(4)
    surfaces = [(n, 3.0, lambda X: True, lambda X: tex(X[0], X[1]))]
    I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    cams = [camera([0.0, 0.0, 0.0], I3), camera([0.4, 0.05, 0.0], I3), camera([-0.35, -0.1, 0.05], rot_y(-0.03))]
    images = [render(c, surfaces) for c in cams]
    ds = [2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6]
    index, depth = plane_sweep(images, cams, n, ds, 1)
    Kinv = inv(K)
    inner = [(u, v) for v in range(2, H - 2) for u in range(3, W - 3)]
    hits = sum(1 for u, v in inner if index[v][u] == 3)
    assert hits >= 0.95 * len(inner)
    for u, v in inner:
        if index[v][u] == 3:
            ray = matvec(Kinv, [u, v, 1.0])
            X = [depth[v][u] * r for r in ray]
            assert abs(sum(a * b for a, b in zip(n, X)) - 3.0) < 1e-9

History

Collins (1996) introduced the space sweep as a way to match features across many images at once without rectification: a plane moves through the scene and features vote for the cells where their back-projected rays meet it. Yang and Pollefeys then made the sweep dense and ran it on graphics hardware, which turned plane sweep into a real-time depth method. Gallup, Frahm, Mordohai, Yang and Pollefeys (2007) swept planes in several directions found from sparse structure from motion, to handle the slanted ground and facades of street-level video in real time.

References

  1. Robert T. Collins, A space-sweep approach to true multi-image matching, IEEE Conference on Computer Vision and Pattern Recognition 1996, pages 358 to 363, the space-sweep method (a plane swept through the scene, back-projected features counted on each plane)
  2. David Gallup, Jan-Michael Frahm, Philippos Mordohai, Qingxiong Yang and Marc Pollefeys, Real-time plane-sweeping stereo with multiple sweeping directions, IEEE Conference on Computer Vision and Pattern Recognition 2007, Section 3 (the planes, the plane-induced homography of Eq. 3, the cost of Eq. 5 with a window and a gain ratio, best-cost selection and the depth of Eq. 7, the left and right camera subsets against occlusion) and Section 4.2 (the spacing of the planes)
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (plane sweep and multi-view stereo)

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