Algorithm Search⌘K

Algorithmcore

Tomasi-Kanade factorization

Also called factorization method, affine factorization.

Recover affine cameras and points from tracks in all views by a rank-3 SVD of the centered measurement matrix, followed by a metric upgrade.

Time
O(N n min(N, n)) total
Space
O(N n) extra
Where
N = the number of frames; n = the number of points
Properties
deterministicnot iterativenot localnot monotoneiterative
Origin
Carlo Tomasi, Takeo Kanade, 1992

The Tomasi-Kanade factorization recovers the shape of a rigid object and the motion of an orthographic camera from point tracks, when every point is seen in every frame. It is the classic solution of the structure from motion problem for the affine camera. Put the image coordinates of nn points in NN frames into one 2N×n2N \times n measurement matrix and subtract the mean of each row. The rank theorem says that the result has rank at most 3, because it is the product of a 2N×32N \times 3 motion matrix and a 3×n3 \times n shape matrix. So one singular value decomposition that keeps the 3 largest singular values gives the motion and the shape, up to an invertible 3×33 \times 3 matrix. A second, metric step fixes that matrix by asking that the camera rows be orthonormal, which leaves only a rotation of the world and a mirror reflection in depth. The method uses all data at once, has no start point and no iteration, and with noise its truncated SVD gives the best rank 3 fit in the Frobenius norm.

In plain words

A camera far away from an object sees it almost without perspective: the image is a flat shadow of the object, turned and moved. Follow some points of the object through a video and write all their image positions into one big table, one pair of rows per frame. Remove the average position in each row. Every number in the table now comes from only three hidden numbers per point and three per row, so the table has a very simple structure. A standard matrix tool, the SVD, splits it into a camera part and a shape part. One last correction makes the camera parts look like real turns. The result is the 3D shape, but you cannot tell it from its mirror image.

The problem

Input. For N≥3N \ge 3 frames and n≥4n \ge 4 points, the image point (ufp,vfp)(u_{fp}, v_{fp}) of point pp in frame ff, with every point seen in every frame.

Camera model. Frame ff is an orthographic camera without a scale factor: the world point XpX_p maps to ufp=if⋅Xp+afu_{fp} = i_f \cdot X_p + a_f and vfp=jf⋅Xp+bfv_{fp} = j_f \cdot X_p + b_f, where ifi_f and jfj_f are the first two rows of a rotation and (af,bf)(a_f, b_f) is an image translation.

Output. The rows if,jfi_f, j_f of each frame, the translations (af,bf)(a_f, b_f) and the points XpX_p, with the origin at the centroid of the points. The answer is unique up to one orthogonal matrix applied to the world, a rotation or a rotation with a mirror.

Rank theorem. Let WW be the 2N×n2N \times n matrix with row 2f2f holding the ufpu_{fp} and row 2f+12f + 1 the vfpv_{fp}. Let tt hold the row means. Then W~=W−t1T=MS\tilde W = W - t \mathbf 1^{\mathsf T} = M S, where MM is 2N×32N \times 3 with the rows ifi_f and jfj_f, and SS is 3×n3 \times n with the centered points. So rank⁡W~≤3\operatorname{rank} \tilde W \le 3 (theorem).

The algorithm

  1. TOMASI-KANADE(W)
  2. 1t <- the row means of W; W~ <- W - t 1^T
  3. 2U Σ V^T <- the SVD of W~
  4. 3M^ <- U_3 Σ_3^(1/2); X^ <- Σ_3^(1/2) V_3^T, from the 3 largest singular values
  5. 4for each frame f with rows a, b of M^: the equations a^T L a = 1, b^T L b = 1, a^T L b = 0, linear in the 6 entries of a symmetric L
  6. 5L <- the least squares solution of the 3N equations of line L4
  7. 6Q <- the Cholesky factor of L, so that L = Q Q^T
  8. 7M <- M^ Q; X <- Q^(-1) X^
  9. 8rotate the world so that the rows of frame 0 are e_1 and e_2
  10. 9return M, t, X

