Algorithm Search⌘K

Algorithmadvanced

Sparse bundle adjustment

Also called SBA, Lourakis-Argyros bundle adjustment.

Levenberg-Marquardt for bundle adjustment that eliminates the points by the reduced camera system, so a step costs O(N^3) in the N cameras and only linear time in the points.

Time
O(m + n N^2 + N^3) per_iteration
Space
O(m + N^2) extra
Where
N = the number of cameras; m = the number of observations; n = the number of points
Properties
deterministiciterativelocalmonotoneiterative
Origin
Duane C. Brown, Manolis I. A. Lourakis, Antonis A. Argyros, 1958

Sparse bundle adjustment (SBA) is Levenberg-Marquardt applied to bundle adjustment, with each damped linear system solved in a way that uses the sparsity of the problem. In bundle adjustment each residual depends on one camera and one point only, so the Gauss-Newton matrix JTJJ^{\mathsf T} J has a block diagonal camera part UU, a block diagonal point part VV with 3×33 \times 3 blocks, and a coupling part WW that is nonzero only where a camera sees a point. SBA builds these blocks from the small per-observation Jacobians, eliminates all the points at once with the Schur complement S=U∗−WV∗−1WTS = U^* - W V^{*-1} W^{\mathsf T}, solves the reduced camera system in SS by a Cholesky factorization, and recovers the point updates one by one. The step is exactly the Levenberg-Marquardt step, but its cost drops from cubic in all the parameters to cubic in the cameras plus linear in the points. Among the close pages, bundle adjustment is the problem, the reduced camera system is the elimination technique on its own, inexact Newton bundle adjustment solves SS approximately by conjugate gradients when NN is too large to factor, and gauge freedom explains why the undamped matrix is singular.

In plain words

Bundle adjustment fixes many cameras and many 3D points together so that every point lands where it was seen in every photo. Written as one big system of equations, this is huge, but most of it is empty: each measurement links only one camera to one point. If you knew the cameras, each point could be fixed alone with a tiny 3 by 3 system. SBA uses this. It first writes, for every point, how its best position depends on the cameras, and folds that into one system about the cameras only. That system is small when there are few cameras. After solving it, each point is updated alone. Around this sits the usual Levenberg-Marquardt brake that keeps every accepted step an improvement.

The problem

Input. A shared intrinsic matrix K=(fxscx0fycy001)K = \begin{pmatrix} f_x & s & c_x \\ 0 & f_y & c_y \\ 0 & 0 & 1 \end{pmatrix}, start values for NN cameras (Ri,ti)(R_i, t_i) and nn points XjX_j, and mm observations (i,j,xij)(i, j, x_{ij}): point jj seen at pixel xijx_{ij} in camera ii. A set of fixed cameras, usually camera 0, a damping factor τ\tau and stopping limits. The camera frame has XX right, YY down and ZZ forward, Xc=RiXj+tiX_c = R_i X_j + t_i, and pixel centers are at integer coordinates.

Output. Cameras and points at a local minimizer of the reprojection cost F=12∑(i,j)∥π(K(RiXj+ti))−xij∥2F = \tfrac12 \sum_{(i, j)} \|\pi(K (R_i X_j + t_i)) - x_{ij}\|^2, with FF no larger than at the start. With isotropic Gaussian pixel noise this is the maximum likelihood estimate.

Parameters. A free camera has 6: a rotation vector ωi\omega_i applied on the left, Ri←exp⁡([ωi]×)RiR_i \leftarrow \exp([\omega_i]_\times) R_i, and a translation step. A point has 3. The Jacobian of the residual rijr_{ij} has two nonzero blocks: AijA_{ij} (2×62 \times 6) for camera ii and BijB_{ij} (2×32 \times 3) for point jj.

The algorithm

  1. SPARSE-BA(K, cameras, points, observations, τ, ε_1, ε_2, k_max)
  2. 1ν <- 2 ; for each observation (i, j): A_ij, B_ij, r_ij; U_i += A^T A ; V_j += B^T B ; W_ij <- A^T B ; g_a,i += A^T r ; g_b,j += B^T r
  3. 2μ <- τ · max diagonal entry of U and V
  4. 3for k <- 1 to k_max
  5. 4if ||g||_∞ <= ε_1 then return
  6. 5U*_i <- U_i + μ I ; V*_j <- V_j + μ I ; e_i <- -g_a,i
  7. 6for each point j, for each pair of cameras i, k that see j: S_ik -= W_ij V*_j^-1 W_kj^T ; e_i += W_ij V*_j^-1 g_b,j ▷ S_ii starts at U*_i
  8. 7solve S δa = e by Cholesky
  9. 8for each point j: δb_j <- -V*_j^-1 (g_b,j + Σ_i W_ij^T δa_i)
  10. 9if ||δ|| <= ε_2 (||x|| + ε_2) then return
  11. 10ρ <- (F(x) - F(x ⊕ δ)) / (½ δ^T (μ δ - g))
  12. 11if ρ > 0 then x <- x ⊕ δ ; rebuild the blocks as in L1 ; μ <- μ · max(1/3, 1 - (2ρ - 1)^3) ; ν <- 2
  13. 12else μ <- μ ν ; ν <- 2 ν
  14. 13return cameras, points

