Algorithm Search⌘K

Algorithmadvanced

Sturm-Triggs projective factorization

Also called projective factorization.

Rescale the measurement matrix by projective depths from fundamental matrices so that it has rank 4, and factor it into projective cameras and points.

Time
O(N n min(N, n)) total
Space
O(N n) extra
Where
N = the number of images; n = the number of points
Properties
deterministicnot iterativenot localnot monotoneiterative
Origin
Peter Sturm, Bill Triggs, 1996

The Sturm-Triggs factorization recovers projective cameras and points from point tracks seen in all of NN perspective images. It extends the Tomasi-Kanade factorization from affine to perspective cameras. Under perspective, the image point xipx_{ip} of point XpX_p in camera PiP_i satisfies λipxip=PiXp\lambda_{ip} x_{ip} = P_i X_p for an unknown scalar λip\lambda_{ip}, the projective depth. If the depths were known, the 3N×n3N \times n matrix with the blocks λipxip\lambda_{ip} x_{ip} would equal the product of the stacked cameras and the stacked points, so it would have rank 4. Sturm and Triggs found the depths, up to one scale per image and one per point, from the fundamental matrices and epipoles of image pairs, and then factored the rescaled matrix by the SVD. By the projective reconstruction theorem, the result is the truth up to one projective change of coordinates in space. It is a linear method that treats all images at once, and it is often the start for projective bundle adjustment and for self-calibration.

In plain words

In a photo, a point tells you only along which line of sight the true 3D point lies, not how far away it is. If you knew the distances, you could write all the image points of all photos into one table, and the table would have a very simple structure that one standard matrix tool splits into cameras and points. The trick is to find the distances first. For two photos, the geometry of the pair relates the distance of a point in one photo to its distance in the other. So you fix the distances in the first photo, pass them along from photo to photo, fill the table and split it. The result is correct only up to a general distortion of space, which you remove later with extra knowledge about the cameras.

The problem

Input. For N≥2N \ge 2 images and n≥8n \ge 8 points, the pixel uipu_{ip} of point pp in image ii, with every point seen in every image.

Model. Image ii is a projective camera PiP_i, a 3×43 \times 4 matrix, and point pp is a homogeneous 4-vector XpX_p, with λipxip=PiXp\lambda_{ip} x_{ip} = P_i X_p, where xip=(u,v,1)x_{ip} = (u, v, 1) and λip≠0\lambda_{ip} \ne 0.

Output. Cameras PiP_i and points XpX_p that reproduce the data, up to Pi↦PiHP_i \mapsto P_i H and Xp↦H−1XpX_p \mapsto H^{-1} X_p for one invertible 4×44 \times 4 matrix HH, and the scales of each PiP_i and XpX_p.

Rank. The matrix WW with the 3×13 \times 1 blocks λipxip\lambda_{ip} x_{ip} equals PXP X, where PP stacks the cameras (3N×43N \times 4) and XX holds the points as columns (4×n4 \times n). So rank⁡W≤4\operatorname{rank} W \le 4 (theorem). With wrong depths, for example all equal to 1, the rank is larger.

Depths from a pair. Write FiF_i for the fundamental matrix of the images i−1i - 1 and ii with xiTFixi−1=0x_i^{\mathsf T} F_i x_{i-1} = 0, and eie_i for the epipole in image ii, with FiTei=0F_i^{\mathsf T} e_i = 0. For suitable scales of FiF_i and eie_i, the true depths satisfy ei×(λipxip)=Fi(λi−1,pxi−1,p)e_i \times (\lambda_{ip} x_{ip}) = F_i (\lambda_{i-1,p} x_{i-1,p}) (theorem). Taking the inner product with ei×xipe_i \times x_{ip} gives the depth of image ii from the depth of image i−1i - 1.

