Algorithm Search⌘K

Algorithmcore

Camera matrix decomposition

Also called RQ decomposition of the camera matrix, KRt decomposition.

Recover K, R and the camera center from a camera matrix by an RQ decomposition of its left 3 by 3 block and the null vector of P.

Time
Θ(1) worst · average · best
Space
Θ(1) extra
Where
n = the number of entries of P, fixed at 12
Properties
deterministicexactofflineiterative
Origin
Sundaram Ganapathy, 1984

Camera matrix decomposition takes a finite camera projection matrix P=[M∣p4]P = [M \mid p_4], known only up to scale, and returns the intrinsic matrix KK, the rotation RR, the translation tt and the camera center CC of the extrinsic parameters, with P∼K[R∣t]P \sim K [R \mid t]. It factors the left 3×33 \times 3 block as M=KRM = K R by an RQ decomposition (upper triangular times orthogonal), fixes the signs so that KK has a positive diagonal and det⁡R=+1\det R = +1, and gets CC as the right null vector of PP. It does no estimation: its input is a matrix, not images. Among the close pages, camera calibration is the problem of finding KK and the distortion; DLT resectioning finds PP from 2D to 3D matches, and this page is its usual second step; Zhang's method and Tsai's method find KK from a pattern without going through a general PP.

In plain words

Suppose a friend hands you the one 3×43 \times 4 table of numbers that describes a camera, and you want the usual camera settings back: the focal lengths, the principal point, where the camera stands and where it points. The left 3×33 \times 3 part of the table is the product of the lens matrix, which has zeros below its diagonal, and the turn of the camera. A standard matrix tool splits a matrix into exactly such a product. The split is unique once you require positive focal lengths and a true turn, not a mirror. The position of the camera is the one point of space that the table sends to nothing, and the last column gives the shift.

The problem

Input. A real 3×43 \times 4 matrix P=[M∣p4]P = [M \mid p_4] with det⁡M≠0\det M \ne 0. PP is a camera matrix up to an unknown nonzero scale, which may be negative.

Output. An intrinsic matrix KK (upper triangular, positive diagonal, K33=1K_{33} = 1), a rotation RR (RTR=IR^{\mathsf T} R = I, det⁡R=+1\det R = +1), a vector tt and the center C=−RTtC = -R^{\mathsf T} t, with P=λK[R∣t]P = \lambda K [R \mid t] for some λ≠0\lambda \ne 0. The conventions are those of the area: Xc=RXw+tX_c = R X_w + t, the camera looks along +Z+Z, and the depth of a point in front of the camera is positive.

If det⁡M=0\det M = 0, PP is not a finite camera (for example it is an affine camera), and no such factorization exists.

The algorithm

  1. DECOMPOSE-CAMERA(P)
  2. 1M <- P[:, 1..3] ; p4 <- P[:, 4]
  3. 2if det M = 0 then error "not a finite camera"
  4. 3if det M < 0 then M <- -M ; p4 <- -p4
  5. 4(K, R) <- RQ(M) ▷ K upper triangular, R orthogonal
  6. 5for i <- 1 to 3: if K[i][i] < 0 then negate column i of K and row i of R
  7. 6t <- K^-1 p4
  8. 7K <- K / K[3][3]
  9. 8C <- -R^T t
  10. 9return K, R, t, C

Line L3 removes a negative scale: PP and −P-P are the same camera, and only the sign with det⁡M>0\det M > 0 can give det⁡R=+1\det R = +1. Line L4 is the RQ decomposition. It is the QR decomposition turned around: reverse the rows of MM, transpose, take a QR decomposition, and undo the reversal (the reference code does this; HZ Appendix 4 uses Givens rotations instead). Line L5 makes the diagonal of KK positive. Negating column ii of KK and row ii of RR leaves the product KRK R unchanged, since it inserts D2=ID^2 = I with DD a diagonal sign matrix. After L3 and L5, det⁡R=det⁡M/det⁡K>0\det R = \det M / \det K > 0, so RR is a rotation. Line L6 must use KK before its scale is removed in L7; then K[R∣t]=[M∣p4]K [R \mid t] = [M \mid p_4] exactly. Line L8 is the center, which also is the right null vector of PP: P(C,1)T=λK(RC+t)=0P (C, 1)^{\mathsf T} = \lambda K (R C + t) = 0.