Line L1 computes, for each observation, the residual and the two Jacobian blocks: with D=∂π/∂XcD = \partial \pi / \partial X_c, Aij=D (−[RiXj]×    I)A_{ij} = D\,(-[R_i X_j]_\times \;\; I) and Bij=DRiB_{ij} = D R_i. It accumulates the blocks of JTJJ^{\mathsf T} J and of the gradient g=JTrg = J^{\mathsf T} r; nothing of size m×(6N+3n)m \times (6N + 3n) is ever stored. Lines L2, L4 and L9 to L12 are the Levenberg-Marquardt loop of Madsen, Nielsen and Tingleff. Lines L5 to L8 solve the damped system (JTJ+μI)δ=−g(J^{\mathsf T} J + \mu I) \delta = -g: line L6 forms the reduced camera matrix point by point, line L7 factors it, and line L8 back-substitutes the points, each with its own 3×33 \times 3 inverse. The update x⊕δx \oplus \delta applies the rotation steps on the left and adds the other steps.

Example

The reference test uses 4 cameras looking at 20 points in a cube of side 2 from a distance of about 5, with fx=fy=800f_x = f_y = 800 and (cx,cy)=(320,240)(c_x, c_y) = (320, 240). Every camera sees every point, so m=80m = 80 and there are 160 residuals. Camera 0 is fixed, so the unknowns are 3⋅6=183 \cdot 6 = 18 camera parameters and 20⋅3=6020 \cdot 3 = 60 point parameters. A dense Levenberg-Marquardt step would factor a 78×7878 \times 78 matrix; SBA factors the 18×1818 \times 18 matrix SS and inverts twenty 3×33 \times 3 blocks. The start perturbs the true rotations by about 0.020.02 rad, the translations by about 0.050.05 and the points by about 0.050.05, which gives an RMS reprojection error of 34.1 pixels. With τ=10−3\tau = 10^{-3}:

accepted step FF RMS error (pixels)
0 4.660⋅1044.660 \cdot 10^{4} 34.134.1
1 1.240⋅1021.240 \cdot 10^{2} 1.761.76
2 1.739⋅1011.739 \cdot 10^{1} 0.6590.659
4 2.950⋅10−12.950 \cdot 10^{-1} 0.08590.0859
6 5.877⋅10−55.877 \cdot 10^{-5} 1.21⋅10−31.21 \cdot 10^{-3}
8 5.141⋅10−85.141 \cdot 10^{-8} 3.59⋅10−53.59 \cdot 10^{-5}
10 4.941⋅10−144.941 \cdot 10^{-14} 3.52⋅10−83.52 \cdot 10^{-8}
12 8.518⋅10−248.518 \cdot 10^{-24} 4.62⋅10−134.62 \cdot 10^{-13}

The run tries 13 steps and accepts 12. The data are exact, so the cost reaches rounding level, and the last steps show the fast local rate of Gauss-Newton on a zero residual problem. The result equals the true scene up to the one gauge freedom left, a common scale, here s=0.99695s = 0.99695; after dividing it out, all cameras and points agree with the truth to better than 10−610^{-6}. With 1 pixel of Gaussian noise on the same kind of scene, the final cost is 52.952.9, below the cost 95.495.4 of the true scene, as it must be for a minimizer. These figures are measurements on these test scenes.

Correctness

The blocks of line L1 are the exact derivatives of the residuals with respect to the local update (theorem). For μ>0\mu > 0, the damped matrix is positive definite, so its Schur complement SS is positive definite and line L7 succeeds (theorem). Lines L6 to L8 return the unique solution of the full damped system, by block elimination (theorem). So SBA computes the same step as dense Levenberg-Marquardt and inherits its properties: the predicted reduction is positive, accepted steps lower the cost strictly, and a non-stationary point is left after finitely many rejections (theorems). The proof file below gives the details. The global convergence result of Moré (1978) for trust region Levenberg-Marquardt applies to the same steps.

Proof: Sparse bundle adjustment computes the exact Levenberg-Marquardt step, so it keeps all the properties of Levenberg-Marquardtfull

We use the notation of the page. There are NN cameras, of which the free ones carry 6 parameters each, and nn points with 3 parameters each. The observation (i,j)(i, j) has the residual rij=π(KXc)−xijr_{ij} = \pi(K X_c) - x_{ij} with Xc=RiXj+tiX_c = R_i X_j + t_i, and the Jacobian blocks AijA_{ij} (2×62 \times 6) and BijB_{ij} (2×32 \times 3). The camera update is Ri←exp⁡([ωi]×)RiR_i \leftarrow \exp([\omega_i]_\times) R_i, ti←ti+δtit_i \leftarrow t_i + \delta t_i, and the point update is Xj←Xj+δXjX_j \leftarrow X_j + \delta X_j. We write x⊕δx \oplus \delta for this update and ϕx(δ)=r(x⊕δ)\phi_x(\delta) = r(x \oplus \delta).

Claim. (a) AijA_{ij} and BijB_{ij} of line L1 are the Jacobians of ϕx\phi_x at δ=0\delta = 0. (b) For μ>0\mu > 0, SS of line L6 is symmetric positive definite, and lines L6 to L8 return the unique solution δ\delta of (JTJ+μI)δ=−JTr(J^{\mathsf T} J + \mu I) \delta = -J^{\mathsf T} r, where JJ is the full Jacobian of ϕx\phi_x at 00. (c) So each step is the Levenberg-Marquardt step for ϕx\phi_x, and all properties proved on the Levenberg-Marquardt page hold: the predicted reduction is positive, accepted steps lower FF strictly, and a non-stationary point is left after finitely many rejections.