The algorithm

  1. STURM-TRIGGS(u)
  2. 1for each image i: T_i <- the Hartley normalization of its points; x_ip <- T_i u_ip
  3. 2λ_0p <- 1 for every point p
  4. 3for i <- 1 to N - 1: F_i <- the eight-point fundamental matrix with x_i^T F_i x_(i-1) = 0; e_i <- the null vector of F_i^T
  5. 4λ_ip <- λ_(i-1)p (e_i × x_ip) · (F_i x_(i-1)p) / ||e_i × x_ip||² for every point p
  6. 5W <- the 3N × n matrix with the blocks λ_ip x_ip
  7. 6balance W: scale the columns to unit norm, then each triplet of rows to unit norm, 3 times
  8. 7U Σ V^T <- the SVD of W; P^ <- U_4 Σ_4; X <- the columns of V_4^T
  9. 8P_i <- T_i^(-1) P^_i for each image i

Line L1 is Hartley normalization, which makes the eight-point method and the SVD well conditioned. Line L3 is the normalized eight-point algorithm on consecutive images; any other spanning tree of image pairs works the same way. Line L4 is the least squares solution of λip(ei×xip)=λi−1,pFixi−1,p\lambda_{ip} (e_i \times x_{ip}) = \lambda_{i-1,p} F_i x_{i-1,p} for the one unknown λip\lambda_{ip}. The scales of FiF_i and eie_i are arbitrary, but each choice multiplies all depths of image ii and of the later images by one common factor, which only rescales the cameras. Line L6 multiplies WW by diagonal matrices on both sides, so it keeps the rank, and it keeps the SVD from being dominated by a few large entries. Line L7 keeps the 4 largest singular values, and line L8 undoes the normalization of line L1.

Example

The reference test draws 20 points in the cube [−1,1]3[-1, 1]^3 and 4 cameras with f=800f = 800 px at a distance of 4 units, each turned by up to 0.4 rad.

  • Exact data. The singular values of the balanced WW are 1.24591.2459, 1.23181.2318, 0.95750.9575, 0.11640.1164, and then 0 up to rounding. So the rank is 4, and the cameras and points reproduce every pixel to 4⋅10−134 \cdot 10^{-13} px. A second test finds the 4×44 \times 4 matrix HH that maps the recovered points to the true ones, as the theorem predicts.
  • Wrong depths. With the cameras at a distance of 2.5 units, where perspective is strong, setting all depths to 1 gives the singular values 11.5211.52, 8.948.94, 8.078.07, 0.35450.3545, 0.06830.0683. The fifth is 0.0060.006 of the first, so the matrix does not have rank 4. With the chained depths of line L4, the fifth singular value drops to 0.
  • Noise. With 4 images, 30 points and Gaussian noise of 0.5 px, the reprojection errors have a root mean square of 0.58 px and a maximum of 1.54 px.

These are benchmark results of the reference tests.

Correctness

On exact data, the chained depths of line L4 equal the true depths times one factor per image and one per point, λip=αiβpλiptrue\lambda_{ip} = \alpha_i \beta_p \lambda_{ip}^{\mathrm{true}}, if each consecutive pair has two distinct centers, the eight-point method is exact for it, and no point lies on an epipole (theorem). The matrix WW is then diag⁡(αiI3) PXdiag⁡(βp)\operatorname{diag}(\alpha_i I_3) \, P X \operatorname{diag}(\beta_p), which has rank 4, and the balancing keeps this. Any rank 4 factorization of WW differs from the true one by an invertible 4×44 \times 4 matrix, so the cameras and points of line L8 are the truth up to a projective change of coordinates and the scales of each camera and point (theorem), and they reproduce every image point exactly. With noise, the SVD minimizes the Frobenius norm of the change to the rescaled matrix, an algebraic error, not the reprojection error, and the chained depths carry errors from image to image, so the result is a good start but not an optimal estimate (heuristic). The proof file gives the details.

Proof: The chained depths are the true projective depths up to row and column scales, so the factorization gives a projective reconstruction of exact datafull