Example

Take K0=(413052001)K_0 = \begin{pmatrix} 4 & 1 & 3 \\ 0 & 5 & 2 \\ 0 & 0 & 1 \end{pmatrix}, the rotation by 90 degrees about ZZ, R0=(0−10100001)R_0 = \begin{pmatrix} 0 & -1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{pmatrix}, and t0=(1,2,4)t_0 = (1, 2, 4). Hide the scale by λ=−2\lambda = -2:

P=−2K0[R0∣t0]=(−28−6−36−100−4−3600−2−8).P = -2 K_0 [R_0 \mid t_0] = \begin{pmatrix} -2 & 8 & -6 & -36 \\ -10 & 0 & -4 & -36 \\ 0 & 0 & -2 & -8 \end{pmatrix}.
line value
L1, L2 M=(−28−6−100−400−2)M = \begin{pmatrix} -2 & 8 & -6 \\ -10 & 0 & -4 \\ 0 & 0 & -2 \end{pmatrix}, det⁡M=−160\det M = -160
L3 negate: M=(2−861004002)M = \begin{pmatrix} 2 & -8 & 6 \\ 10 & 0 & 4 \\ 0 & 0 & 2 \end{pmatrix}, p4=(36,36,8)p_4 = (36, 36, 8)
L4 K=(8260104002)K = \begin{pmatrix} 8 & 2 & 6 \\ 0 & 10 & 4 \\ 0 & 0 & 2 \end{pmatrix}, R=R0R = R_0
L5 the diagonal (8,10,2)(8, 10, 2) is already positive
L6 back substitution: t3=8/2=4t_3 = 8/2 = 4, t2=(36−4⋅4)/10=2t_2 = (36 - 4 \cdot 4)/10 = 2, t1=(36−2⋅2−6⋅4)/8=1t_1 = (36 - 2 \cdot 2 - 6 \cdot 4)/8 = 1
L7 K=K/2=K0K = K / 2 = K_0
L8 RTt=(2,−1,4)R^{\mathsf T} t = (2, -1, 4), so C=(−2,1,−4)C = (-2, 1, -4)

The right null vector of PP, scaled to last entry 1, is also (−2,1,−4,1)(-2, 1, -4, 1), and the Cholesky route of the variants below gives the same K0K_0. Without line L3, the RQ step would have to give a KK with a negative diagonal entry or an RR with det⁡R=−1\det R = -1.

Correctness

Line L3 makes det⁡M>0\det M > 0 by a change of sign that does not change the camera. Every real square matrix has an RQ decomposition M=KQM = K Q, and since MM is nonsingular, the diagonal of KK has no zero, so the sign fix of line L5 is possible and keeps the product. The determinant of the new orthogonal factor is det⁡M/det⁡K\det M / \det K, a quotient of positive numbers, so it is +1+1. Lines L6 and L7 then give P=λK[R∣t]P = \lambda K [R \mid t] with λ=±K33≠0\lambda = \pm K_{33} \ne 0. For uniqueness, two such factorizations give an upper triangular matrix with a positive diagonal that is a multiple of an orthogonal matrix, so it is the identity times a positive scale, and the condition K33=1K_{33} = 1 fixes the scale. The full proof is in the proof file below.

Proof: The decomposition returns the unique K, R and t of a finite camerafull

