Algorithm Search⌘K

Algorithmcore

Direct linear transformation for camera resectioning

Also called DLT resectioning.

Estimate the 3 by 4 camera matrix from six or more world to image point pairs as the null vector of a linear system, found by SVD.

Time
Θ(n) worst · average · best
Space
Θ(n) extra
Where
n = the number of world to image point pairs
Properties
deterministicexactofflineiterative
Origin
Y. I. Abdel Aziz, H. M. Karara, 1971

Direct linear transformation (DLT) resectioning finds the 3×43 \times 4 camera projection matrix PP from n≥6n \ge 6 known 3D points XiX_i and their pixels xix_i. Each pair gives two equations that are linear in the 12 entries of PP, so PP is the null vector of a 2n×122n \times 12 matrix, which the singular value decomposition finds; with noise, it is the unit vector that makes the system smallest. The points must not lie on one plane. Among the close pages, camera calibration is the problem of finding KK and the distortion; this page finds the full PP with no assumption on KK, from a 3D target; camera matrix decomposition then splits PP into KK, RR and tt; Zhang's method uses a plane instead of a 3D target; and Tsai's method also models radial distortion. The same linear idea for a plane to plane map is DLT for homographies.

In plain words

You have a box with marks at known places in 3D, and a photo of it. You want the one table of 12 numbers that turns each 3D mark into its spot in the photo. For each mark, the rule "the table sends this mark to that spot" can be written as two plain equations in the 12 numbers. With six marks you have 12 equations, which is enough, since the table is only known up to a common factor. With more marks and some noise, no table fits exactly, so you take the one that comes closest, which a standard matrix tool gives in one step. Before that, you shift and scale both sets of points to a standard size, or the arithmetic loses precision.

The problem

Input. Pairs Xi↔xiX_i \leftrightarrow x_i, i=1,…,ni = 1, \dots, n, with Xi∈R3X_i \in \mathbb{R}^3 world points and xi=(ui,vi)x_i = (u_i, v_i) their pixels, with n≥6n \ge 6. Pixel centers are at integer points, as in HZ and OpenCV.

Output. A 3×43 \times 4 matrix PP with ∥P∥F=1\|P\|_F = 1 such that xi∼P(Xi,1)x_i \sim P (X_i, 1) for all ii when the data are exact. With noise, PP minimizes the algebraic error ∥Ap∥\|A p\| below. The sign is chosen so that the left 3×33 \times 3 block MM has det⁡M>0\det M > 0; then P=λK[R∣t]P = \lambda K [R \mid t] with λ>0\lambda > 0, and points in front of the camera have a positive third coordinate.

Counting. PP has 11 degrees of freedom and each pair gives 2 equations, so 5.5 pairs are the minimum: 6 pairs, using one of the two equations of the sixth.

The algorithm

For the homogeneous pixel xi=(xi,yi,wi)\mathbf{x}_i = (x_i, y_i, w_i) and the homogeneous world point Xi\mathbf{X}_i, the condition xi∼PXi\mathbf{x}_i \sim P \mathbf{X}_i is xi×PXi=0\mathbf{x}_i \times P \mathbf{X}_i = 0. Its first two entries are linear in pp, the 12 entries of PP row by row:

(0T−wiXiTyiXiTwiXiT0T−xiXiT)p=0.\begin{pmatrix} 0^{\mathsf T} & -w_i \mathbf{X}_i^{\mathsf T} & y_i \mathbf{X}_i^{\mathsf T} \\ w_i \mathbf{X}_i^{\mathsf T} & 0^{\mathsf T} & -x_i \mathbf{X}_i^{\mathsf T} \end{pmatrix} p = 0.

The third entry depends on these two when wi≠0w_i \ne 0. Stacking the rows of all pairs gives Ap=0A p = 0 with AA of size 2n×122n \times 12.

  1. DLT-RESECTION(X_1..X_n, x_1..x_n)
  2. 1if n < 6 then error "need at least 6 point pairs"
  3. 2T <- similarity: centroid of x_i to 0, mean distance sqrt(2)
  4. 3U <- similarity: centroid of X_i to 0, mean distance sqrt(3)
  5. 4x~_i <- T x_i ; X~_i <- U X_i ▷ homogeneous
  6. 5for i <- 1 to n: add row (0^T, -w~_i X~_i^T, y~_i X~_i^T) to A
  7. 6add row (w~_i X~_i^T, 0^T, -x~_i X~_i^T) to A
  8. 7p <- unit right singular vector of A for the smallest singular value
  9. 8P~ <- rows p[1..4], p[5..8], p[9..12]
  10. 9P <- T^-1 P~ U
  11. 10P <- P / ||P||_F, negated if det P[:, 1..3] < 0
  12. 11return P

Lines L2 to L4 are the normalization of Hartley (1997), the step of the Hartley normalization page applied to both sets: the pixels move to centroid 0 and mean distance 2\sqrt 2, and the 3D points to centroid 0 and mean distance 3\sqrt 3, so that the average point is (1,1,1)(1, 1, 1) in size. The normalized data are exact data for the camera TPU−1T P U^{-1}, and line L9 undoes the change. Lines L5 and L6 are the two equations above. Line L7 is the least squares solution of Ap=0A p = 0 with ∥p∥=1\|p\| = 1. Line L10 fixes the scale and the sign, so that two runs can be compared entry by entry.

Example