We use the notation of the page and exact arithmetic. The true cameras are PiP_i, 3×43 \times 4 of rank 3 with centers CiC_i (PiCi=0P_i C_i = 0, Ci≠0C_i \ne 0), and the true points are XpX_p. In the normalized coordinates of line L1, camera ii is P~i=TiPi\tilde P_i = T_i P_i and the image points are xip=Tiuipx_{ip} = T_i u_{ip} with last entry 1. The last row of TiT_i is (0,0,1)(0, 0, 1), so the true depths λip∗≠0\lambda_{ip}^* \ne 0 with λip∗xip=P~iXp\lambda_{ip}^* x_{ip} = \tilde P_i X_p are the same in both coordinate systems. We assume:

  • (G1) For each i≥1i \ge 1, the centers Ci−1C_{i-1} and CiC_i differ, and the conditioned eight-point system of the pair has a null space of dimension 1.
  • (G2) No image point xipx_{ip}, i≥1i \ge 1, is the epipole eie_i of line L3, so ei×xip≠0e_i \times x_{ip} \ne 0.
  • (G3) The stacked cameras PP (3N×43N \times 4) and the points XX (4×n4 \times n) both have rank 4.

Claim. (a) For each i≥1i \ge 1 there is a fundamental matrix Fi∗F_i^* and an epipole ei∗e_i^* with ei∗×(λip∗xip)=Fi∗(λi−1,p∗xi−1,p)e_i^* \times (\lambda_{ip}^* x_{ip}) = F_i^* (\lambda_{i-1,p}^* x_{i-1,p}) for all pp. (b) Line L4 gives λip=αiβpλip∗\lambda_{ip} = \alpha_i \beta_p \lambda_{ip}^* with αi≠0\alpha_i \ne 0 and βp=1/λ0p∗\beta_p = 1 / \lambda_{0p}^*. (c) The balanced matrix of line L6 has rank 4, and lines L7 and L8 return Piout=ciPiHP_i^{\mathrm{out}} = c_i P_i H and Xpout=dpH−1XpX_p^{\mathrm{out}} = d_p H^{-1} X_p for one invertible 4×44 \times 4 matrix HH and nonzero scalars cic_i, dpd_p. (d) The output reproduces every image point exactly.

Proof of (a). Fix i≥1i \ge 1 and write A=P~i−1A = \tilde P_{i-1}, B=P~iB = \tilde P_i, C=Ci−1C = C_{i-1}. Since AA has rank 3, A+=AT(AAT)−1A^+ = A^{\mathsf T} (A A^{\mathsf T})^{-1} satisfies AA+=IA A^+ = I. For any point, A(Xp−A+AXp)=0A (X_p - A^+ A X_p) = 0, so Xp−A+AXp=μpCX_p - A^+ A X_p = \mu_p C for some scalar μp\mu_p, because the null space of AA is spanned by CC. Hence Xp=A+(λi−1,p∗xi−1,p)+μpCX_p = A^+ (\lambda_{i-1,p}^* x_{i-1,p}) + \mu_p C. Apply BB and put ei∗=BCe_i^* = B C, which is nonzero because CC is not the center of BB by (G1):

λip∗xip=BXp=BA+(λi−1,p∗xi−1,p)+μpei∗.\lambda_{ip}^* x_{ip} = B X_p = B A^+ (\lambda_{i-1,p}^* x_{i-1,p}) + \mu_p e_i^*.

The cross product with ei∗e_i^* removes the last term, so ei∗×(λip∗xip)=Fi∗(λi−1,p∗xi−1,p)e_i^* \times (\lambda_{ip}^* x_{ip}) = F_i^* (\lambda_{i-1,p}^* x_{i-1,p}) with Fi∗=[ei∗]×BA+F_i^* = [e_i^*]_\times B A^+. This Fi∗F_i^* is the fundamental matrix of the pair in the convention xiTFi∗xi−1=0x_i^{\mathsf T} F_i^* x_{i-1} = 0 (Hartley and Zisserman, Chapter 9): indeed, xipT(ei∗×xip)=0x_{ip}^{\mathsf T} (e_i^* \times x_{ip}) = 0 gives xipTFi∗xi−1,p=0x_{ip}^{\mathsf T} F_i^* x_{i-1,p} = 0 for every point. It has rank 2 for distinct centers, and (Fi∗)Tei∗=(BA+)T[ei∗]×Tei∗=−(BA+)T(ei∗×ei∗)=0(F_i^*)^{\mathsf T} e_i^* = (B A^+)^{\mathsf T} [e_i^*]_\times^{\mathsf T} e_i^* = -(B A^+)^{\mathsf T} (e_i^* \times e_i^*) = 0. □\square