Proof of (a). Write Xc=(x,y,z)X_c = (x, y, z). The projection is u=(fxx+sy)/z+cxu = (f_x x + s y)/z + c_x, v=fyy/z+cyv = f_y y / z + c_y, so

∂(u,v)∂Xc=(fx/zs/z−(fxx+sy)/z20fy/z−fyy/z2)=D.\frac{\partial (u, v)}{\partial X_c} = \begin{pmatrix} f_x / z & s / z & -(f_x x + s y)/z^2 \\ 0 & f_y / z & -f_y y / z^2 \end{pmatrix} = D.

For the rotation, exp⁡([ω]×)=I+[ω]×+O(∥ω∥2)\exp([\omega]_\times) = I + [\omega]_\times + O(\|\omega\|^2), so Xc(ω)=RX+t+[ω]×RX+O(∥ω∥2)=Xc+ω×(RX)+⋯=Xc−[RX]×ω+…X_c(\omega) = R X + t + [\omega]_\times R X + O(\|\omega\|^2) = X_c + \omega \times (R X) + \dots = X_c - [R X]_\times \omega + \dots. Hence ∂Xc/∂ω=−[RX]×\partial X_c / \partial \omega = -[R X]_\times at ω=0\omega = 0. Also ∂Xc/∂δt=I\partial X_c / \partial \delta t = I and ∂Xc/∂δX=R\partial X_c / \partial \delta X = R. By the chain rule, Aij=D (−[RiXj]×    I)A_{ij} = D \, (-[R_i X_j]_\times \;\; I) and Bij=DRiB_{ij} = D R_i, which is what the code computes. The residual rijr_{ij} does not depend on the parameters of other cameras or points, so these are the only nonzero blocks of the row pair (i,j)(i, j) of JJ. A fixed camera has no columns. □\square

The structure of JTJJ^{\mathsf T} J. Order the parameters as cameras first, then points. By (a),

JTJ=(UWWTV),U=diag⁡(Ui),  Ui=∑jAijTAij,V=diag⁡(Vj),  Vj=∑iBijTBij,J^{\mathsf T} J = \begin{pmatrix} U & W \\ W^{\mathsf T} & V \end{pmatrix}, \quad U = \operatorname{diag}(U_i),\; U_i = \sum_j A_{ij}^{\mathsf T} A_{ij}, \quad V = \operatorname{diag}(V_j),\; V_j = \sum_i B_{ij}^{\mathsf T} B_{ij},

and WW has the block Wij=AijTBijW_{ij} = A_{ij}^{\mathsf T} B_{ij} when camera ii sees point jj and zero otherwise. The gradient is g=(ga,gb)g = (g_a, g_b) with ga,i=∑jAijTrijg_{a,i} = \sum_j A_{ij}^{\mathsf T} r_{ij} and gb,j=∑iBijTrijg_{b,j} = \sum_i B_{ij}^{\mathsf T} r_{ij}. UU is block diagonal because a residual involves only one camera, and VV because it involves only one point.

Proof of (b). Let M=JTJ+μIM = J^{\mathsf T} J + \mu I. For v≠0v \ne 0, vTMv=∥Jv∥2+μ∥v∥2>0v^{\mathsf T} M v = \|J v\|^2 + \mu \|v\|^2 > 0, so MM is positive definite. Its diagonal block V∗=V+μIV^* = V + \mu I is then positive definite, and so is each 3×33 \times 3 block Vj∗V_j^*, which line L6 inverts. The Schur complement S=U∗−WV∗−1WTS = U^* - W V^{*-1} W^{\mathsf T}, with U∗=U+μIU^* = U + \mu I, is symmetric. For a≠0a \ne 0, put b=−V∗−1WTab = -V^{*-1} W^{\mathsf T} a. Then

(ab)TM(ab)=aTU∗a+2aTWb+bTV∗b=aTU∗a−aTWV∗−1WTa=aTSa,\begin{pmatrix} a \\ b \end{pmatrix}^{\mathsf T} M \begin{pmatrix} a \\ b \end{pmatrix} = a^{\mathsf T} U^* a + 2 a^{\mathsf T} W b + b^{\mathsf T} V^* b = a^{\mathsf T} U^* a - a^{\mathsf T} W V^{*-1} W^{\mathsf T} a = a^{\mathsf T} S a,

and the left side is positive, so SS is positive definite and its Cholesky factorization in line L7 exists.