Take the camera with fx=fy=800f_x = f_y = 800, principal point (320,240)(320, 240), R=IR = I and t=(−0.5,−0.5,5)t = (-0.5, -0.5, 5):

P0=(8000320120008002408000015),∥P0∥F≈1876.17,P_0 = \begin{pmatrix} 800 & 0 & 320 & 1200 \\ 0 & 800 & 240 & 800 \\ 0 & 0 & 1 & 5 \end{pmatrix}, \qquad \|P_0\|_F \approx 1876.17,

and six corners of a unit cube, not all on one plane.

XiX_i (0,0,0)(0,0,0) (1,0,0)(1,0,0) (0,1,0)(0,1,0) (0,0,1)(0,0,1) (1,1,0)(1,1,0) (1,0,1)(1,0,1)
xix_i (240,160)(240, 160) (400,160)(400, 160) (240,320)(240, 320) (253.333,173.333)(253.333, 173.333) (400,320)(400, 320) (386.667,173.333)(386.667, 173.333)
line value
L2 centroid of the pixels (320,217.78)(320, 217.78), scale 0.01374750.0137475: TT has translation (−4.3992,−2.9939)(-4.3992, -2.9939)
L3 centroid of the points (0.5,0.333,0.333)(0.5, 0.333, 0.333), scale 2.093332.09333
L5, L6 AA is 12×1212 \times 12; its smallest singular value is 0 up to rounding (5⋅10−19s15 \cdot 10^{-19} s_1)
L7 the null vector, then L9 and L10 give the matrix below
P=(0.426400.170560.639600.42640.127920.4264000.0005330.002665)=P0∥P0∥F.P = \begin{pmatrix} 0.4264 & 0 & 0.17056 & 0.6396 \\ 0 & 0.4264 & 0.12792 & 0.4264 \\ 0 & 0 & 0.000533 & 0.002665 \end{pmatrix} = \frac{P_0}{\|P_0\|_F}.

The effect of lines L2 to L4 shows in the singular values of AA. On this example the ratio s1/s11s_1 / s_{11} of the largest to the smallest nonzero singular value is 8686.38686.3 for the raw data and 3.9573.957 after normalization. The raw matrix mixes entries near 11 (the 3D coordinates) with entries near 10510^5 (pixel times pixel), and its condition number grows with the size of the pixel values. This ratio is a measurement on this example only. In a test with 7 points and pixel noise of σ=1\sigma = 1, the two versions gave almost the same reprojection error; normalization protects against bad conditioning, but it does not make a well conditioned small problem better.

Correctness

By the two rows above, Ap=0A p = 0 holds exactly when every PXiP \mathbf{X}_i is a multiple of xi\mathbf{x}_i. So with exact data, the true P0P_0 is in the null space of AA. If the configuration is not degenerate, the null space has dimension 1, and the unit singular vector of the zero singular value is ±P0/∥P0∥F\pm P_0 / \|P_0\|_F. The normalization maps the exact data for P0P_0 to exact data for TP0U−1T P_0 U^{-1}, and line L9 maps back. Line L10 picks the sign with det⁡M>0\det M > 0. With noise, the singular vector minimizes ∥Ap∥\|A p\| over unit vectors, which is the algebraic error, not the reprojection error. The full proof is in the proof file below.

Degenerate configurations (HZ sections 7.1 and 22.1): all points on one plane, where every P0+a nTP_0 + a\, \mathbf{n}^{\mathsf T} fits as well and the null space has dimension at least 4; the camera center and the points on one twisted cubic; and the points on the union of a plane and one line through the camera center.

Proof: The normalized DLT recovers the camera matrix from exact matches and minimizes the algebraic errorfull

We use the notation of the page. The input is n≥6n \ge 6 pairs Xi↔xiX_i \leftrightarrow x_i, where Xi∈R3X_i \in \mathbb{R}^3 and xi∈R2x_i \in \mathbb{R}^2. We write Xi=(Xi,1)\mathbf{X}_i = (X_i, 1) and xi=(xi,1)\mathbf{x}_i = (x_i, 1) for the homogeneous vectors, p∈R12p \in \mathbb{R}^{12} for the rows of a 3×43 \times 4 matrix PP stacked in order, and AA for the 2n×122n \times 12 matrix of lines L5 and L6.

Claim. (a) For every pp, ApA p is the vector of the two rows of L5 and L6 at each pair, and the output pp of line L7 minimizes ∥Ap∥\|A p\| over the unit vectors. (b) If the data are exact, xi∼P0Xi\mathbf{x}_i \sim P_0 \mathbf{X}_i for a finite camera P0P_0, and the null space of AA has dimension 1, then the algorithm returns P0/∥P0∥FP_0 / \|P_0\|_F with the sign that makes det⁡M>0\det M > 0, where MM is the left 3×33 \times 3 block. (c) The similarities of lines L2 to L4 and L9 do not change the answer in (b).

Lemma 1 (the rows). Let x=(x,y,w)\mathbf{x} = (x, y, w) with w≠0w \ne 0, and let q=PXq = P \mathbf{X}. The two rows of L5 and L6 at this pair give Aip=(yq3−wq2,  wq1−xq3)A_i p = (y q_3 - w q_2, \; w q_1 - x q_3). Both are 0 if and only if qq is a multiple of x\mathbf{x} (the multiple may be 0).