Proof of (b). By (G1), every exact fundamental matrix of the pair is in the null space of the eight-point system, which has dimension 1, so line L3 finds Fi=κiFi∗F_i = \kappa_i F_i^* with κi≠0\kappa_i \ne 0. The projection to rank 2 does not change it, since Fi∗F_i^* already has rank 2. The left null space of a rank 2 matrix has dimension 1, so ei=νiei∗e_i = \nu_i e_i^* with νi≠0\nu_i \ne 0. By (a), Fi∗xi−1,p=(λip∗/λi−1,p∗) ei∗×xipF_i^* x_{i-1,p} = (\lambda_{ip}^* / \lambda_{i-1,p}^*) \, e_i^* \times x_{ip}. So

(ei×xip)⋅(Fixi−1,p)∥ei×xip∥2=νiκiνi2⋅λip∗λi−1,p∗⋅(ei∗×xip)⋅(ei∗×xip)∥ei∗×xip∥2=κiνi⋅λip∗λi−1,p∗,\frac{(e_i \times x_{ip}) \cdot (F_i x_{i-1,p})}{\|e_i \times x_{ip}\|^2} = \frac{\nu_i \kappa_i}{\nu_i^2} \cdot \frac{\lambda_{ip}^*}{\lambda_{i-1,p}^*} \cdot \frac{(e_i^* \times x_{ip}) \cdot (e_i^* \times x_{ip})}{\|e_i^* \times x_{ip}\|^2} = \frac{\kappa_i}{\nu_i} \cdot \frac{\lambda_{ip}^*}{\lambda_{i-1,p}^*},

where the denominator is nonzero by (G2). Line L4 multiplies this by λi−1,p\lambda_{i-1,p}. With λ0p=1=βpλ0p∗\lambda_{0p} = 1 = \beta_p \lambda_{0p}^* and α0=1\alpha_0 = 1, induction on ii gives λip=αiβpλip∗\lambda_{ip} = \alpha_i \beta_p \lambda_{ip}^* with αi=αi−1κi/νi≠0\alpha_i = \alpha_{i-1} \kappa_i / \nu_i \ne 0. □\square

Proof of (c). By (b), the block (i,p)(i, p) of WW is αiβpλip∗xip=αiβpP~iXp\alpha_i \beta_p \lambda_{ip}^* x_{ip} = \alpha_i \beta_p \tilde P_i X_p. So W=DαP~XDβW = D_\alpha \tilde P X D_\beta, where P~\tilde P stacks the P~i\tilde P_i, DαD_\alpha repeats each αi\alpha_i three times on its diagonal and Dβ=diag⁡(βp)D_\beta = \operatorname{diag}(\beta_p). Each balancing step divides a column or a triplet of rows by its norm, which is positive because the column or the triplet is nonzero; so the balanced matrix is W′=E1WE2W' = E_1 W E_2 with positive diagonal E1E_1, constant on each triplet, and E2E_2. Then W′=P^0X^0W' = \hat P_0 \hat X_0 with P^0=E1DαP~\hat P_0 = E_1 D_\alpha \tilde P and X^0=XDβE2\hat X_0 = X D_\beta E_2. The matrix P~\tilde P has rank 4 because TiT_i is invertible and (G3) holds, and the diagonal factors are invertible, so both factors have rank 4 and W′W' has rank exactly 4. As in the proof of the Tomasi-Kanade factorization, the SVD gives W′=P^X^W' = \hat P \hat X exactly with P^=U4Σ4\hat P = U_4 \Sigma_4, the column spaces of P^\hat P and P^0\hat P_0 agree, so P^0=P^G\hat P_0 = \hat P G for an invertible 4×44 \times 4 matrix GG, and then X^=GX^0\hat X = G \hat X_0. Put H=G−1H = G^{-1}. The block of camera ii in P^=P^0H\hat P = \hat P_0 H is ϵiαiTiPiH\epsilon_i \alpha_i T_i P_i H, where ϵi\epsilon_i is the entry of E1E_1 for the triplet ii, and line L8 gives Piout=Ti−1ϵiαiTiPiH=ciPiHP_i^{\mathrm{out}} = T_i^{-1} \epsilon_i \alpha_i T_i P_i H = c_i P_i H with ci=ϵiαi≠0c_i = \epsilon_i \alpha_i \ne 0. Column pp of X^=H−1X^0\hat X = H^{-1} \hat X_0 is dpH−1Xpd_p H^{-1} X_p with dp=βp⋅(E2)pp≠0d_p = \beta_p \cdot (E_2)_{pp} \ne 0. □\square