Now the system Mδ=−gM \delta = -g reads U∗δa+Wδb=−gaU^* \delta_a + W \delta_b = -g_a and WTδa+V∗δb=−gbW^{\mathsf T} \delta_a + V^* \delta_b = -g_b. The second equation gives δb=−V∗−1(gb+WTδa)\delta_b = -V^{*-1}(g_b + W^{\mathsf T} \delta_a), which is line L8, block by block, since V∗V^* is block diagonal: δXj=−Vj∗−1(gb,j+∑iWijTδai)\delta X_j = -V_j^{*-1} (g_{b,j} + \sum_i W_{ij}^{\mathsf T} \delta a_i). Putting it into the first equation gives (U∗−WV∗−1WT)δa=−ga+WV∗−1gb(U^* - W V^{*-1} W^{\mathsf T}) \delta_a = -g_a + W V^{*-1} g_b, which is the system of lines L6 and L7. Its block (i,k)(i, k) is δikUi∗−∑jWijVj∗−1WkjT\delta_{ik} U_i^* - \sum_j W_{ij} V_j^{*-1} W_{kj}^{\mathsf T}, with the sum over the points seen by both cameras, and its right side at camera ii is −ga,i+∑jWijVj∗−1gb,j-g_{a,i} + \sum_j W_{ij} V_j^{*-1} g_{b,j}. These are the sums the code accumulates point by point. Conversely, any solution of the reduced system together with line L8 solves Mδ=−gM \delta = -g, and that solution is unique because MM is nonsingular. □\square

Proof of (c). By (a) and (b), at each step the code computes the exact Levenberg-Marquardt step with D=ID = I for the residual function ϕx\phi_x, whose value at 00 is r(x)r(x) and whose Jacobian at 00 is JJ. Line L10 compares F(x⊕δ)=12∥ϕx(δ)∥2F(x \oplus \delta) = \tfrac12 \|\phi_x(\delta)\|^2 with the model 12∥r+Jδ∥2\tfrac12 \|r + J \delta\|^2 and uses the predicted reduction 12δT(μδ−g)\tfrac12 \delta^{\mathsf T} (\mu \delta - g), which is the formula of the Levenberg-Marquardt page. The proofs there use only these facts at a single point, so they apply unchanged: the predicted reduction is positive when g≠0g \ne 0, an accepted step lowers FF strictly, and ρ→1\rho \to 1 as μ→∞\mu \to \infty because ϕx\phi_x is differentiable at 00. □\square

The gauge. With camera 00 fixed, the cost is still unchanged by the scaling Xj→sXjX_j \to s X_j, ti→stit_i \to s t_i, so JJ has a null vector and JTJJ^{\mathsf T} J is singular. This does not affect (b), which needs only μ>0\mu > 0. In floating point, a very small μ\mu can make SS numerically indefinite; the code then treats the step as rejected and raises μ\mu, which is a safe choice by the argument of (c).

Complexity

In the real RAM model, let cjc_j be the number of cameras that see point jj, so m=∑jcjm = \sum_j c_j. Line L1 costs O(m)O(m), since each observation does a constant amount of work. Line L6 costs O(∑jcj2)O(\sum_j c_j^2): one 6×66 \times 6 product for each pair of cameras that share a point. Line L7 is a dense Cholesky factorization of the 6N×6N6N \times 6N matrix, O(N3)O(N^3). Line L8 costs O(m)O(m). So one step costs O(m+∑jcj2+N3)O(m + \sum_j c_j^2 + N^3), which is at most O(m+nN2+N3)O(m + n N^2 + N^3) since cj≤Nc_j \le N. A dense factorization of the whole system would cost Θ((6N+3n)3)\Theta((6N + 3n)^3). The extra space is O(m)O(m) for the blocks WijW_{ij} and O(N2)O(N^2) for SS. When each camera sees only a few others, SS is itself sparse, and a sparse Cholesky factorization with a fill-reducing ordering costs much less than N3N^3. When NN is in the thousands, even that is too much, and inexact Newton bundle adjustment is used instead.

Properties

  • Exact step (theorem). The step equals the dense Levenberg-Marquardt step; only the cost differs.
  • Monotone (theorem). The accepted costs decrease strictly.
  • Points never coupled directly. VV is block diagonal because no residual involves two points, which is what makes the elimination cheap. A residual that links two points, such as a distance constraint, breaks this.
  • Gauge. With one camera fixed, the scale is still free, so JTJJ^{\mathsf T} J is singular. The damping keeps SS positive definite for μ>0\mu > 0, and the iterates may drift slowly along the scale direction.
  • The camera model can change. Shared or per-camera intrinsics, distortion terms and other camera parameters only change the size of the camera blocks.

Variants and improvements

  • Sparse dog leg. Lourakis and Argyros (2005) use the same block solve inside Powell's dog leg method, which reuses the Gauss-Newton step after a rejection; they report shorter run times on their tests (a benchmark result).
  • Sparse Cholesky of SS. When the camera graph is sparse, order SS with nested dissection or minimum degree and factor it as a sparse matrix.
  • Iterative solve of SS. Use the conjugate gradient method with a block Jacobi preconditioner, without forming SS; see inexact Newton bundle adjustment.
  • Eliminating the cameras instead. When there are many more cameras than points, which is rare in vision, eliminate the cameras and solve for the points.
  • Robust costs. Weight each observation by an M-estimator weight; the block structure does not change.
  • Local and windowed versions. Optimize only the latest cameras and the points they see, as in sliding window bundle adjustment and local bundle adjustment in SLAM systems such as ORB-SLAM.

When to use it

Use SBA for bundle adjustment with up to a few thousand cameras, which covers most offline reconstructions of single objects and buildings and most incremental SfM steps. It gives the exact damped step at a cost dominated by the factorization of SS. When NN reaches tens of thousands, or when SS is dense because many cameras see the same points, switch to inexact Newton bundle adjustment. For a fixed scene with known cameras, refine each point alone by optimal triangulation; for known points, refine each camera alone by PnP refinement.