Proof. The row (0T,−wXT,yXT)(0^{\mathsf T}, -w \mathbf{X}^{\mathsf T}, y \mathbf{X}^{\mathsf T}) times pp is −w p2TX+y p3TX=yq3−wq2-w\, p^{2\mathsf T} \mathbf{X} + y\, p^{3\mathsf T} \mathbf{X} = y q_3 - w q_2, where pkTp^{k\mathsf T} is row kk of PP. The other row gives wq1−xq3w q_1 - x q_3 in the same way. These are the first two entries of x×q\mathbf{x} \times q, up to sign. If q=c xq = c\,\mathbf{x}, both are 0. Conversely, if both are 0, then q2=(y/w)q3q_2 = (y / w) q_3 and q1=(x/w)q3q_1 = (x / w) q_3, so q=(q3/w) xq = (q_3 / w)\,\mathbf{x}. □\square

The third entry of x×q\mathbf{x} \times q, xq2−yq1x q_2 - y q_1, adds nothing when w≠0w \ne 0, which is why two rows per pair are enough. After line L4, w=1w = 1 times a positive scale, so w≠0w \ne 0 always holds.

Proof of (a). The first part is Lemma 1. The second part is a property of the singular value decomposition: if A=USVTA = U S V^{\mathsf T} with singular values s1≥⋯≥s12≥0s_1 \ge \dots \ge s_{12} \ge 0 (padded with zeros if 2n<122n < 12, which line L1 excludes), then for a unit vector pp, ∥Ap∥2=∑ksk2(vkTp)2≥s122∑k(vkTp)2=s122\|A p\|^2 = \sum_k s_k^2 (v_k^{\mathsf T} p)^2 \ge s_{12}^2 \sum_k (v_k^{\mathsf T} p)^2 = s_{12}^2, with equality at p=v12p = v_{12}. Line L7 returns v12v_{12}. □\square

Proof of (b), without the similarities. Let p0p_0 be the vector of P0P_0. By Lemma 1 and xi∼P0Xi\mathbf{x}_i \sim P_0 \mathbf{X}_i, Ap0=0A p_0 = 0. The null space of AA has dimension 1, so it is spanned by p0p_0, and s12=0<s11s_{12} = 0 < s_{11}. By (a), line L7 returns a unit vector pp with Ap=0A p = 0, so p=±p0/∥p0∥p = \pm p_0 / \|p_0\|. Line L8 reshapes it into ±P0/∥P0∥F\pm P_0 / \|P_0\|_F, and line L10 keeps the norm 1 and picks the sign with det⁡M>0\det M > 0. That is the claim. □\square

Proof of (c). Let TT be the 3×33 \times 3 similarity of line L2 and UU the 4×44 \times 4 similarity of line L3. Both are invertible, and TT has last row (0,0,1)(0, 0, 1), so TxiT \mathbf{x}_i has last entry 1. From xi∼P0Xi\mathbf{x}_i \sim P_0 \mathbf{X}_i we get

Txi∼(TP0U−1)(UXi).T \mathbf{x}_i \sim (T P_0 U^{-1})(U \mathbf{X}_i).

So the normalized data are exact data for the camera P~0=TP0U−1\tilde P_0 = T P_0 U^{-1}, and this camera is finite. Indeed, U=(sUI−sUc0T1)U = \begin{pmatrix} s_U I & -s_U c \\ 0^{\mathsf T} & 1 \end{pmatrix} with sU>0s_U > 0, so the left 3×33 \times 3 block of TP0U−1T P_0 U^{-1} is TM0/sUT M_0 / s_U, and its determinant det⁡Tdet⁡M0/sU3\det T \det M_0 / s_U^3 is not zero and has the sign of det⁡M0\det M_0, because det⁡T=sT2>0\det T = s_T^2 > 0. The map P↦TPU−1P \mapsto T P U^{-1} is a linear bijection of the 3×43 \times 4 matrices, so the null space of the normalized AA is again one-dimensional: it is the image of the null space for the raw data under this bijection, because by Lemma 1 both null spaces are the sets of matrices that send each Xi\mathbf{X}_i (or UXiU \mathbf{X}_i) to a multiple of xi\mathbf{x}_i (or TxiT \mathbf{x}_i). By (b), line L7 returns ±P~0\pm \tilde P_0 up to scale, and line L9 returns T−1(±cP~0)U=±cP0T^{-1} (\pm c \tilde P_0) U = \pm c P_0 with c>0c > 0. Line L10 then gives P0/∥P0∥FP_0 / \|P_0\|_F with det⁡M>0\det M > 0, since det⁡(cM0)\det(c M_0) has the sign of det⁡M0\det M_0 and the sign rule picks the right one. □\square

Remark (when the null space is larger). If all XiX_i lie on one plane nTX=0\mathbf{n}^{\mathsf T} \mathbf{X} = 0, then every P0+anTP_0 + a \mathbf{n}^{\mathsf T} with a∈R3a \in \mathbb{R}^3 also sends each Xi\mathbf{X}_i to P0XiP_0 \mathbf{X}_i, so the null space has dimension at least 4 and line L7 returns an arbitrary element of it. The other critical configurations, a twisted cubic through the camera center and the points, or a plane plus a line through the center, are in HZ section 22.1. With noise, s12>0s_{12} > 0 and the answer of line L7 is the minimizer of the algebraic error of (a), not of the reprojection error.

Complexity