Proof of (d). By (c), PioutXpout=cidpPiHH−1Xp=cidpλip∗uipP_i^{\mathrm{out}} X_p^{\mathrm{out}} = c_i d_p P_i H H^{-1} X_p = c_i d_p \lambda_{ip}^* u_{ip}, where uip=(u,v,1)u_{ip} = (u, v, 1) is the pixel in homogeneous form and λip∗uip=PiXp\lambda_{ip}^* u_{ip} = P_i X_p. The factor cidpλip∗c_i d_p \lambda_{ip}^* is nonzero, so the dehomogenized projection is exactly the observed pixel. ■\blacksquare

Complexity

In the real RAM model, line L1 costs O(Nn)O(N n). Line L3 runs the eight-point method N−1N - 1 times on nn points, O(n)O(n) each, and line L4 costs O(1)O(1) per point and image, so the depths cost O(Nn)O(N n). Lines L5 and L6 cost O(Nn)O(N n). The SVD of the 3N×n3N \times n matrix costs O(Nnmin⁡(N,n))O(N n \min(N, n)) and dominates. The space is O(Nn)O(N n).

Properties

  • Linear and global. No start point, and all images are treated together in the SVD.
  • Projective only. The output is fixed up to a 4×44 \times 4 projective change of coordinates. A metric result needs self-calibration or other knowledge, as in stratified reconstruction.
  • Signs of the depths. Nothing forces the recovered depths to be positive. A projective reconstruction with all points in front of all cameras needs an extra step.
  • Complete data. Every point must be seen in every image.
  • Chain errors. Depths found along a chain of pairs collect the errors of all pairs on the way.

Variants and improvements

  • Iterative depths. Alternate between the factorization and a new estimate of the depths from the projected points, to fit the rank 4 model better. Oliensis and Hartley (2007) studied the convergence of such iterations and showed that the simplest form need not converge to a correct solution.
  • Other depth sources. The depths can also come from other matching tensors, such as the trifocal tensor, as discussed by Triggs (1996).
  • Missing data. Fit the rank 4 model only to the observed entries, by alternation or by matrix completion methods, and re-estimate the depths at the same time.
  • Affine special case. For affine cameras all depths can be set to 1. Then the matrix with a row of ones per image has rank 4, and the method is an affine factorization without the centering step of Tomasi and Kanade.

When to use it

Use it to start a projective or, after self-calibration, a metric reconstruction from a short sequence where all points are tracked in all images, for example a turntable or a short video. It is also a useful baseline for projective methods. For large photo collections with missing data and outliers, use incremental structure from motion or global structure from motion. For weak perspective, the Tomasi-Kanade factorization is simpler and more stable.

Pitfalls

  • No normalization. Without the normalization of line L1, pixel coordinates near 1000 dominate the entry 1 of each homogeneous point, and both the eight-point method and the SVD lose accuracy.
  • Points near an epipole. Then ei×xipe_i \times x_{ip} is close to 0, and the depth of line L4 is unstable. The reference code raises an error for an exact hit.
  • Small baselines. A pair with nearly the same center gives a poor fundamental matrix and poor depths for all later images in the chain.
  • Planar scenes. Coplanar points make the fundamental matrix undetermined, and the method fails.
  • Reading the result as metric. The cameras are projective. Distances and angles in the recovered space have no meaning until the projective ambiguity is removed.

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()
sturm_triggs_factorization.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sturm-triggs-factorization/. The authors are listed in prov/JQNS8Q.jsonl.