Pitfalls

  • Forgetting to damp VV. In line L5 both UU and VV get μI\mu I. Damping only UU gives a different, non-Levenberg-Marquardt step, and a point seen by one camera has a singular VjV_j.
  • Points with too few views. A point seen by one camera has a rank 2 VjV_j, which only the damping makes invertible. Remove such points, or points with a tiny triangulation angle, before the run.
  • Wrong rotation derivative. The block −[RiXj]×-[R_i X_j]_\times in line L1 belongs to the left update exp⁡([ω]×)R\exp([\omega]_\times) R. With a right update Rexp⁡([ω]×)R \exp([\omega]_\times) the block is −R[Xj]×-R [X_j]_\times. Mixing them gives a wrong Jacobian, which a finite difference test catches.
  • Points behind a camera. A step can move a point to z≤0z \le 0, where π\pi is not defined. Reject such steps as failed steps.
  • No gauge fix. Without a fixed camera, SS has a 7-dimensional near null space when μ\mu is small, and Cholesky can fail in floating point. The reference code then raises μ\mu; fixing camera 0 and possibly one scale parameter avoids it.

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()
sparse_bundle_adjustment.py 224 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-bundle-adjustment/. The authors are listed in prov/C231EB.jsonl.

"""Sparse bundle adjustment: Levenberg-Marquardt with the reduced camera system.

The scene has N cameras with a shared, known intrinsic matrix K, and n 3D
points. Camera i has a rotation R_i and a translation t_i, so a world point
X maps to X_c = R_i X + t_i and to the pixel pi(K X_c). An observation is a
tuple (i, j, u, v): point j is seen at pixel (u, v) in camera i.

The cost is F = 1/2 sum ||pi(K (R_i X_j + t_i)) - (u, v)||^2 over all
observations. A camera is updated by R <- exp([w]_x) R and t <- t + dt (6
parameters), a point by X <- X + dX (3 parameters). The cameras in `fixed`
are not changed; fixing camera 0 removes 6 of the 7 gauge freedoms, and the
damping handles the scale.

Each Levenberg-Marquardt step builds the blocks U_i = sum_j A_ij^T A_ij,
V_j = sum_i B_ij^T B_ij and W_ij = A_ij^T B_ij of J^T J from the 2 x 6 and
2 x 3 Jacobian blocks of each observation, eliminates the points with the
Schur complement S = U* - W V*^-1 W^T, solves S by Cholesky and recovers
the point steps by back-substitution.
"""

from typing import Dict, List, Sequence, Tuple

from cvgeom import axis_angle_to_R
from cvla import cholesky, inv, matvec, mul, skew, transpose

Vector = List[float]
Matrix = List[List[float]]
Camera = Tuple[Matrix, Vector]
Observation = Tuple[int, int, float, float]


def to_camera_frame(R: Matrix, t: Vector, X: Sequence[float]) -> Vector:
    """X_c = R X + t."""
    return [sum(R[a][b] * X[b] for b in range(3)) + t[a] for a in range(3)]


def project_point(K: Matrix, R: Matrix, t: Vector, X: Sequence[float]) -> Vector:
    """The pixel (u, v) of X; pixel centers are at integer coordinates."""
    x, y, z = to_camera_frame(R, t, X)
    return [(K[0][0] * x + K[0][1] * y) / z + K[0][2], K[1][1] * y / z + K[1][2]]


def observation_blocks(K: Matrix, R: Matrix, t: Vector, X: Sequence[float]) -> Tuple[Matrix, Matrix]:
    """The Jacobian blocks of one residual: A (2 x 6, for (w, dt)) and B (2 x 3, for dX)."""
    rx = matvec(R, X)
    x, y, z = rx[0] + t[0], rx[1] + t[1], rx[2] + t[2]
    fx, s, fy = K[0][0], K[0][1], K[1][1]
    dpi = [[fx / z, s / z, -(fx * x + s * y) / (z * z)],
           [0.0, fy / z, -fy * y / (z * z)]]
    sk = skew(rx)
    dw = mul(dpi, [[-v for v in row] for row in sk])  # d X_c / d w = -[R X]_x
    a = [dw[k] + dpi[k] for k in range(2)]  # d X_c / d t = I
    b = mul(dpi, R)  # d X_c / d X = R
    return a, b


def cost(K: Matrix, cams: Sequence[Camera], pts: Sequence[Vector], obs: Sequence[Observation]) -> float:
    """F = 1/2 sum of the squared reprojection errors."""
    f = 0.0
    for i, j, u, v in obs:
        p = project_point(K, cams[i][0], cams[i][1], pts[j])
        f += 0.5 * ((p[0] - u) ** 2 + (p[1] - v) ** 2)
    return f


def reprojection_rms(K, cams, pts, obs) -> float:
    """The root mean square of the residual vectors, in pixels."""
    return (2.0 * cost(K, cams, pts, obs) / len(obs)) ** 0.5


def _tmul(a: Matrix, b: Matrix) -> Matrix:
    """a^T b."""
    return [[sum(a[k][p] * b[k][q] for k in range(len(a))) for q in range(len(b[0]))] for p in range(len(a[0]))]


def _tvec(a: Matrix, r: Vector) -> Vector:
    """a^T r."""
    return [sum(a[k][p] * r[k] for k in range(len(a))) for p in range(len(a[0]))]