The model is the floating-point model, because the page is about conditioning; the operation counts are the same in the real RAM. Lines L2 to L6 cost Θ(n)\Theta(n). Line L7 is the SVD of a 2n×122n \times 12 matrix. One-sided Jacobi, as in the reference code, costs Θ(n)\Theta(n) per sweep, and a fixed number of sweeps is enough for full precision in practice; a Householder bidiagonalization costs Θ(n⋅122)=Θ(n)\Theta(n \cdot 12^2) = \Theta(n) with no iteration in nn. Lines L8 to L11 are Θ(1)\Theta(1). So the time is Θ(n)\Theta(n), which is optimal, since each pair must be read. The extra space is Θ(n)\Theta(n) for AA; it drops to Θ(1)\Theta(1) if one accumulates the 12×1212 \times 12 matrix ATAA^{\mathsf T} A and takes its smallest eigenvector, at the price of squaring the condition number.

Properties

  • Exact on exact data. Without noise, and outside the degenerate configurations, the output is the true camera up to scale.
  • Not invariant without normalization. The algebraic error depends on the coordinate frames of the image and of the world. With the normalization of lines L2 to L4, the result does not depend on a similarity of the input frames.
  • Algebraic, not geometric. With noise, the answer minimizes ∥Ap∥\|A p\|. It is not the maximum likelihood estimate, which minimizes the reprojection error under Gaussian pixel noise.
  • No constraints. The result has 11 free parameters. It does not force zero skew or square pixels, so with noise its KK has a small skew.

Variants and improvements

  • Gold standard algorithm (HZ Algorithm 7.1). Use the normalized DLT as a start, then minimize the reprojection error ∑id(xi,PXi)2\sum_i d(x_i, P \mathbf{X}_i)^2 over PP with Levenberg-Marquardt. This is the maximum likelihood estimate when the 3D points are exact and the pixel noise is Gaussian.
  • Inhomogeneous solution. Fix p34=1p_{34} = 1 and solve 11 equations by least squares. With 6 points and 11 of the 12 equations, this is the minimal solution; the reference tests use it as an independent check. It fails when the true p34p_{34} is 0, that is, when the world origin lies on the principal plane of the camera.
  • Restricted cameras. If KK is partly known (zero skew, square pixels), fit those parameters by minimizing the reprojection error over the restricted set, starting from the DLT (HZ chapter 7). If KK is fully known, solve the perspective-n-point problem instead.
  • Radial distortion. Fit a distortion model jointly in the geometric refinement (HZ chapter 7), or use Tsai's method, whose first stage is not affected by radial distortion.
  • Lines. A 3D line and its image line l\mathbf{l} give two equations lTPX=0\mathbf{l}^{\mathsf T} P \mathbf{X} = 0, one for each of two points X\mathbf{X} on the 3D line. They can be stacked into AA with the point rows.

When to use it

Use the DLT when you have a 3D calibration target, or any set of known 3D points that are not on one plane, and you do not know KK: it gives PP and, through camera matrix decomposition, KK, RR and tt, with no starting guess. Use it as the start of a geometric refinement whenever accuracy matters. With a flat target, use Zhang's method. With known KK, use a PnP solver, which needs fewer points and fits fewer unknowns. With strong lens distortion, add a distortion model, since the DLT assumes a pinhole camera.

Pitfalls

  • No normalization. With raw pixel values of a few hundred and world coordinates of size 1, the entries of AA differ by a factor near 10510^5, and the result can lose many digits. Always apply lines L2 to L4 and undo them in L9.
  • Coplanar points. A planar target gives a null space of dimension at least 4, and the SVD returns an arbitrary member. Test the ratio of the second smallest to the largest singular value, and use a homography based method for planar data.
  • Few points near the minimum. With 6 or 7 points, the result follows the noise closely, and the principal point can be far off. Use many points spread over the image and over a range of depths.
  • The sign. The SVD returns pp or −p-p. Without line L10, half of the results have det⁡M<0\det M < 0, and a decomposition without a sign fix then gives a reflection.
  • Equation choice. Using the third row of x×PX\mathbf{x} \times P \mathbf{X} instead of one of the first two fails for points with wi=0w_i = 0 and adds nothing otherwise. Keep the two rows of lines L5 and L6.
  • Pixel convention. Mixing pixel centers at uu with pixel centers at u+0.5u + 0.5 moves the principal point by half a pixel.

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()
dlt_camera_resectioning.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dlt-camera-resectioning/. The authors are listed in prov/WCKDXR.jsonl.
"""Normalized direct linear transformation (DLT) for camera resectioning.

Given n >= 6 world points X_i (3D) and their pixels x_i, find the 3 x 4
camera matrix P with x_i ~ P (X_i, 1). This is the linear part of Hartley
and Zisserman, Algorithm 7.1. The result is scaled to Frobenius norm 1,
with the sign that makes det P[:, :3] > 0.
"""

from __future__ import annotations

import math
from typing import List, Sequence

from cvla import det, inv, matvec, mul, norm, nullvec, scale, svd
from cvgeom import from_h, to_h

Matrix = List[List[float]]


def normalize_2d(pts: Sequence[Sequence[float]]) -> Matrix:
    """The 3 x 3 similarity T that moves the centroid of the 2D points to
    the origin and makes their mean distance to it sqrt(2)."""
    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
    if d == 0.0:
        raise ValueError("all image points coincide")
    s = math.sqrt(2.0) / d
    return [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]]