We use the notation of the page. The input is a real 3×43 \times 4 matrix P=[M∣p4]P = [M \mid p_4] with det⁡M≠0\det M \ne 0. A matrix KK is an intrinsic matrix if it is upper triangular with a positive diagonal and K33=1K_{33} = 1. A rotation is a real 3×33 \times 3 matrix RR with RTR=IR^{\mathsf T} R = I and det⁡R=+1\det R = +1.

Claim. DECOMPOSE-CAMERA(P)(P) returns an intrinsic matrix KK, a rotation RR, a vector tt and the point C=−RTtC = -R^{\mathsf T} t, such that P=λK[R∣t]P = \lambda K [R \mid t] for some real λ≠0\lambda \ne 0 and P(C,1)T=0P (C, 1)^{\mathsf T} = 0. Moreover, these KK, RR and tt are the only ones with this property.

Lemma 1 (RQ). Every real square matrix AA can be written A=UQA = U Q with UU upper triangular and QQ orthogonal.

Proof. Let JJ be the reversal matrix, with ones on the anti-diagonal, so J=JT=J−1J = J^{\mathsf T} = J^{-1}. Take a QR factorization (JA)T=Q1U1(J A)^{\mathsf T} = Q_1 U_1, with Q1Q_1 orthogonal and U1U_1 upper triangular; it exists for every real square matrix, for example by Householder reflections. Then JA=U1TQ1TJ A = U_1^{\mathsf T} Q_1^{\mathsf T}, so A=(JU1TJ)(JQ1T)A = (J U_1^{\mathsf T} J)(J Q_1^{\mathsf T}). The matrix JU1TJJ U_1^{\mathsf T} J is upper triangular, because U1TU_1^{\mathsf T} is lower triangular and conjugation by JJ reverses the order of both the rows and the columns. The matrix JQ1TJ Q_1^{\mathsf T} is orthogonal as a product of orthogonal matrices. □\square

Lemma 2. An orthogonal upper triangular matrix is diagonal, with diagonal entries ±1\pm 1.

Proof. If UU is upper triangular and invertible, U−1U^{-1} is upper triangular. If UU is also orthogonal, U−1=UTU^{-1} = U^{\mathsf T} is lower triangular. So U−1U^{-1} is diagonal, and then UU is diagonal. A diagonal orthogonal matrix has entries dd with d2=1d^2 = 1. □\square

Existence. Let σ=sign⁡(det⁡M)∈{+1,−1}\sigma = \operatorname{sign}(\det M) \in \{+1, -1\}. After line L3, the algorithm works with σP=[M′∣p4′]\sigma P = [M' \mid p_4'], and det⁡M′=σ3det⁡M=∣det⁡M∣>0\det M' = \sigma^3 \det M = |\det M| > 0. Line L4 gives M′=KQM' = K Q by Lemma 1. Since det⁡M′≠0\det M' \ne 0, every diagonal entry of KK is nonzero. Line L5 multiplies KK on the right and QQ on the left by D=diag⁡(d1,d2,d3)D = \operatorname{diag}(d_1, d_2, d_3) with di=sign⁡(Kii)d_i = \operatorname{sign}(K_{ii}). Because D2=ID^2 = I, the product is unchanged: M′=(KD)(DQ)M' = (K D)(D Q). Now KDK D is upper triangular with a positive diagonal, and R=DQR = D Q is orthogonal. Its determinant is det⁡M′/det⁡(KD)\det M' / \det(K D), a quotient of two positive numbers, and it is ±1\pm 1, so det⁡R=+1\det R = +1 and RR is a rotation. Write KK for KDK D from now on.

Line L6 sets t=K−1p4′t = K^{-1} p_4', so K[R∣t]=[KR∣p4′]=σPK [R \mid t] = [K R \mid p_4'] = \sigma P. Line L7 divides KK by k=K33>0k = K_{33} > 0; call the result K^\hat K, which is an intrinsic matrix. Then P=σk K^[R∣t]P = \sigma k\, \hat K [R \mid t], which is the claim with λ=σk≠0\lambda = \sigma k \ne 0. Line L8 sets C=−RTtC = -R^{\mathsf T} t, so RC+t=0R C + t = 0 and P(C,1)T=λK^(RC+t)=0P (C, 1)^{\mathsf T} = \lambda \hat K (R C + t) = 0.