"""Sturm-Triggs factorization: projective structure and motion from tracks.

There are N >= 2 perspective images and n points, and every point is seen
in every image. obs[i][p] is the pixel (u, v) of point p in image i. The
method finds cameras P_i (3 x 4) and homogeneous points X_p (4-vectors)
with P_i X_p proportional to (u, v, 1), up to one projective change of
coordinates of space.

The points of each image are first normalized by a similarity T_i. The
projective depths lambda_ip are then chained along the images with the
fundamental matrices F_i of the image pairs (i - 1, i), which are
computed by the normalized 8-point method in the convention
x_i^T F_i x_(i-1) = 0. The rescaled measurement matrix W, with block
(i, p) equal to lambda_ip x_ip, has rank at most 4, and a truncated SVD
splits it into cameras and points.
"""

import math
from typing import Dict, List, Sequence

from cvla import cross, dot, inv, mul, nullvec, svd, transpose

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


def normalizing_transform(pts: Sequence[Sequence[float]]) -> Matrix:
    """The similarity T that moves the centroid to the origin and makes the
    mean distance to the origin sqrt(2) (Hartley normalization)."""
    n = len(pts)
    cx = sum(p[0] for p in pts) / n
    cy = sum(p[1] for p in pts) / n
    d = sum(math.hypot(p[0] - cx, p[1] - cy) for p in pts) / n
    s = math.sqrt(2.0) / d
    return [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]]


def apply(t: Matrix, p: Sequence[float]) -> Vector:
    """T (u, v, 1), a homogeneous image point with last entry 1."""
    return [t[0][0] * p[0] + t[0][1] * p[1] + t[0][2],
            t[1][0] * p[0] + t[1][1] * p[1] + t[1][2], 1.0]


def eight_point(xa: Sequence[Vector], xb: Sequence[Vector]) -> Matrix:
    """F of rank 2 with xb^T F xa = 0 for the given homogeneous points (at
    least 8 pairs, already normalized), by the linear 8-point method."""
    a = [[q[0] * p[0], q[0] * p[1], q[0] * p[2],
          q[1] * p[0], q[1] * p[1], q[1] * p[2],
          q[2] * p[0], q[2] * p[1], q[2] * p[2]] for p, q in zip(xa, xb)]
    f = nullvec(a)
    fm = [f[0:3], f[3:6], f[6:9]]
    u, s, v = svd(fm)
    return mul(mul(u, [[s[0], 0.0, 0.0], [0.0, s[1], 0.0], [0.0, 0.0, 0.0]]), transpose(v))


def chained_depths(xn: Sequence[Sequence[Vector]]) -> List[Vector]:
    """The projective depths lambda_ip, with lambda_0p = 1 and
    lambda_ip = lambda_(i-1)p (e_i x x_ip) . (F_i x_(i-1)p) / ||e_i x x_ip||^2."""
    big_n, n = len(xn), len(xn[0])
    lam = [[1.0] * n]  # @line L2
    for i in range(1, big_n):
        f = eight_point(xn[i - 1], xn[i])  # @line L3
        e = nullvec(transpose(f))
        row = []
        for p in range(n):  # @line L4
            ex = cross(e, xn[i][p])
            fx = [dot(r, xn[i - 1][p]) for r in f]
            den = dot(ex, ex)
            if den <= 1e-24 * dot(e, e) * dot(xn[i][p], xn[i][p]):
                raise ValueError("sturm_triggs_factorization: a point lies on the epipole")
            row.append(lam[i - 1][p] * dot(ex, fx) / den)
        lam.append(row)
    return lam


def balance(w: Matrix, passes: int = 3) -> Matrix:
    """Scale the columns and then the row triplets of W to unit norm, a few
    times. This multiplies W by diagonal matrices on both sides, so it does
    not change the rank."""
    w = [list(r) for r in w]
    big_n, n = len(w) // 3, len(w[0])
    for _ in range(passes):
        for p in range(n):
            c = math.sqrt(sum(w[r][p] ** 2 for r in range(3 * big_n)))
            for r in range(3 * big_n):
                w[r][p] /= c
        for i in range(big_n):
            c = math.sqrt(sum(x * x for r in w[3 * i:3 * i + 3] for x in r))
            for r in range(3 * i, 3 * i + 3):
                w[r] = [x / c for x in w[r]]
    return w