def normalize_3d(pts: Sequence[Sequence[float]]) -> Matrix:
    """The 4 x 4 similarity U that moves the centroid of the 3D points to
    the origin and makes their mean distance to it sqrt(3)."""
    n = len(pts)
    c = [sum(p[k] for p in pts) / n for k in range(3)]
    d = sum(math.sqrt(sum((p[k] - c[k]) ** 2 for k in range(3))) for p in pts) / n
    if d == 0.0:
        raise ValueError("all world points coincide")
    s = math.sqrt(3.0) / d
    return [[s, 0.0, 0.0, -s * c[0]], [0.0, s, 0.0, -s * c[1]],
            [0.0, 0.0, s, -s * c[2]], [0.0, 0.0, 0.0, 1.0]]


def dlt_matrix(Xh: Sequence[Sequence[float]], xh: Sequence[Sequence[float]]) -> Matrix:
    """The 2n x 12 matrix A of the DLT, two rows per pair (HZ chapter 7),
    for homogeneous world points Xh (4 entries) and image points xh (3)."""
    a: Matrix = []
    for X, (x, y, w) in zip(Xh, xh):
        zero = [0.0] * 4
        a.append(zero + [-w * c for c in X] + [y * c for c in X])  # @line L5
        a.append([w * c for c in X] + zero + [-x * c for c in X])  # @line L6
    return a


def dlt_resection(X: Sequence[Sequence[float]], x: Sequence[Sequence[float]],
                  normalize: bool = True) -> Matrix:
    """Estimate P from n >= 6 pairs of world points X[i] (3 entries) and
    pixels x[i] (2 entries). With normalize=False the data are used as
    they are (the plain DLT, badly conditioned for pixel data)."""
    n = len(X)
    if n != len(x) or n < 6:  # @line L1
        raise ValueError("need at least 6 point pairs")
    if normalize:
        T = normalize_2d(x)  # @line L2
        U = normalize_3d(X)  # @line L3
    else:
        T = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
        U = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
    xh = [matvec(T, to_h(p)) for p in x]  # @line L4
    Xh = [matvec(U, to_h(p)) for p in X]  # @line L4
    a = dlt_matrix(Xh, xh)
    p = nullvec(a)  # @line L7
    pt = [p[0:4], p[4:8], p[8:12]]  # @line L8
    P = mul(mul(inv(T), pt), U)  # @line L9
    s = 1.0 / norm(P)  # @line L10
    if det([row[:3] for row in P]) < 0:
        s = -s
    return scale(P, s)  # @line L11


def normalize_P(P: Sequence[Sequence[float]]) -> Matrix:
    """P scaled to Frobenius norm 1 with det P[:, :3] > 0, to compare two
    camera matrices that are equal up to scale."""
    s = 1.0 / norm(P)
    if det([row[:3] for row in P]) < 0:
        s = -s
    return scale(P, s)


def reprojection_errors(P: Sequence[Sequence[float]], X: Sequence[Sequence[float]],
                        x: Sequence[Sequence[float]]) -> List[float]:
    """The distance in pixels between each x[i] and the projection of X[i]."""
    out = []
    for Xi, xi in zip(X, x):
        u, v = from_h(matvec(P, to_h(Xi)))
        out.append(math.hypot(u - xi[0], v - xi[1]))
    return out


def rms(errors: Sequence[float]) -> float:
    """Root mean square of a list of errors."""
    return math.sqrt(sum(e * e for e in errors) / len(errors))


def singular_values_of_dlt(X: Sequence[Sequence[float]], x: Sequence[Sequence[float]]) -> List[float]:
    """Singular values (descending) of the normalized DLT matrix. A second
    small singular value shows a degenerate configuration."""
    T, U = normalize_2d(x), normalize_3d(X)
    a = dlt_matrix([matvec(U, to_h(p)) for p in X], [matvec(T, to_h(p)) for p in x])
    return svd(a)[1]
test_dlt_camera_resectioning.py 351 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dlt-camera-resectioning/. The authors are listed in prov/WCKDXR.jsonl.
"""Tests of the normalized DLT and of the shared helpers cvla and cvgeom."""

import math
import random
from fractions import Fraction

import cvgeom
import cvla
from cvgeom import (add_noise, axis_angle_to_R, camera_center, camera_matrix,
                    from_h, make_K, project, quat_to_R, random_rotation,
                    random_scene, rot_x, rot_y, rot_z, to_h)
from cvla import (add, cholesky, cross, det, dot, eye, inv, matvec, mul, norm,
                  nullvec, polyroots_real, qr, rq, scale, skew, solve, sub,
                  svd, sym_eig, transpose, zeros)
from dlt_camera_resectioning import (dlt_matrix, dlt_resection, normalize_2d,
                                     normalize_3d, normalize_P, reprojection_errors,
                                     rms, singular_values_of_dlt)


def close(a, b, tol):
    return norm(sub(a, b)) <= tol


def diag(s, m, n):
    return [[s[i] if i == j else 0.0 for j in range(n)] for i in range(m)]


# ------------------------------------------------------------ cvla

def test_cvla_self_test():
    cvla.self_test()