Uniqueness. Suppose that P=λ1K1[R1∣t1]=λ2K2[R2∣t2]P = \lambda_1 K_1 [R_1 \mid t_1] = \lambda_2 K_2 [R_2 \mid t_2], with K1,K2K_1, K_2 intrinsic matrices, R1,R2R_1, R_2 rotations and λ1,λ2≠0\lambda_1, \lambda_2 \ne 0. Let μ=λ1/λ2\mu = \lambda_1 / \lambda_2. The left blocks give μK1R1=K2R2\mu K_1 R_1 = K_2 R_2, so

U=μ K2−1K1=R2R1T.U = \mu\, K_2^{-1} K_1 = R_2 R_1^{\mathsf T}.

The middle term is upper triangular, and the right term is orthogonal. By Lemma 2, UU is diagonal with entries ±1\pm 1. The diagonal of K2−1K1K_2^{-1} K_1 is positive (it is the quotient of the diagonals), so all diagonal entries of UU have the sign of μ\mu, and U=±IU = \pm I. Since det⁡U=det⁡R2det⁡R1T=+1\det U = \det R_2 \det R_1^{\mathsf T} = +1, U=IU = I. So R1=R2R_1 = R_2 and K1=K2/μK_1 = K_2 / \mu. The (3,3)(3,3) entries are both 1, so μ=1\mu = 1 and K1=K2K_1 = K_2. Finally the last columns give K1t1=K2t2K_1 t_1 = K_2 t_2, so t1=t2t_1 = t_2. □\square

Remark (degenerate input). If det⁡M=0\det M = 0, then no factorization P=λK[R∣t]P = \lambda K [R \mid t] exists, because det⁡(λKR)=λ3det⁡K≠0\det(\lambda K R) = \lambda^3 \det K \ne 0. Line L2 reports this case. The center is then a point at infinity, as for an affine camera.

Complexity

The input has a fixed size. In the real RAM with square roots, each line does a fixed number of operations: the determinant, an RQ decomposition of a 3×33 \times 3 matrix by three Householder reflections (or three Givens rotations), and a 3×33 \times 3 triangular solve. So the time and the extra space are Θ(1)\Theta(1). The DLT that usually comes before it costs Θ(n)\Theta(n) for nn points, so the decomposition is never the expensive step.

Properties

  • Exact. In exact arithmetic the output reproduces PP up to scale exactly.
  • Unique. With the sign rules (KK with a positive diagonal and K33=1K_{33} = 1, det⁡R=+1\det R = +1), the factors KK, RR and tt are unique for each finite camera.
  • Scale free. PP and μP\mu P give the same output for every μ≠0\mu \ne 0, including negative μ\mu.
  • No constraints imposed. The output KK has whatever skew and aspect ratio PP implies. If PP came from noisy data, the skew is small but not zero, even when the real camera has none.

Variants and improvements

  • Cholesky route. Since MMT=λ2KRRTKT=λ2KKTM M^{\mathsf T} = \lambda^2 K R R^{\mathsf T} K^{\mathsf T} = \lambda^2 K K^{\mathsf T}, the Cholesky decomposition of (MMT)−1=LLT(M M^{\mathsf T})^{-1} = L L^{\mathsf T} gives K∝(LT)−1K \propto (L^{\mathsf T})^{-1}; then R=K−1M/λR = K^{-1} M / \lambda with the sign of det⁡M\det M. The reference tests use this route as an independent check. It squares the matrix, so it loses about half the digits when MM is badly conditioned.
  • QR of the inverse. M−1=RTK−1M^{-1} = R^{\mathsf T} K^{-1} is orthogonal times upper triangular, so a plain QR decomposition of M−1M^{-1} gives RTR^{\mathsf T} and K−1K^{-1}. This avoids an RQ routine but needs the inverse.
  • Center by the SVD. The right singular vector of PP for the smallest singular value is the center in homogeneous form. It also works when MM is singular; then its last entry is 0, and the center is at infinity.
  • Gram-Schmidt. RQ is also the Gram-Schmidt process applied to the rows of MM from the last row up. The third row of RR is the unit vector along m3m_3, the third row of MM, which is also the optical axis.
  • Constrained cameras. If the camera is known to have zero skew or square pixels, the decomposition of a noisy PP does not give this. Fit the constrained parameters by minimizing the reprojection error over KK, RR and tt, starting from the decomposition (HZ chapter 7).