Line L3 splits the singular values evenly between the two factors; any split gives the same result after the metric step. Line L4 states that the rows of M=M^QM = \hat M Q have unit length and that the two rows of one frame are orthogonal, since mTm=m^TQQTm^m^{\mathsf T} m = \hat m^{\mathsf T} Q Q^{\mathsf T} \hat m. The unknown is L=QQTL = Q Q^{\mathsf T}, not QQ, because the constraints are linear in LL. Line L6 uses the Cholesky decomposition and fails when the least squares LL is not positive definite, which happens when the data are far from orthographic; the reference code raises an error then. Line L8 only fixes the gauge.

Example

The reference test draws 12 points in the cube [−1,1]3[-1, 1]^3 and 5 orthographic frames, each turned by up to 0.6 rad about a random axis from one base rotation and moved by up to 5 units in the image.

  • Exact data. The singular values of W~\tilde W are 4.3928484.392848, 3.1902073.190207, 1.0316951.031695, and then 0 up to rounding. So the rank is 3, as the theorem says. The factorization reproduces WW to 10−910^{-9}, and all 66 distances between the recovered points match the true ones to 10−810^{-8}.
  • Noisy data. With 8 frames, 20 points and Gaussian noise of 0.0020.002 units on each coordinate, the singular values are 8.347158.34715, 5.93955.9395, 1.21511.2151, 0.012630.01263, 0.011810.01181 and smaller. The gap after the third value shows the rank 3 structure. The largest error over the 190 distances between points is 0.00900.0090, and the root mean square residual of the fit is 0.00160.0016, a little below the noise, because the fit absorbs part of it.
  • The mirror. Changing the sign of the third column of MM and of the depth of every point gives the same images and orthonormal rows, so the data cannot tell the shape from its mirror image.
  • Two frames. With 2 frames, the 6 equations of line L4 have rank 5 in the test, so a one-parameter family of LL fits, and the method needs at least 3 frames.

These are benchmark results of the reference tests.

Correctness

On exact data, W~=MS\tilde W = M S has rank 3 when the true motion rows span R3\mathbb{R}^3 and the points are not coplanar (theorem). Then lines L2 and L3 give an exact factorization W~=M^X^\tilde W = \hat M \hat X, and every rank 3 factorization differs from the true one by an invertible matrix AA: M=M^AM = \hat M A and S=A−1X^S = A^{-1} \hat X (theorem). The true L∗=AATL^* = A A^{\mathsf T} satisfies all equations of line L4. If these equations have rank 6, line L5 returns L∗L^*, and the Cholesky factor QQ equals AGA G for an orthogonal GG, so the output is the truth up to GG (theorem). The rank 6 condition is generic for 3 or more frames; with 2 frames it fails, in line with Ullman's result that 3 orthographic views of 4 points are needed. With noise, the truncated SVD gives the best rank 3 approximation of W~\tilde W in the Frobenius norm, which is the maximum likelihood estimate of the affine structure for independent Gaussian noise of equal variance and complete data (theorem). The metric step is a linear least squares fit, not a maximum likelihood estimate (heuristic). The proof file gives the details.

Proof: The centered measurement matrix has rank 3, and the factorization with the metric step recovers motion and shape up to one orthogonal matrixfull

We use the notation of the page. Frame ff maps XpX_p to ufp=if⋅Xp+afu_{fp} = i_f \cdot X_p + a_f and vfp=jf⋅Xp+bfv_{fp} = j_f \cdot X_p + b_f, where if,jfi_f, j_f are orthonormal. MM is the 2N×32N \times 3 matrix with the rows ifTi_f^{\mathsf T} and jfTj_f^{\mathsf T}, Xˉ=1n∑pXp\bar X = \frac{1}{n} \sum_p X_p, and SS is the 3×n3 \times n matrix with the columns Xp−XˉX_p - \bar X.