def test_basic_ops():
    a = [[1.0, 2.0], [3.0, 4.0]]
    assert mul(a, eye(2)) == a
    assert transpose(a) == [[1.0, 3.0], [2.0, 4.0]]
    assert add(a, a) == scale(a, 2.0)
    assert sub(a, a) == zeros(2, 2)
    assert matvec(a, [1.0, 1.0]) == [3.0, 7.0]
    assert dot([1, 2, 3], [4, 5, 6]) == 32
    assert norm([3.0, 4.0]) == 5.0
    assert abs(norm(a) - math.sqrt(30.0)) < 1e-15
    u, v = [1.0, 2.0, 3.0], [-2.0, 0.5, 4.0]
    assert matvec(skew(u), v) == cross(u, v)
    assert dot(cross(u, v), u) == 0.0


def test_solve_inv_det_exact_with_fractions():
    rng = random.Random(3)
    for _ in range(20):
        n = rng.randint(1, 5)
        a = [[Fraction(rng.randint(-9, 9)) for _ in range(n)] for _ in range(n)]
        if det(a) == 0:
            continue
        x = [Fraction(rng.randint(-9, 9), rng.randint(1, 5)) for _ in range(n)]
        b = matvec(a, x)
        assert solve(a, b) == x
        ident = [[Fraction(int(i == j)) for j in range(n)] for i in range(n)]
        assert mul(a, inv(a)) == ident
    a = [[Fraction(2), Fraction(1), Fraction(0)], [Fraction(1), Fraction(3), Fraction(1)],
         [Fraction(0), Fraction(1), Fraction(4)]]
    assert det(a) == 18
    assert det([[1.0, 2.0], [2.0, 4.0]]) == 0


def test_det_matches_permutation_expansion():
    import itertools
    rng = random.Random(4)
    a = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(4)]
    total = 0.0
    for perm in itertools.permutations(range(4)):
        inversions = sum(1 for i in range(4) for j in range(i + 1, 4) if perm[i] > perm[j])
        term = -1.0 if inversions % 2 else 1.0
        for i in range(4):
            term *= a[i][perm[i]]
        total += term
    assert abs(det(a) - total) < 1e-12


def test_solve_singular_raises():
    try:
        solve([[1.0, 2.0], [2.0, 4.0]], [1.0, 1.0])
    except ValueError:
        return
    raise AssertionError("expected ValueError")


def test_svd_shapes_and_orthogonality():
    rng = random.Random(5)
    for m, n in [(7, 4), (4, 7), (3, 3), (12, 12), (5, 1), (1, 5)]:
        a = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(m)]
        u, s, v = svd(a)
        k = min(m, n)
        assert len(u) == m and len(u[0]) == k and len(s) == k and len(v) == n
        assert close(mul(mul(u, diag(s, k, k)), transpose(v)), a, 1e-12)
        assert close(mul(transpose(u), u), eye(k), 1e-12)
        assert close(mul(transpose(v), v), eye(len(v[0])), 1e-12)
        assert all(s[i] >= s[i + 1] >= 0 for i in range(k - 1))


def test_svd_against_sym_eig():
    rng = random.Random(6)
    a = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(6)]
    _, s, _ = svd(a)
    w, _ = sym_eig(mul(transpose(a), a))
    assert all(abs(si * si - wi) < 1e-12 for si, wi in zip(s, reversed(w)))


def test_svd_rank_deficient():
    a = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]
    u, s, v = svd(a)
    assert s[2] < 1e-14
    assert close(mul(transpose(u), u), eye(3), 1e-12)
    assert close(mul(mul(u, diag(s, 3, 3)), transpose(v)), a, 1e-12)


def test_nullvec():
    a = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [1.0, 1.0, 1.0]]
    x = nullvec(a)
    assert abs(norm(x) - 1.0) < 1e-14 and norm(matvec(a, x)) < 1e-14
    b = [[1.0, 2.0, 3.0, 4.0], [2.0, 4.0, 6.0, 8.5]]
    y = nullvec(b)
    assert abs(norm(y) - 1.0) < 1e-14 and norm(matvec(b, y)) < 1e-14


def test_qr_rq_cholesky():
    rng = random.Random(8)
    for m, n in [(3, 3), (5, 3), (3, 5), (4, 4)]:
        a = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(m)]
        q, r = qr(a)
        assert close(mul(q, r), a, 1e-13)
        assert close(mul(transpose(q), q), eye(m), 1e-13)
        assert all(r[i][j] == 0.0 for i in range(m) for j in range(min(i, n)))
        assert all(r[i][i] >= 0.0 for i in range(min(m, n)))
    for _ in range(5):
        a = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
        r, q = rq(a)
        assert close(mul(r, q), a, 1e-13)
        assert close(mul(q, transpose(q)), eye(3), 1e-13)
        assert r[1][0] == r[2][0] == r[2][1] == 0.0
        assert all(r[i][i] >= 0.0 for i in range(3))
        spd = add(mul(a, transpose(a)), eye(3))
        low = cholesky(spd)
        assert close(mul(low, transpose(low)), spd, 1e-13)
        assert low[0][1] == low[0][2] == low[1][2] == 0.0
    try:
        cholesky([[1.0, 2.0], [2.0, 1.0]])
    except ValueError:
        return
    raise AssertionError("expected ValueError")