def build_blocks(K, cams, pts, obs, free):
    """The blocks of J^T J and J^T r. Returns (U, V, W, ga, gb), with U and
    ga keyed by the free camera index and W keyed by (i, j)."""
    U = {i: [[0.0] * 6 for _ in range(6)] for i in free}
    ga = {i: [0.0] * 6 for i in free}
    V = [[[0.0] * 3 for _ in range(3)] for _ in pts]
    gb = [[0.0] * 3 for _ in pts]
    W = {}
    for i, j, u, v in obs:
        R, t = cams[i]
        p = project_point(K, R, t, pts[j])
        r = [p[0] - u, p[1] - v]
        a, b = observation_blocks(K, R, t, pts[j])
        btb, btr = _tmul(b, b), _tvec(b, r)
        for p_ in range(3):
            gb[j][p_] += btr[p_]
            for q in range(3):
                V[j][p_][q] += btb[p_][q]
        if i in U:
            ata, atr = _tmul(a, a), _tvec(a, r)
            for p_ in range(6):
                ga[i][p_] += atr[p_]
                for q in range(6):
                    U[i][p_][q] += ata[p_][q]
            W[(i, j)] = _tmul(a, b)
    return U, V, W, ga, gb


def _cholesky_solve(low: Matrix, b: Vector) -> Vector:
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def solve_damped(U, V, W, ga, gb, mu, free):
    """Solve the damped normal equations by the reduced camera system.

    Returns (da, db): da maps each free camera to its 6-vector, db is the
    list of the point 3-vectors. Raises ValueError if S is not positive
    definite."""
    pos = {i: 6 * k for k, i in enumerate(free)}
    nc = 6 * len(free)
    s = [[0.0] * nc for _ in range(nc)]
    e = [0.0] * nc
    for i in free:  # @line L5
        o = pos[i]
        for p in range(6):
            e[o + p] = -ga[i][p]
            for q in range(6):
                s[o + p][o + q] = U[i][p][q] + (mu if p == q else 0.0)
    seen: Dict[int, List[int]] = {}
    for (i, j) in W:
        seen.setdefault(j, []).append(i)
    vinv = [inv([[V[j][p][q] + (mu if p == q else 0.0) for q in range(3)] for p in range(3)])
            for j in range(len(V))]
    for j, cams_j in seen.items():  # @line L6
        ys = {i: mul(W[(i, j)], vinv[j]) for i in cams_j}  # Y_ij = W_ij V*_j^-1
        for i in cams_j:
            yg = matvec(ys[i], gb[j])
            for p in range(6):
                e[pos[i] + p] += yg[p]
            for k in cams_j:
                block = mul(ys[i], transpose(W[(k, j)]))
                for p in range(6):
                    row = s[pos[i] + p]
                    for q in range(6):
                        row[pos[k] + q] -= block[p][q]
    da_flat = _cholesky_solve(cholesky(s), e) if nc else []  # @line L7
    da = {i: da_flat[pos[i]:pos[i] + 6] for i in free}
    db = []
    for j in range(len(V)):  # @line L8
        acc = list(gb[j])
        for i in seen.get(j, []):
            wt = _tvec(W[(i, j)], da[i])
            acc = [x + y for x, y in zip(acc, wt)]
        db.append([-v for v in matvec(vinv[j], acc)])
    return da, db


def apply_step(cams, pts, da, db):
    """x (+) delta: R <- exp([w]_x) R, t <- t + dt, X <- X + dX."""
    new_cams = []
    for i, (R, t) in enumerate(cams):
        if i in da:
            d = da[i]
            new_cams.append((mul(axis_angle_to_R(d[:3]), R), [t[k] + d[3 + k] for k in range(3)]))
        else:
            new_cams.append(([list(row) for row in R], list(t)))
    new_pts = [[x[k] + d[k] for k in range(3)] for x, d in zip(pts, db)]
    return new_cams, new_pts


def sparse_bundle_adjustment(K, cams, pts, obs, fixed=(0,), tau=1e-3,
                             eps1=1e-10, eps2=1e-12, max_iter=100):
    """Run sparse Levenberg-Marquardt. Returns (cams, pts, info) with
    info["costs"] the cost at the start and after each accepted step and
    info["iterations"] the number of steps tried."""
    free = [i for i in range(len(cams)) if i not in fixed]
    cams = [([list(r) for r in R], list(t)) for R, t in cams]
    pts = [list(x) for x in pts]
    nu = 2.0
    f = cost(K, cams, pts, obs)
    U, V, W, ga, gb = build_blocks(K, cams, pts, obs, free)  # @line L1
    diag = [U[i][p][p] for i in free for p in range(6)] + [v[p][p] for v in V for p in range(3)]
    mu = tau * max(diag)  # @line L2
    info = {"costs": [f], "iterations": 0}
    for k in range(max_iter):  # @line L3
        g = [x for i in free for x in ga[i]] + [x for gj in gb for x in gj]
        if max(abs(x) for x in g) <= eps1:  # @line L4
            break
        info["iterations"] = k + 1
        try:
            da, db = solve_damped(U, V, W, ga, gb, mu, free)
        except ValueError:  # S not positive definite in floating point: damp more
            mu *= nu
            nu *= 2.0
            continue
        delta = [x for i in free for x in da[i]] + [x for d in db for x in d]
        size = sum(x * x for x in delta) ** 0.5
        xsize = (sum(x * x for _, t in cams for x in t) + sum(x * x for p in pts for x in p)) ** 0.5
        if size <= eps2 * (xsize + eps2):  # @line L9
            break
        new_cams, new_pts = apply_step(cams, pts, da, db)
        f_new = cost(K, new_cams, new_pts, obs)
        predicted = 0.5 * sum(d * (mu * d - gi) for d, gi in zip(delta, g))
        rho = (f - f_new) / predicted  # @line L10
        if rho > 0:  # @line L11
            cams, pts, f = new_cams, new_pts, f_new
            U, V, W, ga, gb = build_blocks(K, cams, pts, obs, free)
            info["costs"].append(f)
            mu *= max(1.0 / 3.0, 1.0 - (2.0 * rho - 1.0) ** 3)
            nu = 2.0
        else:
            mu *= nu  # @line L12
            nu *= 2.0
    return cams, pts, info  # @line L13