def sturm_triggs_factorization(obs: Sequence[Sequence[Sequence[float]]]) -> Dict[str, object]:
    """Projective reconstruction from complete tracks in N >= 2 images.

    Returns a dict with "P" (N cameras, 3 x 4, in pixel coordinates), "X"
    (n homogeneous points), "S" (the singular values of the balanced W) and
    "depths" (the chained lambda_ip, before balancing). Raises ValueError
    if there are fewer than 8 points or a point lies on an epipole."""
    big_n, n = len(obs), len(obs[0])
    if big_n < 2 or n < 8:
        raise ValueError("sturm_triggs_factorization: need 2 images and 8 points")
    ts = [normalizing_transform(frame) for frame in obs]  # @line L1
    xn = [[apply(t, p) for p in frame] for t, frame in zip(ts, obs)]
    lam = chained_depths(xn)
    w = []  # @line L5
    for i in range(big_n):
        for k in range(3):
            w.append([lam[i][p] * xn[i][p][k] for p in range(n)])
    w = balance(w)  # @line L6
    u, s, v = svd(w)  # @line L7
    cams_hat = [[u[r][k] * s[k] for k in range(4)] for r in range(3 * big_n)]
    pts = [[v[p][k] for k in range(4)] for p in range(n)]
    cams = [mul(inv(ts[i]), cams_hat[3 * i:3 * i + 3]) for i in range(big_n)]  # @line L8
    return {"P": cams, "X": pts, "S": s, "depths": lam}


def reprojection_errors(cams: Sequence[Matrix], pts: Sequence[Vector],
                        obs: Sequence[Sequence[Sequence[float]]]) -> List[float]:
    """The pixel distance between P_i X_p and the observed point, for all i and p."""
    out = []
    for cam, frame in zip(cams, obs):
        for x, o in zip(pts, frame):
            y = [dot(r, x) for r in cam]
            out.append(math.hypot(y[0] / y[2] - o[0], y[1] / y[2] - o[1]))
    return out


def rank4_residual(w: Matrix) -> float:
    """The fifth singular value of W divided by the first."""
    s = svd(w)[1]
    return s[4] / s[0] if len(s) > 4 else 0.0
test_sturm_triggs_factorization.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sturm-triggs-factorization/. The authors are listed in prov/JQNS8Q.jsonl.

import math
import random

import pytest

from cvgeom import add_noise, random_scene
from cvla import matvec, svd
from sturm_triggs_factorization import (apply, chained_depths, normalizing_transform,
                                        reprojection_errors, sturm_triggs_factorization)


def make_scene(seed, n_cams=4, n_pts=20, max_angle=0.4, distance=4.0):
    rng = random.Random(seed)
    sc = random_scene(rng, n=n_pts, n_cams=n_cams, max_angle=max_angle, distance=distance)
    return rng, sc


def test_exact_data_reprojects_exactly():
    for seed in range(3):
        _, sc = make_scene(seed)
        res = sturm_triggs_factorization(sc["x"])
        assert res["S"][4] < 1e-9 * res["S"][0]
        assert max(reprojection_errors(res["P"], res["X"], sc["x"])) < 1e-6


def test_chained_depths_are_true_depths_up_to_row_and_column_scales():
    _, sc = make_scene(3, n_cams=5)
    ts = [normalizing_transform(f) for f in sc["x"]]
    xn = [[apply(t, p) for p in f] for t, f in zip(ts, sc["x"])]
    lam = chained_depths(xn)
    true = [[matvec(r, x)[2] + t[2] for x in sc["X"]] for r, t in zip(sc["R"], sc["t"])]
    ratio = [[a / b for a, b in zip(ra, rb)] for ra, rb in zip(lam, true)]
    # ratio[i][p] = a_i b_p, so the ratio matrix has rank 1
    for i in range(5):
        for p in range(len(sc["X"])):
            assert abs(ratio[i][p] * ratio[0][0] - ratio[i][0] * ratio[0][p]) < 1e-8 * abs(ratio[0][0] * ratio[i][p])