def test_polyroots_real():
    assert all(abs(x - y) < 1e-10 for x, y in zip(polyroots_real([1, -6, 11, -6]), [1, 2, 3]))
    assert polyroots_real([1.0, 0.0, 1.0]) == []
    assert polyroots_real([0.0, 2.0, -4.0]) == [2.0]
    assert polyroots_real([5.0]) == []
    assert polyroots_real([1.0, 0.0, -1.0, 0.0]) == [-1.0, 0.0, 1.0]
    double = polyroots_real([1.0, -2.0, 1.0])
    assert len(double) == 2 and all(abs(x - 1.0) < 1e-6 for x in double)
    rng = random.Random(9)
    for _ in range(10):
        true = sorted(rng.uniform(-5, 5) for _ in range(6))
        c = [1.0]
        for r in true:
            c = [a - r * b for a, b in zip(c + [0.0], [0.0] + c)]
        # x^2 + 1 adds two complex roots that must be dropped
        c = [a + b for a, b in zip(c + [0.0, 0.0], [0.0, 0.0] + c)]
        got = polyroots_real(c)
        assert len(got) == 6
        assert all(abs(x - y) < 1e-8 for x, y in zip(got, true))


# ------------------------------------------------------------ cvgeom

def test_cvgeom_self_test():
    cvgeom.self_test()


def test_homogeneous_and_projection():
    assert to_h([2, 3]) == [2.0, 3.0, 1.0]
    assert from_h([4.0, 6.0, 2.0]) == [2.0, 3.0]
    try:
        from_h([1.0, 0.0])
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")
    K = make_K(500, 500, 320, 240)
    P = camera_matrix(K, eye(3), [0.0, 0.0, 0.0])
    assert project(P, [0.1, -0.2, 2.0]) == [345.0, 190.0]
    assert project(P, [0.2, -0.4, 4.0, 2.0]) == [345.0, 190.0]
    assert project(P, [[0.0, 0.0, 1.0], [0.1, -0.2, 2.0]]) == [[320.0, 240.0], [345.0, 190.0]]
    assert make_K(1, 2, 3, 4, 0.5) == [[1.0, 0.5, 3.0], [0.0, 2.0, 4.0], [0.0, 0.0, 1.0]]


def test_camera_center():
    rng = random.Random(10)
    for _ in range(5):
        R = random_rotation(rng)
        C = [rng.uniform(-3, 3) for _ in range(3)]
        t = [-v for v in matvec(R, C)]
        P = camera_matrix(make_K(700, 650, 300, 200, 1.5), R, t)
        assert close(camera_center(P), C, 1e-12)
        assert norm(matvec(P, to_h(C))) < 1e-9


def test_rotations():
    a = 0.7
    assert close(axis_angle_to_R([1, 0, 0], a), rot_x(a), 1e-15)
    assert close(axis_angle_to_R([0, 2, 0], a), rot_y(a), 1e-15)
    assert close(axis_angle_to_R([0, 0, 0.5], a), rot_z(a), 1e-15)
    assert close(axis_angle_to_R([0, 0, a]), rot_z(a), 1e-15)
    # right-hand rule: a quarter turn about Z maps X to Y
    assert close([matvec(rot_z(math.pi / 2), [1.0, 0.0, 0.0])], [[0.0, 1.0, 0.0]], 1e-15)
    h = math.sqrt(0.5)
    assert close(quat_to_R([h, 0.0, 0.0, h]), rot_z(math.pi / 2), 1e-15)
    assert close(quat_to_R([-h, 0.0, 0.0, -h]), rot_z(math.pi / 2), 1e-15)
    rng = random.Random(12)
    for _ in range(10):
        R = random_rotation(rng)
        assert close(mul(transpose(R), R), eye(3), 1e-12)
        assert abs(det(R) - 1.0) < 1e-12
        axis = [rng.gauss(0, 1) for _ in range(3)]
        Ra = axis_angle_to_R(axis, 1.1)
        assert close(matvec(Ra, axis), axis, 1e-12)


def test_random_rotation_mean_trace():
    # For the uniform distribution on SO(3), E[trace R] = 0.
    rng = random.Random(13)
    m = 3000
    s = sum(sum(random_rotation(rng)[i][i] for i in range(3)) for _ in range(m)) / m
    assert abs(s) < 0.1


def test_random_scene():
    rng = random.Random(14)
    sc = random_scene(rng, n=25, n_cams=3, size=(640, 480))
    for P, R, t, xs in zip(sc["P"], sc["R"], sc["t"], sc["x"]):
        for X, x in zip(sc["X"], xs):
            assert matvec(R, X)[2] + t[2] > 0.0
            assert 0.0 <= x[0] <= 640.0 and 0.0 <= x[1] <= 480.0
            assert close(project(P, X), x, 1e-9)
    sc = random_scene(rng, n=10, n_cams=3, planar=True, first_identity=True)
    assert sc["R"][0] == eye(3) and sc["t"][0] == [0.0, 0.0, 0.0]
    for P, xs in zip(sc["P"], sc["x"]):
        for X, x in zip(sc["X"], xs):
            assert close(project(P, X), x, 1e-9)
    cams = [(make_K(500, 500, 0, 0), eye(3), [0.0, 0.0, 10.0])]
    sc = random_scene(rng, n=5, cams=cams)
    assert sc["t"] == [[0.0, 0.0, 10.0]]


def test_add_noise():
    rng = random.Random(15)
    pts = [[0.0, 0.0] for _ in range(2000)]
    noisy = add_noise(rng, pts, 0.5)
    assert pts[0] == [0.0, 0.0]
    var = sum(p[0] ** 2 + p[1] ** 2 for p in noisy) / (2 * len(noisy))
    assert abs(math.sqrt(var) - 0.5) < 0.03