When to use it

Use it after DLT resectioning, to read focal lengths, the principal point and the pose from an estimated PP, or to start a nonlinear refinement in the parameters of KK, RR and tt. Use it also to turn a camera matrix from a projective reconstruction, after an upgrade to a metric frame, into a camera that a graphics program or a robot can use. If KK is known in advance, do not decompose an unconstrained PP; solve the perspective-n-point problem for the pose instead, which uses the known KK.

Pitfalls

  • Library sign conventions. RQ routines do not agree on the signs of the diagonal. Some return negative entries, which give negative focal lengths. Always apply line L5.
  • Forgetting the sign of the scale. If det⁡M<0\det M < 0 and line L3 is skipped, a positive diagonal of KK forces det⁡R=−1\det R = -1, a reflection, which is not a camera pose. DLT returns PP with an arbitrary sign, so this happens half of the time.
  • Normalizing KK too early. If KK is divided by K33K_{33} before line L6, the computed tt is too large by the factor K33K_{33}, and the center is wrong by the same factor.
  • Reading RR from MM directly. MM is KRK R, not RR. Its rows are not unit vectors unless K=IK = I.
  • Noise. A small change in PP changes KK and RR smoothly, but the principal point can be poorly determined by the data that gave PP (for example a narrow field of view), so it can move by many pixels. That is a property of the estimate of PP, not of the decomposition.

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.

camera_matrix_decomposition.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/camera-matrix-decomposition/. The authors are listed in prov/VTG4C0.jsonl.
"""Decomposition of a finite camera matrix P = lambda K [R | t].

The input is a 3 x 4 matrix P = [M | p4] with det M != 0, known only up to
a nonzero scale. The output is the intrinsic matrix K (upper triangular,
positive diagonal, K[2][2] = 1), the rotation R (det R = +1), the
translation t and the camera center C = -R^T t, with P ~ K [R | t].
"""

from __future__ import annotations

from typing import List, Sequence, Tuple

from cvla import cholesky, det, inv, matvec, mul, nullvec, rq, solve, transpose

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


def decompose_camera_matrix(P: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix, Vector, Vector]:
    """Return (K, R, t, C) for a finite camera P. Raises ValueError if the
    left 3 x 3 block of P is singular (then P is not a finite camera)."""
    M = [[float(v) for v in row[:3]] for row in P]  # @line L1
    p4 = [float(row[3]) for row in P]  # @line L1
    d = det(M)
    if d == 0.0:  # @line L2
        raise ValueError("the left 3 x 3 block of P is singular")
    if d < 0.0:  # @line L3
        M = [[-v for v in row] for row in M]
        p4 = [-v for v in p4]
    K, R = rq(M)  # @line L4
    for i in range(3):  # @line L5
        if K[i][i] < 0.0:
            for r in range(3):
                K[r][i] = -K[r][i]
            R[i] = [-v for v in R[i]]
    t = solve(K, p4)  # @line L6
    k33 = K[2][2]
    K = [[v / k33 for v in row] for row in K]  # @line L7
    C = [-v for v in matvec(transpose(R), t)]  # @line L8
    return K, R, t, C  # @line L9