test_sparse_bundle_adjustment.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-bundle-adjustment/. The authors are listed in prov/C231EB.jsonl.

import math
import random

from cvgeom import add_noise, axis_angle_to_R, random_scene
from cvla import mul, solve
from sparse_bundle_adjustment import (apply_step, build_blocks, cost, observation_blocks,
                                      project_point, reprojection_rms, solve_damped,
                                      sparse_bundle_adjustment)


def make_problem(seed, n_cams=4, n_pts=20, noise=0.0):
    rng = random.Random(seed)
    sc = random_scene(rng, n=n_pts, n_cams=n_cams, first_identity=True)
    obs = []
    for i in range(n_cams):
        pix = add_noise(rng, sc["x"][i], noise) if noise > 0 else sc["x"][i]
        for j in range(n_pts):
            obs.append((i, j, pix[j][0], pix[j][1]))
    cams = list(zip(sc["R"], sc["t"]))
    return rng, sc["K"][0], cams, sc["X"], obs


def perturb(rng, cams, pts, rot=0.02, trans=0.05, point=0.05):
    out = [cams[0]]
    for R, t in cams[1:]:
        w = [rng.gauss(0, rot) for _ in range(3)]
        out.append((mul(axis_angle_to_R(w), R), [v + rng.gauss(0, trans) for v in t]))
    return out, [[v + rng.gauss(0, point) for v in x] for x in pts]


def test_jacobian_blocks_against_finite_differences():
    rng, K, cams, pts, _ = make_problem(1)
    h = 1e-6
    for i in range(1, 4):
        R, t = cams[i]
        for j in (0, 7, 13):
            X = pts[j]
            a, b = observation_blocks(K, R, t, X)
            for c in range(6):
                d = [0.0] * 6
                d[c] = h
                plus = apply_step([(R, t)], [], {0: d}, [])[0][0]
                d[c] = -h
                minus = apply_step([(R, t)], [], {0: d}, [])[0][0]
                pp, pm = project_point(K, plus[0], plus[1], X), project_point(K, minus[0], minus[1], X)
                for k in range(2):
                    fd = (pp[k] - pm[k]) / (2 * h)
                    assert abs(fd - a[k][c]) <= 1e-5 * max(1.0, abs(fd))
            for c in range(3):
                xp, xm = list(X), list(X)
                xp[c] += h
                xm[c] -= h
                pp, pm = project_point(K, R, t, xp), project_point(K, R, t, xm)
                for k in range(2):
                    fd = (pp[k] - pm[k]) / (2 * h)
                    assert abs(fd - b[k][c]) <= 1e-5 * max(1.0, abs(fd))


def test_reduced_system_matches_dense_solve():
    rng, K, cams, pts, obs = make_problem(2, n_cams=3, n_pts=8)
    cams, pts = perturb(rng, cams, pts)
    free = [1, 2]
    U, V, W, ga, gb = build_blocks(K, cams, pts, obs, free)
    mu = 3.7
    da, db = solve_damped(U, V, W, ga, gb, mu, free)
    # the full damped system, assembled densely from the per-observation blocks
    nc, n = 6 * len(free), 6 * len(free) + 3 * len(pts)
    a_full = [[0.0] * n for _ in range(n)]
    g_full = [0.0] * n
    for i, j, u, v in obs:
        R, t = cams[i]
        p = project_point(K, R, t, pts[j])
        r = [p[0] - u, p[1] - v]
        a, b = observation_blocks(K, R, t, pts[j])
        row = [[0.0] * n for _ in range(2)]
        for k in range(2):
            if i in free:
                o = 6 * free.index(i)
                row[k][o:o + 6] = a[k]
            row[k][nc + 3 * j:nc + 3 * j + 3] = b[k]
        for p_ in range(n):
            g_full[p_] += row[0][p_] * r[0] + row[1][p_] * r[1]
            for q in range(n):
                a_full[p_][q] += row[0][p_] * row[0][q] + row[1][p_] * row[1][q]
    for p_ in range(n):
        a_full[p_][p_] += mu
    dense = solve(a_full, [-v for v in g_full])
    ours = [x for i in free for x in da[i]] + [x for d in db for x in d]
    for x, y in zip(ours, dense):
        assert abs(x - y) <= 1e-8 * max(1.0, abs(y))