Claim. (a) W~=W−t1T=MS\tilde W = W - t \mathbf 1^{\mathsf T} = M S, so rank⁡W~≤3\operatorname{rank} \tilde W \le 3. (b) If MM and SS have rank 3, then lines L2 and L3 give W~=M^X^\tilde W = \hat M \hat X, and there is an invertible 3×33 \times 3 matrix AA with M=M^AM = \hat M A and S=A−1X^S = A^{-1} \hat X. (c) L∗=AATL^* = A A^{\mathsf T} satisfies every equation of line L4, and if the 3N×63N \times 6 system of line L4 has rank 6, lines L5 to L8 return MGM G and GTSG^{\mathsf T} S for one orthogonal matrix GG. (d) The output reproduces WW exactly and preserves all distances between the points. (e) For any data, tt and the rank 3 factorization of lines L1 to L3 minimize ∥W−M′X′−t′1T∥F\|W - M' X' - t' \mathbf 1^{\mathsf T}\|_F over all 2N×32N \times 3 matrices M′M', 3×n3 \times n matrices X′X' and vectors t′t'.

Proof of (a). Write cfc_f for the translation entry of row ff of WW, that is afa_f or bfb_f, and mfm_f for the row of MM. Then Wfp=mf⋅Xp+cfW_{fp} = m_f \cdot X_p + c_f, so the row mean is tf=mf⋅Xˉ+cft_f = m_f \cdot \bar X + c_f, and W~fp=mf⋅(Xp−Xˉ)=(MS)fp\tilde W_{fp} = m_f \cdot (X_p - \bar X) = (M S)_{fp}. The product of a matrix with 3 columns and a matrix with 3 rows has rank at most 3. □\square

Proof of (b). If MM and SS have rank 3, then W~=MS\tilde W = M S has rank exactly 3, because MM has full column rank and SS has full row rank. So the SVD has exactly 3 nonzero singular values, and W~=U3Σ3V3T=M^X^\tilde W = U_3 \Sigma_3 V_3^{\mathsf T} = \hat M \hat X. The column space of W~\tilde W is the column space of MM, and also that of M^=U3Σ31/2\hat M = U_3 \Sigma_3^{1/2}. Both have dimension 3, so each column of MM is a combination of the columns of M^\hat M: M=M^AM = \hat M A for some 3×33 \times 3 matrix AA, and AA is invertible because MM has rank 3. Then M^AS=M^X^\hat M A S = \hat M \hat X, and M^\hat M has full column rank, so AS=X^A S = \hat X, that is S=A−1X^S = A^{-1} \hat X. □\square

Proof of (c). Let a^,b^\hat a, \hat b be the rows of frame ff in M^\hat M. The true rows are ifT=a^TAi_f^{\mathsf T} = \hat a^{\mathsf T} A and jfT=b^TAj_f^{\mathsf T} = \hat b^{\mathsf T} A. So a^TL∗a^=∥if∥2=1\hat a^{\mathsf T} L^* \hat a = \|i_f\|^2 = 1, b^TL∗b^=∥jf∥2=1\hat b^{\mathsf T} L^* \hat b = \|j_f\|^2 = 1 and a^TL∗b^=if⋅jf=0\hat a^{\mathsf T} L^* \hat b = i_f \cdot j_f = 0. Each equation is linear in the 6 entries of the symmetric matrix LL. So L∗L^* solves the system exactly. If the system matrix G6G_6 has rank 6, its least squares solution is unique and equals the exact solution, so line L5 returns L=L∗L = L^*. The matrix L∗=AATL^* = A A^{\mathsf T} is positive definite because AA is invertible, so line L6 succeeds and gives QQ with QQT=AATQ Q^{\mathsf T} = A A^{\mathsf T}. Put G=A−1QG = A^{-1} Q. Then GGT=A−1QQTA−T=A−1AATA−T=IG G^{\mathsf T} = A^{-1} Q Q^{\mathsf T} A^{-\mathsf T} = A^{-1} A A^{\mathsf T} A^{-\mathsf T} = I, so GG is orthogonal. Line L7 gives M^Q=M^AG=MG\hat M Q = \hat M A G = M G and Q−1X^=G−1A−1X^=GTSQ^{-1} \hat X = G^{-1} A^{-1} \hat X = G^{\mathsf T} S. Line L8 multiplies the motion on the right by R0TR_0^{\mathsf T} and the shape on the left by R0R_0 for a rotation R0R_0, which replaces GG by the orthogonal matrix GR0TG R_0^{\mathsf T}. □\square