def test_result_is_projectively_equivalent_to_the_truth():
    _, sc = make_scene(4, n_cams=3, n_pts=15)
    res = sturm_triggs_factorization(sc["x"])
    # find H with X_true ~ H X_rec by the DLT: for each pair of coordinates
    # (i, j), X_true[i] (H X_rec)[j] - X_true[j] (H X_rec)[i] = 0
    xr = res["X"]
    xt = [x + [1.0] for x in sc["X"]]
    rows = []
    for a, b in zip(xr, xt):
        for i in range(4):
            for j in range(i + 1, 4):
                r = [0.0] * 16
                for k in range(4):
                    r[4 * j + k] += b[i] * a[k]
                    r[4 * i + k] -= b[j] * a[k]
                rows.append(r)
    _, s, v = svd(rows)
    assert s[15] < 1e-9 * s[0]
    h = [[v[4 * i + k][15] for k in range(4)] for i in range(4)]
    for a, b in zip(xr, xt):
        y = matvec(h, a)
        y = [c / y[3] for c in y]
        assert max(abs(c - d) for c, d in zip(y, b)) < 1e-6


def test_noise_gives_small_reprojection_errors():
    rng, sc = make_scene(5, n_cams=4, n_pts=30)
    obs = [add_noise(rng, f, 0.5) for f in sc["x"]]
    res = sturm_triggs_factorization(obs)
    err = reprojection_errors(res["P"], res["X"], obs)
    rms = math.sqrt(sum(e * e for e in err) / len(err))
    assert rms < 2.0


def test_two_images_are_enough():
    _, sc = make_scene(6, n_cams=2, n_pts=12)
    res = sturm_triggs_factorization(sc["x"])
    assert max(reprojection_errors(res["P"], res["X"], sc["x"])) < 1e-6


def test_too_few_points_are_rejected():
    _, sc = make_scene(7, n_cams=3, n_pts=7)
    with pytest.raises(ValueError):
        sturm_triggs_factorization(sc["x"])


def test_unit_depths_break_the_rank():
    # with all depths set to 1 (the affine guess), W of perspective data has rank above 4
    _, sc = make_scene(8, n_cams=4, n_pts=20, distance=2.5)
    ts = [normalizing_transform(f) for f in sc["x"]]
    w = []
    for t, f in zip(ts, sc["x"]):
        pts = [apply(t, p) for p in f]
        for k in range(3):
            w.append([p[k] for p in pts])
    s = svd(w)[1]
    assert s[4] > 1e-4 * s[0]
    res = sturm_triggs_factorization(sc["x"])
    assert res["S"][4] < 1e-9 * res["S"][0]

History

Tomasi and Kanade (1992) factored the measurement matrix for orthographic cameras. Sturm and Triggs (1996) showed that the same idea works for perspective cameras once each image point is multiplied by its projective depth, and that these depths follow from the fundamental matrices and epipoles of image pairs. Triggs (1996) gave the theory in terms of matching tensors. Later work studied iterative depth estimation, missing data and the conditions for convergence, among them the analysis of Oliensis and Hartley (2007).

References

  1. Peter Sturm and Bill Triggs, A factorization based algorithm for multi-image projective structure and motion, Computer Vision ECCV '96, Lecture Notes in Computer Science 1065, Springer, 1996, 709-720, the whole paper (the recovery of the projective depths from fundamental matrices and epipoles, the balancing and the factorization)
  2. Bill Triggs, Factorization methods for projective structure and motion, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 1996), 845-851, the projective factorization and the depth recovery from matching tensors
  3. John Oliensis and Richard Hartley, Iterative extensions of the Sturm/Triggs algorithm: convergence and nonconvergence, IEEE Transactions on Pattern Analysis and Machine Intelligence 29(12), 2007, 2217-2233, the analysis of the iterations that alternate between the depths and the factorization
  4. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Chapter 18, N-view computational methods (projective factorization) and Chapter 10 (the projective reconstruction theorem)

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.total
  • 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