def test_exact_data_is_recovered_up_to_the_gauge():
    rng, K, cams_true, pts_true, obs = make_problem(3)
    cams0, pts0 = perturb(rng, cams_true, pts_true)
    assert reprojection_rms(K, cams0, pts0, obs) > 1.0
    cams, pts, info = sparse_bundle_adjustment(K, cams0, pts0, obs)
    assert reprojection_rms(K, cams, pts, obs) < 1e-8
    # camera 0 is fixed; the scale is the last gauge freedom
    s = math.sqrt(sum(v * v for v in cams[1][1])) / math.sqrt(sum(v * v for v in cams_true[1][1]))
    assert abs(s - 1.0) < 0.2
    for (R, t), (Rt, tt) in zip(cams, cams_true):
        assert max(abs(R[a][b] - Rt[a][b]) for a in range(3) for b in range(3)) < 1e-6
        assert max(abs(x - s * y) for x, y in zip(t, tt)) < 1e-6 * max(1.0, s * max(abs(y) for y in tt))
    for x, y in zip(pts, pts_true):
        assert max(abs(a - s * b) for a, b in zip(x, y)) < 1e-6 * max(1.0, max(abs(b) for b in y))


def test_costs_decrease_strictly():
    rng, K, cams_true, pts_true, obs = make_problem(4, noise=0.5)
    cams0, pts0 = perturb(rng, cams_true, pts_true, rot=0.05, trans=0.2, point=0.1)
    _, _, info = sparse_bundle_adjustment(K, cams0, pts0, obs)
    costs = info["costs"]
    assert len(costs) > 3
    assert all(c1 < c0 for c0, c1 in zip(costs, costs[1:]))


def test_noisy_data_reaches_at_most_the_cost_of_the_truth():
    rng, K, cams_true, pts_true, obs = make_problem(5, noise=1.0)
    cams0, pts0 = perturb(rng, cams_true, pts_true)
    cams, pts, _ = sparse_bundle_adjustment(K, cams0, pts0, obs)
    f_true = cost(K, cams_true, pts_true, obs)
    f_opt = cost(K, cams, pts, obs)
    assert f_opt <= f_true
    # the gradient is zero at the minimizer
    free = [1, 2, 3]
    _, _, _, ga, gb = build_blocks(K, cams, pts, obs, free)
    g = [x for i in free for x in ga[i]] + [x for d in gb for x in d]
    assert max(abs(x) for x in g) < 1e-6
    # with sigma = 1 pixel, the residual RMS per coordinate is close to 1
    rms = math.sqrt(2.0 * f_opt / (2 * len(obs)))
    assert 0.6 < rms < 1.2


def test_predicted_reduction_is_positive():
    rng, K, cams_true, pts_true, obs = make_problem(6, n_cams=3, n_pts=10)
    cams, pts = perturb(rng, cams_true, pts_true)
    free = [1, 2]
    U, V, W, ga, gb = build_blocks(K, cams, pts, obs, free)
    g = [x for i in free for x in ga[i]] + [x for d in gb for x in d]
    for mu in (1e-3, 1.0, 1e3, 1e6):
        da, db = solve_damped(U, V, W, ga, gb, mu, free)
        delta = [x for i in free for x in da[i]] + [x for d in db for x in d]
        assert 0.5 * sum(d * (mu * d - gi) for d, gi in zip(delta, g)) > 0

History

Bundle adjustment comes from photogrammetry. Duane Brown worked out the method for aerial and close range photogrammetry in the late 1950s, and the photogrammetric literature already reduced the normal equations to the camera parameters by eliminating the points, as Triggs, McLauchlan, Hartley and Fitzgibbon (2000) recount in their historical appendix. Their survey brought this structure to computer vision, together with gauge theory and sparse factorization. Hartley and Zisserman (2000, second edition 2004) presented sparse Levenberg-Marquardt as the standard bundle method. Lourakis and Argyros released the SBA package in 2004 and described it in ACM Transactions on Mathematical Software in 2009. It was used in early large reconstruction systems such as Bundler, before solvers with iterative linear algebra took over the largest problems.

References

  1. Manolis I. A. Lourakis and Antonis A. Argyros, SBA: A software package for generic sparse bundle adjustment, ACM Transactions on Mathematical Software 36(1), 2009, the whole paper (the sparse Levenberg-Marquardt algorithm, the block structure of the normal equations, the Schur complement and the software)
  2. Bill Triggs, Philip F. McLauchlan, Richard I. Hartley and Andrew W. Fitzgibbon, Bundle adjustment, a modern synthesis, in Vision Algorithms, Theory and Practice, Lecture Notes in Computer Science 1883, Springer, 2000, 298-372, Section 6, Network structure and implementation (Section 6.1, the Schur complement and the reduced bundle system), and the historical appendix
  3. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Appendix 6, Iterative estimation methods (sparse Levenberg-Marquardt, its application to bundle adjustment and the sparse methods for solving the equations); Chapter 18, N-view computational methods (bundle adjustment)
  4. Manolis I. A. Lourakis and Antonis A. Argyros, Is Levenberg-Marquardt the most efficient optimization algorithm for implementing bundle adjustment?, Tenth IEEE International Conference on Computer Vision (ICCV 2005), vol. 2, 1526-1531, the whole paper (the sparse dog leg alternative and the timing comparison)
  5. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 11, Structure from motion and SLAM (bundle adjustment and exploiting sparsity)

Where this leads

About this page

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

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