Proof of (d). The output gives MG⋅GTS+t1T=MS+t1T=WM G \cdot G^{\mathsf T} S + t \mathbf 1^{\mathsf T} = M S + t \mathbf 1^{\mathsf T} = W by (a). The output points are GT(Xp−Xˉ)G^{\mathsf T} (X_p - \bar X), and an orthogonal map preserves distances, so ∥GT(Xp−Xq)∥=∥Xp−Xq∥\|G^{\mathsf T}(X_p - X_q)\| = \|X_p - X_q\|. Each output frame has the rows GTifG^{\mathsf T} i_f and GTjfG^{\mathsf T} j_f, which are orthonormal. If det⁡G=−1\det G = -1, the output is the mirror image of the truth, and the data cannot rule it out, because MGM G and GTSG^{\mathsf T} S explain WW exactly. □\square

Proof of (e). For fixed M′M' and X′X', the cost ∑f∑p(Wfp−(M′X′)fp−tf′)2\sum_f \sum_p (W_{fp} - (M' X')_{fp} - t'_f)^2 separates over the rows, and in row ff it is minimized by tf′t'_f equal to the mean of Wfp−(M′X′)fpW_{fp} - (M' X')_{fp} over pp. Replacing X′X' by X′−xˉ′1TX' - \bar x' \mathbf 1^{\mathsf T}, where xˉ′\bar x' is the mean column of X′X', changes t′t' but not the cost, so we may take X′X' with zero row means, and then the best t′t' is tt, the row means of WW. What remains is min⁡∥W~−M′X′∥F\min \|\tilde W - M' X'\|_F over all matrices of rank at most 3. By the Eckart-Young theorem, the minimum is reached by the truncated SVD U3Σ3V3T=M^X^U_3 \Sigma_3 V_3^{\mathsf T} = \hat M \hat X. The rows of X^\hat X have zero means, because W~1=0\tilde W \mathbf 1 = 0 gives V3T1=Σ3−1U3TW~1=0V_3^{\mathsf T} \mathbf 1 = \Sigma_3^{-1} U_3^{\mathsf T} \tilde W \mathbf 1 = 0 when Σ3\Sigma_3 is invertible. So the triple (M^,X^,t)(\hat M, \hat X, t) is a minimizer. With independent Gaussian noise of equal variance on all entries, this least squares minimizer is the maximum likelihood estimate of the affine motion and shape. ■\blacksquare

Complexity

In the real RAM model, line L1 costs O(Nn)O(N n). The SVD of the 2N×n2N \times n matrix costs O(Nnmin⁡(N,n))O(N n \min(N, n)), and it dominates. Only the 3 leading singular vectors are needed, so an iterative method such as power iteration or a Lanczos method can find them in O(Nn)O(N n) per iteration. Lines L4 and L5 build and solve a 3N×63N \times 6 least squares problem in O(N)O(N). Line L7 costs O(N+n)O(N + n). The space is O(Nn)O(N n) for WW.

Properties

  • Closed form. No start point and no iteration, apart from the SVD itself.
  • Global. It uses all frames and points at once, so no frame is preferred.
  • Optimal affine fit. With complete data and equal Gaussian noise, the affine part is the maximum likelihood estimate (theorem).
  • Ambiguities. A world rotation and a depth mirror remain; with a perspective camera, the mirror is the Necker reversal that perspective cues can resolve.
  • Complete data only. The plain method needs every point in every frame.

Variants and improvements

  • Paraperspective and weak perspective. Poelman and Kanade (1997) used the same factorization with metric constraints for the paraperspective camera, which models the change of scale and position with distance.
  • Missing data. Tomasi and Kanade (1992) also described how to fill in entries that are missing because of occlusion. Later methods fit the rank 3 model by alternating least squares, Wiberg's method or matrix completion.
  • Outliers. Robust PCA and L1L_1 factorizations handle wrong tracks.
  • Projective cameras. The Sturm-Triggs factorization scales each image point by its projective depth so that a rank 4 factorization works for perspective cameras.
  • Multiple bodies and nonrigid shapes. Costeira and Kanade separated independent motions by the structure of the shape interaction matrix, and nonrigid factorization models the shape as a combination of a few basis shapes.
  • Sequential factorization. Updates of the factorization frame by frame avoid recomputing the full SVD.

When to use it

Use it when the camera is far from the object compared with the depth of the object, for example for a telephoto lens or a small object, and when tracks are complete, as in a short video from a KLT tracker. It is also a good start for bundle adjustment with a perspective model. For wide angle views of a deep scene, use a perspective method such as the Sturm-Triggs factorization or incremental structure from motion.

Pitfalls

  • Perspective effects. Strong perspective makes the fourth singular value large and can make LL indefinite, so the Cholesky step fails.
  • Planar scenes. Coplanar points give rank 2, and the third column of the motion is not fixed.
  • Too little rotation. If all frames have almost the same rotation, the motion rows span less than R3\mathbb{R}^3 in practice, and the depth is poorly determined.
  • Centering with missing data. The row means must be over the same points in every frame, or the rank theorem fails.
  • The mirror. The output can be the mirror shape. Use another cue, such as a perspective effect or occlusions, to choose.

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()
tomasi_kanade_factorization.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tomasi-kanade-factorization/. The authors are listed in prov/0876R2.jsonl.

"""Tomasi-Kanade factorization: shape and motion from orthographic tracks.

There are N frames and n points, and every point is seen in every frame.
Frame f is an orthographic camera: the point X maps to the image point
(i_f . X + a_f, j_f . X + b_f), where i_f and j_f are the first two rows
of a rotation. obs[f][p] is the image point (u, v) of point p in frame f.

The measurement matrix W has 2N rows (row 2f holds the u values of frame
f and row 2f + 1 the v values) and n columns. After the row means are
removed, W has rank at most 3, and a truncated SVD gives W ~ M^ X^. The
metric step finds a symmetric L = Q Q^T such that the rows of M^ Q are
unit vectors and the two rows of each frame are orthogonal. The result
is unique up to a rotation of the world (fixed here so that frame 0 has
the rows e1 and e2) and a mirror reflection in depth.
"""

import math
from typing import Dict, List, Sequence

from cvla import cholesky, cross, dot, inv, mul, solve, svd, transpose

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


def measurement_matrix(obs: Sequence[Sequence[Sequence[float]]]) -> Matrix:
    """The 2N x n matrix W: rows 2f and 2f + 1 are the u and v values of frame f."""
    w = []
    for frame in obs:
        w.append([float(x[0]) for x in frame])
        w.append([float(x[1]) for x in frame])
    return w


def metric_rows(m_hat: Matrix) -> Matrix:
    """One row per constraint on L = [[l0, l1, l2], [l1, l3, l4], [l2, l4, l5]].

    For vectors a and b, a^T L b is linear in (l0, ..., l5). Each frame
    gives a^T L a = 1, b^T L b = 1 and a^T L b = 0, where a and b are its
    two rows of M^."""

    def row(a: Sequence[float], b: Sequence[float]) -> Vector:
        return [a[0] * b[0], a[0] * b[1] + a[1] * b[0], a[0] * b[2] + a[2] * b[0],
                a[1] * b[1], a[1] * b[2] + a[2] * b[1], a[2] * b[2]]

    rows = []
    for f in range(len(m_hat) // 2):
        a, b = m_hat[2 * f], m_hat[2 * f + 1]
        rows.extend([row(a, a), row(b, b), row(a, b)])
    return rows


def _unpack(l: Sequence[float]) -> Matrix:
    return [[l[0], l[1], l[2]], [l[1], l[3], l[4]], [l[2], l[4], l[5]]]


def tomasi_kanade_factorization(obs: Sequence[Sequence[Sequence[float]]]) -> Dict[str, object]:
    """Recover motion and shape from complete orthographic tracks.

    Returns a dict with "M" (2N x 3, the camera rows), "t" (2N row means,
    the image translations), "X" (n points as 3-vectors), "S" (all singular
    values of the centered W) and "L" (the metric matrix). Raises ValueError
    if there are fewer than 3 frames or 4 points, or if the least squares
    L is not positive definite (the data is not orthographic enough)."""
    w = measurement_matrix(obs)
    two_n, n = len(w), len(w[0])
    if two_n < 6 or n < 4:
        raise ValueError("tomasi_kanade_factorization: need 3 frames and 4 points")
    t = [sum(r) / n for r in w]  # @line L1
    wc = [[x - tr for x in r] for r, tr in zip(w, t)]
    u, s, v = svd(wc)  # @line L2
    r3 = [math.sqrt(s[k]) for k in range(3)]  # @line L3
    m_hat = [[u[i][k] * r3[k] for k in range(3)] for i in range(two_n)]
    x_hat = [[r3[k] * v[j][k] for j in range(n)] for k in range(3)]
    g = metric_rows(m_hat)  # @line L4
    h = [1.0 if c % 3 != 2 else 0.0 for c in range(len(g))]
    gt = transpose(g)
    l_vec = solve(mul(gt, g), [dot(col, h) for col in gt])  # @line L5
    l_mat = _unpack(l_vec)
    try:
        q = cholesky(l_mat)  # @line L6
    except ValueError:
        raise ValueError("tomasi_kanade_factorization: the metric matrix is not positive definite")
    m = mul(m_hat, q)  # @line L7
    x = mul(inv(q), x_hat)
    r0 = frame_rotation(m[0], m[1])  # @line L8
    m = mul(m, transpose(r0))
    x = mul(r0, x)
    pts = [[x[k][j] for k in range(3)] for j in range(n)]
    return {"M": m, "t": t, "X": pts, "S": s, "L": l_mat}  # @line L9


def frame_rotation(a: Sequence[float], b: Sequence[float]) -> Matrix:
    """The rotation with rows r1, r2 and r1 x r2, where r1 and r2 come from
    a and b by Gram-Schmidt. It maps a to a multiple of e1 and b into the
    plane of e1 and e2."""
    na = math.sqrt(dot(a, a))
    r1 = [c / na for c in a]
    d = dot(r1, b)
    b2 = [bc - d * c for bc, c in zip(b, r1)]
    nb = math.sqrt(dot(b2, b2))
    r2 = [c / nb for c in b2]
    return [r1, r2, cross(r1, r2)]


def reproject(result: Dict[str, object]) -> Matrix:
    """The 2N x n matrix M X + t 1^T of a result."""
    m, t, pts = result["M"], result["t"], result["X"]
    return [[dot(row, p) + tr for p in pts] for row, tr in zip(m, t)]
test_tomasi_kanade_factorization.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tomasi-kanade-factorization/. The authors are listed in prov/0876R2.jsonl.

import math
import random

import pytest

from cvgeom import axis_angle_to_R, random_rotation
from cvla import dot, mul, svd, transpose
from tomasi_kanade_factorization import (measurement_matrix, metric_rows, reproject,
                                         tomasi_kanade_factorization)


def make_tracks(seed, n_frames=5, n_pts=12, noise=0.0, max_angle=0.6):
    rng = random.Random(seed)
    pts = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(n_pts)]
    base = random_rotation(rng)
    rots = []
    for _ in range(n_frames):
        axis = [rng.gauss(0, 1) for _ in range(3)]
        rots.append(mul(axis_angle_to_R(axis, rng.uniform(0, max_angle)), base))
    obs = []
    for r in rots:
        a, b = rng.uniform(-5, 5), rng.uniform(-5, 5)
        obs.append([(dot(r[0], p) + a + rng.gauss(0, noise) if noise else dot(r[0], p) + a,
                     dot(r[1], p) + b + rng.gauss(0, noise) if noise else dot(r[1], p) + b)
                    for p in pts])
    return pts, rots, obs


def distances(pts):
    return [math.dist(p, q) for i, p in enumerate(pts) for q in pts[i + 1:]]


def test_exact_tracks_give_the_true_shape():
    for seed in range(3):
        pts, _, obs = make_tracks(seed)
        res = tomasi_kanade_factorization(obs)
        # the centered matrix has rank 3
        assert res["S"][3] < 1e-9 * res["S"][0]
        # M X + t reproduces W
        w = measurement_matrix(obs)
        rep = reproject(res)
        assert max(abs(a - b) for ra, rb in zip(w, rep) for a, b in zip(ra, rb)) < 1e-9
        # the shape is right up to a rotation, a translation and a reflection
        for d1, d2 in zip(distances(pts), distances(res["X"])):
            assert abs(d1 - d2) < 1e-8


def test_rows_are_orthonormal_and_frame_zero_is_fixed():
    _, _, obs = make_tracks(4, n_frames=6)
    res = tomasi_kanade_factorization(obs)
    m = res["M"]
    for f in range(6):
        a, b = m[2 * f], m[2 * f + 1]
        assert abs(dot(a, a) - 1) < 1e-9 and abs(dot(b, b) - 1) < 1e-9
        assert abs(dot(a, b)) < 1e-9
    assert max(abs(x - y) for x, y in zip(m[0] + m[1], [1, 0, 0, 0, 1, 0])) < 1e-9


def test_true_rotations_up_to_one_world_rotation():
    _, rots, obs = make_tracks(5, n_frames=4)
    m = tomasi_kanade_factorization(obs)["M"]
    # M_f = rows of R_f G for one orthogonal G; G = R_0^T [m_0; m_1; m_0 x m_1] up to a mirror
    for f in range(4):
        for k in (0, 1):
            # inner products between all camera rows are invariant under G
            for g in range(4):
                for l in (0, 1):
                    want = dot(rots[f][k], rots[g][l])
                    got = dot(m[2 * f + k], m[2 * g + l])
                    assert abs(want - got) < 1e-9


def test_noise_gives_a_small_error():
    pts, _, obs = make_tracks(7, n_frames=8, n_pts=20, noise=0.002)
    res = tomasi_kanade_factorization(obs)
    err = max(abs(d1 - d2) for d1, d2 in zip(distances(pts), distances(res["X"])))
    assert err < 0.02
    # the fourth singular value is at the noise level
    assert res["S"][3] < 0.05 * res["S"][2]


def test_two_frames_do_not_fix_the_metric_matrix():
    _, _, obs = make_tracks(8, n_frames=2)
    w = measurement_matrix(obs)
    n = len(w[0])
    t = [sum(r) / n for r in w]
    u, s, _ = svd([[x - tr for x in r] for r, tr in zip(w, t)])
    m_hat = [[u[i][k] * math.sqrt(s[k]) for k in range(min(3, len(s)))] for i in range(4)]
    g = metric_rows(m_hat)
    sv = svd(g)[1]
    # 6 equations in 6 unknowns, but only rank 5: a one-parameter family remains
    assert sv[4] > 1e-6 * sv[0]
    assert sv[5] < 1e-9 * sv[0]
    with pytest.raises(ValueError):
        tomasi_kanade_factorization(obs)


def test_mirror_shape_fits_equally_well():
    pts, _, obs = make_tracks(9)
    res = tomasi_kanade_factorization(obs)
    # flipping depth and the third column of M gives the same image data
    m2 = [[r[0], r[1], -r[2]] for r in res["M"]]
    x2 = [[p[0], p[1], -p[2]] for p in res["X"]]
    rep1 = reproject(res)
    rep2 = reproject({"M": m2, "t": res["t"], "X": x2})
    assert max(abs(a - b) for ra, rb in zip(rep1, rep2) for a, b in zip(ra, rb)) < 1e-12
    for f in range(len(m2) // 2):
        assert abs(dot(m2[2 * f], m2[2 * f + 1])) < 1e-9

History

Ullman (1979) proved that three orthographic views of four points that are not coplanar determine the structure, up to a reflection. Tomasi and Kanade (1992) observed that the centered measurement matrix of orthographic tracks has rank 3 and factored it with the SVD, which gave a stable method that uses all frames and points together. Poelman and Kanade (1997) extended the method to the paraperspective model. Sturm and Triggs (1996) carried the idea to projective cameras, and the factorization idea became a standard part of multiple view geometry.

References

  1. Carlo Tomasi and Takeo Kanade, Shape and motion from image streams under orthography: a factorization method, International Journal of Computer Vision 9(2), 1992, 137-154, the whole paper (the rank theorem, the factorization by the SVD, the metric constraints and the experiments)
  2. Conrad J. Poelman and Takeo Kanade, A paraperspective factorization method for shape and motion recovery, IEEE Transactions on Pattern Analysis and Machine Intelligence 19(3), 1997, 206-218, the paraperspective model and its metric constraints
  3. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Chapter 18, N-view computational methods (the factorization algorithm for affine cameras)
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 11, Structure from motion and SLAM (the section on factorization)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.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