def center_from_null_vector(P: Sequence[Sequence[float]]) -> Vector:
    """The camera center as the right null vector of P, dehomogenized. This
    is the second way to get C; it also works when only P is trusted."""
    c = nullvec([list(map(float, row)) for row in P])
    if c[3] == 0.0:
        raise ValueError("the center is at infinity (P is not a finite camera)")
    return [c[i] / c[3] for i in range(3)]


def intrinsics_by_cholesky(P: Sequence[Sequence[float]]) -> Matrix:
    """A second way to get K, used as a reference in the tests: M M^T =
    lambda^2 K K^T, so (M M^T)^-1 = K^-T K^-1 / lambda^2 = L L^T with L
    lower triangular, and K is the inverse of L^T, scaled to K[2][2] = 1."""
    M = [[float(v) for v in row[:3]] for row in P]
    L = cholesky(inv(mul(M, transpose(M))))
    K = inv(transpose(L))
    return [[v / K[2][2] for v in row] for row in K]
cvgeom.py 243 lines
# 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()
test_camera_matrix_decomposition.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/camera-matrix-decomposition/. The authors are listed in prov/VTG4C0.jsonl.
"""Tests of the decomposition P -> K, R, t, C."""

import math
import random

from camera_matrix_decomposition import (center_from_null_vector,
                                         decompose_camera_matrix,
                                         intrinsics_by_cholesky)
from cvgeom import camera_center, camera_matrix, make_K, random_rotation
from cvla import det, eye, mul, norm, scale, sub, transpose


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


def random_camera(rng):
    K = make_K(rng.uniform(300, 1500), rng.uniform(300, 1500),
               rng.uniform(200, 500), rng.uniform(150, 400), rng.uniform(-5, 5))
    R = random_rotation(rng)
    t = [rng.uniform(-3, 3) for _ in range(3)]
    return K, R, t


def check_valid(K, R):
    assert all(K[i][j] == 0.0 for i in range(3) for j in range(i))
    assert all(K[i][i] > 0.0 for i in range(3))
    assert K[2][2] == 1.0
    assert close(mul(transpose(R), R), eye(3), 1e-12)
    assert abs(det(R) - 1.0) <= 1e-12


def test_page_example():
    # K = [[4, 1, 3], [0, 5, 2], [0, 0, 1]], R = rotation by 90 degrees
    # about Z, t = (1, 2, 4), and P scaled by -2.
    P = [[-2.0, 8.0, -6.0, -36.0],
         [-10.0, 0.0, -4.0, -36.0],
         [0.0, 0.0, -2.0, -8.0]]
    K, R, t, C = decompose_camera_matrix(P)
    assert close(K, [[4.0, 1.0, 3.0], [0.0, 5.0, 2.0], [0.0, 0.0, 1.0]], 1e-12)
    assert close(R, [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], 1e-12)
    assert close(t, [1.0, 2.0, 4.0], 1e-12)
    assert close(C, [-2.0, 1.0, -4.0], 1e-12)


def test_exact_recovery_any_scale():
    rng = random.Random(1)
    for _ in range(40):
        K0, R0, t0 = random_camera(rng)
        lam = rng.uniform(0.01, 100.0) * rng.choice([-1.0, 1.0])
        P = scale(camera_matrix(K0, R0, t0), lam)
        K, R, t, C = decompose_camera_matrix(P)
        check_valid(K, R)
        assert close(K, K0, 1e-10 * norm(K0))
        assert close(R, R0, 1e-10)
        assert close(t, t0, 1e-10)
        C0 = [-v for v in [sum(R0[j][i] * t0[j] for j in range(3)) for i in range(3)]]
        assert close(C, C0, 1e-10)