# ------------------------------------------------------------ DLT

def scene(seed, n, planar=False):
    rng = random.Random(seed)
    K = make_K(800, 780, 320, 240, 2.0)
    sc = random_scene(rng, n=n, n_cams=1, K=K, size=(640, 480), planar=planar)
    return rng, sc["X"], sc["x"][0], sc["P"][0]


def test_normalizations():
    _, X, x, _ = scene(20, 12)
    T, U = normalize_2d(x), normalize_3d(X)
    xs = [from_h(matvec(T, to_h(p))) for p in x]
    Xs = [from_h(matvec(U, to_h(p))) for p in X]
    assert all(abs(sum(p[k] for p in xs)) < 1e-12 for k in range(2))
    assert abs(sum(norm(p) for p in xs) / len(xs) - math.sqrt(2)) < 1e-12
    assert all(abs(sum(p[k] for p in Xs)) < 1e-12 for k in range(3))
    assert abs(sum(norm(p) for p in Xs) / len(Xs) - math.sqrt(3)) < 1e-12


def test_dlt_rows_vanish_on_true_P():
    _, X, x, P = scene(21, 8)
    a = dlt_matrix([to_h(p) for p in X], [to_h(p) for p in x])
    p = P[0] + P[1] + P[2]
    assert norm(matvec(a, p)) < 1e-9 * norm(p)


def test_exact_recovery_without_noise():
    for seed, n in [(22, 6), (23, 7), (24, 20), (25, 60)]:
        _, X, x, P = scene(seed, n)
        for flag in (True, False):
            est = dlt_resection(X, x, normalize=flag)
            assert close(est, normalize_P(P), 1e-8)
            assert max(reprojection_errors(est, X, x)) < 1e-8


def test_against_inhomogeneous_reference():
    # Reference: fix p34 = 1 and solve 11 of the 12 equations of 6 points.
    _, X, x, P = scene(26, 6)
    a = dlt_matrix([to_h(p) for p in X], [to_h(p) for p in x])[:11]
    m = [row[:11] for row in a]
    rhs = [-row[11] for row in a]
    p = solve(m, rhs) + [1.0]
    ref = normalize_P([p[0:4], p[4:8], p[8:12]])
    assert close(dlt_resection(X, x), ref, 1e-8)


def test_scale_and_sign_rule():
    _, X, x, P = scene(27, 10)
    est = dlt_resection(X, x)
    assert abs(norm(est) - 1.0) < 1e-12
    assert det([row[:3] for row in est]) > 0
    # positive third coordinate: the points are in front of the camera
    assert all(matvec(est, to_h(p))[2] > 0 for p in X)


def test_noise():
    # sigma = 0.5 pixels on 50 points: the residual is near sigma sqrt(2)
    # and the center is within 0.1 (the scene is 5 units away).
    rng, X, x, P = scene(28, 50)
    C = camera_center(P)
    for _ in range(3):
        xn = add_noise(rng, x, 0.5)
        est = dlt_resection(X, xn)
        assert rms(reprojection_errors(est, X, xn)) < 0.9
        assert rms(reprojection_errors(est, X, x)) < 0.5
        assert norm(sub(camera_center(est), C)) < 0.1


def test_coplanar_points_are_degenerate():
    _, X, x, _ = scene(29, 20, planar=True)
    s = singular_values_of_dlt(X, x)
    assert s[-3] < 1e-12 * s[0]
    _, X, x, _ = scene(30, 20)
    s = singular_values_of_dlt(X, x)
    assert s[-1] < 1e-12 * s[0] and s[-2] > 1e-3 * s[0]


def test_too_few_points():
    _, X, x, _ = scene(31, 6)
    try:
        dlt_resection(X[:5], x[:5])
    except ValueError:
        return
    raise AssertionError("expected ValueError")

History

Abdel-Aziz and Karara presented the direct linear transformation at the ASP Symposium on Close-Range Photogrammetry in 1971, as a linear model with 11 parameters from object space to the coordinates measured on a photograph, which needs no starting values. It became a standard tool of close-range photogrammetry, and computer vision adopted it as the basic linear method for the camera matrix. Hartley (1997) explained the poor accuracy of the raw linear methods by the condition of the system and showed that a simple normalization of the data fixes it. Hartley and Zisserman (2000, second edition 2004) present the normalized DLT followed by a fit of the geometric error as the gold standard algorithm.

References

  1. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Chapter 7, Computation of the camera matrix P (Section 7.1, the basic equations, the minimal solution and the degenerate configurations; Algorithm 7.1, the gold standard algorithm); Section 4.4 on data normalization; Section 22.1 on the degenerate configurations of resectioning
  2. Y. I. Abdel-Aziz and H. M. Karara, Direct linear transformation from comparator coordinates into object space coordinates in close-range photogrammetry, Proceedings of the ASP Symposium on Close-Range Photogrammetry, 1971; reprinted in Photogrammetric Engineering and Remote Sensing 81(2), 2015, 103-107, the whole paper (the 11 parameter linear model from object space to comparator coordinates)
  3. Richard I. Hartley, In defense of the eight-point algorithm, IEEE Transactions on Pattern Analysis and Machine Intelligence 19(6), 1997, 580-593, the analysis of the condition of the linear system and the isotropic normalization of the data (shown for the fundamental matrix; the same argument applies to the DLT)

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example