def test_center_three_ways():
    rng = random.Random(2)
    for _ in range(20):
        K0, R0, t0 = random_camera(rng)
        P = scale(camera_matrix(K0, R0, t0), rng.uniform(-5.0, 5.0))
        _, _, _, C = decompose_camera_matrix(P)
        assert close(C, center_from_null_vector(P), 1e-9)
        assert close(C, camera_center(P), 1e-9)
        Ch = C + [1.0]
        assert all(abs(sum(row[k] * Ch[k] for k in range(4))) <= 1e-9 * norm(P)
                   for row in P)


def test_against_cholesky_reference():
    rng = random.Random(3)
    for _ in range(20):
        K0, R0, t0 = random_camera(rng)
        P = scale(camera_matrix(K0, R0, t0), rng.uniform(-5.0, 5.0))
        K, _, _, _ = decompose_camera_matrix(P)
        assert close(K, intrinsics_by_cholesky(P), 1e-9 * norm(K))


def test_any_nonsingular_P_is_a_finite_camera():
    # A random 3 x 4 matrix (for example a noisy DLT estimate) still
    # decomposes, and K [R | t] gives P back up to scale.
    rng = random.Random(4)
    for _ in range(40):
        P = [[rng.gauss(0.0, 1.0) for _ in range(4)] for _ in range(3)]
        K, R, t, _ = decompose_camera_matrix(P)
        check_valid(K, R)
        Q = camera_matrix(K, R, t)
        s = sum(a * b for ra, rb in zip(P, Q) for a, b in zip(ra, rb)) / \
            sum(b * b for rb in Q for b in rb)
        assert close(scale(Q, s), P, 1e-10 * norm(P))


def test_sign_of_scale_puts_points_in_front():
    # With det M > 0 after the sign fix, a point in front of the true camera
    # has a positive third coordinate in K [R | t].
    rng = random.Random(5)
    K0, R0, t0 = make_K(800, 800, 320, 240), eye(3), [0.0, 0.0, 5.0]
    P = scale(camera_matrix(K0, R0, t0), -3.0)
    K, R, t, _ = decompose_camera_matrix(P)
    for _ in range(10):
        X = [rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)]
        z = sum(R[2][k] * X[k] for k in range(3)) + t[2]
        assert z > 0.0


def test_singular_left_block_raises():
    # An affine camera has last row (0, 0, 0, 1), so M is singular.
    P = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
    try:
        decompose_camera_matrix(P)
    except ValueError:
        return
    raise AssertionError("expected ValueError")


def test_rotation_angle_and_zero_skew():
    K0 = make_K(500, 500, 0, 0)
    R0 = [[math.cos(0.3), 0.0, math.sin(0.3)], [0.0, 1.0, 0.0],
          [-math.sin(0.3), 0.0, math.cos(0.3)]]
    K, R, _, _ = decompose_camera_matrix(camera_matrix(K0, R0, [0.0, 0.0, 1.0]))
    assert abs(K[0][1]) <= 1e-12
    trace = sum(R[i][i] for i in range(3))
    assert abs(math.acos((trace - 1.0) / 2.0) - 0.3) <= 1e-12

History

Ganapathy (1984) gave a closed form for the camera parameters from the 3×43 \times 4 matrix of a calibrated camera, for robot vision. In the same years photogrammetry used the direct linear transformation of Abdel-Aziz and Karara (1971) and then read the camera parameters from its coefficients. Hartley and Zisserman (2000, second edition 2004) wrote the decomposition as an RQ factorization of the left 3×33 \times 3 block, with the sign fixes above, and this is the form used in computer vision libraries today.

References

  1. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 6.2, The projective camera (finding the camera center and the decomposition of the camera matrix into K, R and C by RQ); Appendix 4 (the RQ decomposition by Givens rotations)
  2. Sundaram Ganapathy, Decomposition of transformation matrices for robot vision, Pattern Recognition Letters 2(6), 1984, 401-412, the whole paper (camera parameters from the 3 by 4 transformation matrix)
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 11, Structure from motion and SLAM (the part on camera matrix estimation and its decomposition)

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