Algorithmresearch
Bundle adjustment in the large
Also called inexact Newton bundle adjustment, preconditioned conjugate gradient bundle adjustment.
Solve the reduced camera system of very large bundle adjustments approximately by conjugate gradients with block Jacobi or Schur preconditioners.
- Solves
- Bundle adjustment
- Time
- O(k (m + N)) per_iteration
- Space
- O(m + n + N) extra
- Where
- N = the number of cameras; k = the number of CG iterations in one step; m = the number of observations; n = the number of points
- Model
- Real RAM
- Properties
- deterministiciterativelocalmonotoneiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sameer Agarwal, Noah Snavely, Steven M. Seitz, Richard Szeliski, 2010
Bundle adjustment in the large is Levenberg-Marquardt for bundle adjustment in which each damped step is computed only approximately. It keeps the point elimination of sparse bundle adjustment, but it does not form or factor the reduced camera system . It runs the preconditioned conjugate gradient method on that system instead. Each product is computed block by block from the per-observation blocks, so the work and memory per CG iteration are linear in the number of observations. The preconditioner is block Jacobi on : the inverses of its diagonal blocks. CG stops early, when the residual is a fraction of the right side, as in the inexact Newton methods of Dembo, Eisenstat and Steihaug. The point steps are then recovered exactly. This is the method of choice when the number of cameras is so large that the dense matrix , or its Cholesky factor, does not fit in memory. Among the close pages, sparse bundle adjustment solves the same system exactly, and the reduced camera system page describes the elimination itself.
In plain words
Sparse bundle adjustment shrinks the big bundle adjustment system to a system about the cameras only, and solves that exactly. With tens of thousands of cameras even that small system is too big to store and solve. This method never writes it down. It only needs to know what the system does to a vector, and it can work that out from the many tiny blocks that each photo measurement gives. With that, it solves the system roughly, by a few steps of the conjugate gradient method, which improves a guess one direction at a time. A rough answer is good enough, because the outer loop corrects it at the next step, and the usual Levenberg-Marquardt test still rejects any step that does not lower the error.
The problem
Input. As for sparse bundle adjustment: a shared intrinsic matrix , start values for cameras and points , observations , the fixed cameras, and a damping factor . In addition, a forcing parameter and an optional cap on the CG iterations of one step. The camera frame has right, down and forward, , and pixel centers are at integer coordinates.
Output. Cameras and points at a local minimizer of , with no larger than at the start.
The algorithm
INEXACT-NEWTON-BA(K, cameras, points, observations, τ, η, k_max)- 1
ν <- 2 ; build U_i, V_j, W_ij, g_a, g_b from the observation blocks - 2
μ <- τ · max diagonal entry of U and V - 3
loop - 4
if ||g||_∞ <= ε_1 then return - 5
V*_j^-1 <- (V_j + μ I)^-1 for each point ; e <- -g_a + W V*^-1 g_b - 6
P_i <- (U_i + μ I - Σ_j W_ij V*_j^-1 W_ij^T)^-1 for each free camera ▷ block Jacobi - 7
δa <- PCG from 0 on S δa = e, with S x computed as U* x - W (V*^-1 (W^T x)) and preconditioner P, until ||e - S δa|| <= η ||e|| or k_max iterations - 8
for each point j: δb_j <- -V*_j^-1 (g_b,j + Σ_i W_ij^T δa_i) - 9
if ||δ|| <= ε_2 (||x|| + ε_2) then return - 10
pred <- -g^T δ - ½ ||J δ||^2 ; ρ <- (F(x) - F(x ⊕ δ)) / pred - 11
if ρ > 0 then x <- x ⊕ δ ; rebuild the blocks ; μ <- μ · max(1/3, 1 - (2ρ - 1)^3) ; ν <- 2 - 12
else μ <- μ ν ; ν <- 2 ν - 13
return cameras, points
Lines L1 to L4 and L9 to L12 are the Levenberg-Marquardt loop of sparse bundle adjustment. Line L5 inverts the point blocks and forms the right side of the reduced system. Line L6 builds the block Jacobi preconditioner: each diagonal block gets one term for each point that camera sees, so this costs . Line L7 is the inexact solve. A product with first gathers point by point, multiplies by the inverses, and scatters the result back to the cameras. Line L8 is the exact back-substitution. Line L10 computes the predicted reduction from its definition, with . The short formula of exact Levenberg-Marquardt is wrong here, because the step does not solve the damped system.
Example
The test scene is the one of the sparse bundle adjustment page: 4 cameras, camera 0 fixed, 20 points, 80 observations, an matrix , and a start with an RMS reprojection error of 34.1 pixels. With :
| setting | steps tried | accepted | CG iterations in all | final RMS (pixels) |
|---|---|---|---|---|
| , no cap | 13 | 12 | 226 | |
| , no cap | 13 | 12 | 68 | |
| , at most 3 per step | 42 | 41 | 97 |
With the costs agree with the exact solve of sparse bundle adjustment to the printed digits (, , after the first three steps), and CG uses up to 18 iterations, the size of . With the costs after the first three steps are , and : almost the same progress for a third of the CG work. The CG count per step grows from 2 near the start to 8 near the end, because the right side becomes small and the same relative accuracy needs more iterations. With a loose and a cap of 3, the method still converges and every accepted step lowers the cost, but it needs three times as many outer steps, each with a full rebuild of the blocks. On the first reduced system, block Jacobi preconditioning reaches a relative residual of in 4 CG iterations and in 9, against 9 and 15 without a preconditioner. These numbers are measurements on this small scene; on large scenes the counts and the trade-offs differ.
Correctness
The implicit product equals , and and the block Jacobi preconditioner are symmetric positive definite for (theorem). With the exact back-substitution, the full step is the minimizer of the damped model over for the given , so the damped model equals a quadratic in the cameras; CG from never increases , and so the damped model at the step is at most , and below it when . It follows that the predicted reduction is at least for any number of CG iterations, that accepted steps lower strictly, and that a non-stationary point is left after finitely many rejections (theorems). The forcing parameter only affects the speed. For Newton's method on systems of equations, Dembo, Eisenstat and Steihaug proved local linear convergence for a relative residual bounded by a constant below 1, and superlinear convergence when it tends to 0 (theorem, for that setting). The proof file below gives the details.
Proof: Inexact Newton bundle adjustment computes the reduced camera system correctly and every truncated step is safefull
We use the notation of the page and of the sparse bundle adjustment page. The parameters are ordered as the free cameras (6 each) and then the points (3 each). is the Jacobian of the residual at the current parameters with respect to the local update, , and
and are block diagonal, with blocks and blocks , and has the block when camera sees point . The reduced camera matrix is , and the right side is .
Claim. (a) apply returns and rhs returns . (b) and its diagonal blocks are symmetric positive definite, so the block Jacobi preconditioner of line L6 exists and is positive definite, and in exact arithmetic PCG reaches the exact solution in at most iterations, where is the number of free cameras. (c) Let , where is the PCG iterate after any number of iterations (or when ) and comes from line L8. Then the damped model satisfies , and if then and the predicted reduction computed in line L10 is positive. (d) Accepted steps lower strictly, and at a point with only finitely many steps are rejected before one is accepted.
Proof of (a). For a vector over the free cameras, , then because is block diagonal, and . The code computes for each point from the cameras that see it, and subtracts from the block of camera for each such camera. Together with this is . The same argument with replaced by in the point space gives .
Proof of (b). is positive definite because . Each is a diagonal block of , so it is positive definite and invertible. For put ; then , as on the sparse bundle adjustment page, so is positive definite. A diagonal block , with the columns of camera in the identity, is positive definite too, and so is its inverse. So the preconditioner is positive definite. PCG with a symmetric positive definite matrix and preconditioner is the conjugate gradient method applied to with , and conjugate gradients on a positive definite matrix of order reach the exact solution in at most iterations in exact arithmetic (Nocedal and Wright, Theorem 5.1 and Section 5.1). The check in pcg therefore never fires in exact arithmetic.
Proof of (c). Fix and minimize over . The terms with are , a strictly convex quadratic whose minimizer is . This is line L8. Putting it back gives
which one checks by expanding: the cross terms collect to , and together with gives , while .
PCG started at produces iterates that minimize over the nested affine sets (the minimization property of conjugate gradients, applied to the transformed system; Nocedal and Wright, Theorem 5.2). Since , . If and , the first iterate is with , and , so then .
So . Now let . If , then because is positive definite. If , then and , and by the last remark. In both cases , so . Finally
The code computes from the blocks, which is .
Note that the formula used for exact Levenberg-Marquardt steps is wrong here: it uses , which an inexact step does not satisfy, so it would give a wrong . This is why line L10 computes the reduction directly.
Proof of (d). A step is accepted only if , that is because . So accepted costs decrease strictly.
Let . Each rejection multiplies by at least , so along a run of rejections. From we get , so . The function is twice continuously differentiable near (for points in front of the cameras), with , . So there is a constant with for small , and hence
By (c), . Dividing, . So after finitely many rejections and the step is accepted.
Remarks. The argument of (c) and (d) uses only , and the exact back-substitution, not the size of the CG residual. So the forcing parameter and the cap on the CG iterations only affect the speed, never the safety. The speed is a separate question: for Newton's method on a system of equations, Dembo, Eisenstat and Steihaug (1982) prove local linear convergence when the relative residual stays below a constant , and superlinear convergence when it tends to . The same rates for Levenberg-Marquardt with and both tending to need further conditions, which this proof does not cover.
Complexity
In the real RAM model, with and (every point and camera is observed): building the blocks costs , line L5 costs , and line L6 costs for the products and the inversions of blocks. One product with costs , and one preconditioner application . So one outer step with CG iterations costs , written for . The memory is : the blocks , , and a few vectors. Nothing of size is stored. Sparse bundle adjustment needs time and memory per step instead. In exact arithmetic CG needs at most iterations, but the point of the method is to stop much earlier; the count depends on the conditioning of the preconditioned , which in turn depends on the scene.
Properties
- Matrix free. Only products with are needed; is never formed.
- Safe at any accuracy (theorem). Any number of CG iterations gives a step with positive predicted reduction, as long as the points are back-substituted exactly.
- Monotone (theorem). Accepted costs decrease strictly.
- Slower final convergence. With a fixed the last steps are only as accurate as allows; to get a fast final rate, must go to .
- Parallel. The products and the preconditioner are sums over observations and points, and parallelize well.
Variants and improvements
- Explicit Schur complement. Form as a sparse matrix and run CG on it. This saves work per iteration when is sparse, at the price of storing it.
- Other preconditioners. Agarwal et al. compare several preconditioners, among them the block diagonal of , which they call Schur-Jacobi and which is the one used here. Visibility based preconditioners group the cameras by the points they share, and incomplete Cholesky of is another option.
- CG on the full system. Byröd and Åström (2010) run preconditioned conjugate gradients on the least squares problem itself instead of on the reduced system.
- Adaptive forcing. Choose per step, for example smaller as the gradient shrinks, so that the final convergence is fast. The ideas come from the inexact Newton literature, such as the choices of Eisenstat and Walker.
- Trust region version. Run truncated CG inside a trust region, stopping when the iterate reaches the boundary, as in the Steihaug method; this fits Powell's dog leg method and other trust region frameworks.
- Software. The Ceres Solver library provides an iterative Schur solver of this kind, next to the direct sparse solvers.
When to use it
Use it for bundle adjustment with many thousands of cameras, such as global structure from motion on large internet photo collections, where is too large to factor or its factor too dense. For up to a few thousand cameras, the exact solve of sparse bundle adjustment, with a sparse Cholesky factorization when is sparse, is usually faster and more robust, because it needs fewer outer steps and does not depend on the conditioning. For small windows in real time systems, such as sliding window bundle adjustment, a direct dense solve is simplest.
Pitfalls
- Using the exact pred formula. assumes the damped system is solved exactly. With an inexact step it gives a wrong . Compute .
- Approximate back-substitution. The safety argument needs the exact point steps of line L8. Computing them only roughly can give a step with a negative predicted reduction.
- Poor conditioning. Scenes with long camera chains, such as a street sequence, give an with a large condition number, and CG with block Jacobi needs many iterations. A stronger preconditioner helps.
- Too strict a tolerance. A tiny throws away the advantage: the example needs 226 CG iterations with against 68 with , for the same outer steps.
- Too loose a tolerance. A large or a small cap makes each step cheap but increases the number of outer steps, each of which rebuilds all blocks.
- Gauge. As in sparse bundle adjustment, the undamped is singular when the gauge is not fixed. CG with a small then works on a nearly singular matrix and converges slowly in the gauge directions.
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.
# 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()
inexact_newton_bundle_adjustment.py 310 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inexact-newton-bundle-adjustment/. The authors are listed in prov/HF6T4X.jsonl.
"""Inexact Newton bundle adjustment: Levenberg-Marquardt whose reduced
camera system is solved approximately by preconditioned conjugate gradients.
The scene and the cost are those of the sparse bundle adjustment page. There
are N cameras with a shared, known intrinsic matrix K and n 3D points. Camera
i maps a world point X to X_c = R_i X + t_i and to the pixel pi(K X_c). An
observation (i, j, u, v) says that point j is seen at pixel (u, v) in camera
i, and F = 1/2 sum ||pi(K (R_i X_j + t_i)) - (u, v)||^2.
Each outer step builds the blocks U_i, V_j and W_ij of J^T J. It does not
form the reduced camera matrix S = U* - W V*^-1 W^T. It runs preconditioned
conjugate gradients on S da = e, with products by S computed block by block
and with the inverses of the 6 x 6 diagonal blocks of S as a block Jacobi
preconditioner. CG stops when ||e - S da|| <= eta ||e||. The point steps are
then recovered exactly, and the predicted reduction is computed for the step
that was actually taken.
"""
from typing import Callable, Dict, List, Sequence, Tuple
from cvgeom import axis_angle_to_R
from cvla import inv, matvec, mul, skew
Vector = List[float]
Matrix = List[List[float]]
Camera = Tuple[Matrix, Vector]
Observation = Tuple[int, int, float, float]
# ------------------------------------------------------------- the model
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)]]
dw = mul(dpi, [[-v for v in row] for row in skew(rx)]) # 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 _dot(x: Sequence[float], y: Sequence[float]) -> float:
return sum(p * q for p, q in zip(x, y))
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 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
# ------------------------------------------- the reduced camera system
class ReducedSystem:
"""The damped reduced camera system S da = e, kept in block form.
S = U* - W V*^-1 W^T with U* = U + mu I and V* = V + mu I, and
e = -ga + W V*^-1 gb. Vectors over the free cameras are flat lists of
length 6 len(free), in the order of `free`."""
def __init__(self, U, V, W, ga, gb, mu, free):
self.U, self.W, self.ga, self.gb, self.mu = U, W, ga, gb, mu
self.free = list(free)
self.pos = {i: 6 * k for k, i in enumerate(self.free)}
self.size = 6 * len(self.free)
self.seen: Dict[int, List[int]] = {}
for (i, j) in W:
self.seen.setdefault(j, []).append(i)
self.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))]
def rhs(self) -> Vector:
"""e = -ga + W V*^-1 gb."""
e = [0.0] * self.size
for i in self.free:
for p in range(6):
e[self.pos[i] + p] = -self.ga[i][p]
for j, cams_j in self.seen.items():
y = matvec(self.vinv[j], self.gb[j])
for i in cams_j:
wy = matvec(self.W[(i, j)], y)
for p in range(6):
e[self.pos[i] + p] += wy[p]
return e
def apply(self, x: Vector) -> Vector:
"""S x = U* x - W (V*^-1 (W^T x)), without forming S."""
y = [0.0] * self.size
for i in self.free:
o, ui = self.pos[i], self.U[i]
for p in range(6):
y[o + p] = sum(ui[p][q] * x[o + q] for q in range(6)) + self.mu * x[o + p]
for j, cams_j in self.seen.items():
z = [0.0, 0.0, 0.0]
for i in cams_j:
wt = _tvec(self.W[(i, j)], x[self.pos[i]:self.pos[i] + 6])
z = [a + b for a, b in zip(z, wt)]
z = matvec(self.vinv[j], z)
for i in cams_j:
wz = matvec(self.W[(i, j)], z)
o = self.pos[i]
for p in range(6):
y[o + p] -= wz[p]
return y
def block_jacobi(self) -> Dict[int, Matrix]:
"""The inverses of the 6 x 6 diagonal blocks S_ii = U*_i - sum_j W_ij V*_j^-1 W_ij^T."""
diag = {i: [[self.U[i][p][q] + (self.mu if p == q else 0.0) for q in range(6)] for p in range(6)]
for i in self.free}
for j, cams_j in self.seen.items():
for i in cams_j:
w = self.W[(i, j)]
y = mul(w, self.vinv[j])
for p in range(6):
for q in range(6):
diag[i][p][q] -= sum(y[p][k] * w[q][k] for k in range(3))
return {i: inv(d) for i, d in diag.items()}
def precondition(self, blocks: Dict[int, Matrix], r: Vector) -> Vector:
"""M^-1 r with M the block diagonal of S."""
z = [0.0] * self.size
for i in self.free:
o = self.pos[i]
zi = matvec(blocks[i], r[o:o + 6])
z[o:o + 6] = zi
return z
def back_substitute(self, da: Dict[int, Vector]) -> List[Vector]:
"""db_j = -V*_j^-1 (gb_j + sum_i W_ij^T da_i)."""
db = []
for j in range(len(self.vinv)):
acc = list(self.gb[j])
for i in self.seen.get(j, []):
wt = _tvec(self.W[(i, j)], da[i])
acc = [a + b for a, b in zip(acc, wt)]
db.append([-v for v in matvec(self.vinv[j], acc)])
return db
def pcg(apply_a: Callable[[Vector], Vector], apply_m: Callable[[Vector], Vector], b: Vector,
eta: float, max_iter: int) -> Tuple[Vector, int]:
"""Preconditioned conjugate gradients for A x = b from x = 0. Stops when
||b - A x|| <= eta ||b|| or after max_iter iterations. Returns (x, iterations)."""
x = [0.0] * len(b)
r = list(b)
bnorm = _dot(b, b) ** 0.5
if bnorm == 0.0:
return x, 0
z = apply_m(r)
p = list(z)
rz = _dot(r, z)
for k in range(max_iter):
ap = apply_a(p)
pap = _dot(p, ap)
if pap <= 0.0: # cannot happen for a positive definite A, except by rounding
return x, k
alpha = rz / pap
x = [xi + alpha * pi for xi, pi in zip(x, p)]
r = [ri - alpha * qi for ri, qi in zip(r, ap)]
if _dot(r, r) ** 0.5 <= eta * bnorm:
return x, k + 1
z = apply_m(r)
rz_new = _dot(r, z)
beta = rz_new / rz
rz = rz_new
p = [zi + beta * pi for zi, pi in zip(z, p)]
return x, max_iter
def quadratic_form(U, V, W, free, da: Dict[int, Vector], db: List[Vector]) -> float:
"""delta^T J^T J delta = ||J delta||^2, from the blocks."""
s = 0.0
for i in free:
s += _dot(da[i], matvec(U[i], da[i]))
for j, d in enumerate(db):
s += _dot(d, matvec(V[j], d))
for (i, j), w in W.items():
s += 2.0 * _dot(da[i], matvec(w, db[j]))
return s
def inexact_newton_step(U, V, W, ga, gb, mu, free, eta=0.1, max_cg=None):
"""One damped step with an inexact solve. Returns (da, db, cg_iterations)."""
system = ReducedSystem(U, V, W, ga, gb, mu, free)
e = system.rhs() # @line L5
blocks = system.block_jacobi() # @line L6
limit = max_cg if max_cg is not None else max(1, system.size)
x, its = pcg(system.apply, lambda r: system.precondition(blocks, r), e, eta, limit) # @line L7
da = {i: x[system.pos[i]:system.pos[i] + 6] for i in free}
db = system.back_substitute(da) # @line L8
return da, db, its
def inexact_newton_bundle_adjustment(K, cams, pts, obs, fixed=(0,), tau=1e-3, eta=0.1,
max_cg=None, eps1=1e-10, eps2=1e-12, max_iter=100):
"""Run Levenberg-Marquardt with inexact steps. Returns (cams, pts, info):
info["costs"] holds the cost at the start and after each accepted step,
info["iterations"] the number of steps tried and info["cg"] the number of
CG iterations of each step 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, "cg": []}
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
da, db, its = inexact_newton_step(U, V, W, ga, gb, mu, free, eta, max_cg)
info["cg"].append(its)
delta = [x for i in free for x in da[i]] + [x for d in db for x in d]
size = _dot(delta, 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 = -_dot(g, delta) - 0.5 * quadratic_form(U, V, W, free, da, db)
rho = (f - f_new) / predicted if predicted > 0 else -1.0 # @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_inexact_newton_bundle_adjustment.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inexact-newton-bundle-adjustment/. The authors are listed in prov/HF6T4X.jsonl.
import math
import random
from cvgeom import add_noise, axis_angle_to_R, random_scene
from cvla import inv, mul, solve, transpose
from inexact_newton_bundle_adjustment import (ReducedSystem, build_blocks, cost,
inexact_newton_bundle_adjustment,
inexact_newton_step, observation_blocks,
pcg, project_point, quadratic_form,
reprojection_rms)
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 explicit_s(U, V, W, mu, free):
"""S = U* - W V*^-1 W^T as a dense matrix."""
pos = {i: 6 * k for k, i in enumerate(free)}
n = 6 * len(free)
s = [[0.0] * n for _ in range(n)]
for i in free:
for p in range(6):
for q in range(6):
s[pos[i] + p][pos[i] + q] = U[i][p][q] + (mu if p == q else 0.0)
for j in range(len(V)):
vinv = inv([[V[j][p][q] + (mu if p == q else 0.0) for q in range(3)] for p in range(3)])
for i in free:
for k in free:
if (i, j) in W and (k, j) in W:
blk = mul(mul(W[(i, j)], vinv), transpose(W[(k, j)]))
for p in range(6):
for q in range(6):
s[pos[i] + p][pos[k] + q] -= blk[p][q]
return s
def setup(seed=2, n_cams=4, n_pts=12, mu=2.5):
rng, K, cams, pts, obs = make_problem(seed, n_cams=n_cams, n_pts=n_pts)
cams, pts = perturb(rng, cams, pts)
free = list(range(1, n_cams))
U, V, W, ga, gb = build_blocks(K, cams, pts, obs, free)
return K, cams, pts, obs, free, U, V, W, ga, gb, mu
def test_implicit_product_equals_explicit_schur_complement():
_, _, _, _, free, U, V, W, ga, gb, mu = setup()
system = ReducedSystem(U, V, W, ga, gb, mu, free)
s = explicit_s(U, V, W, mu, free)
rng = random.Random(1)
for _ in range(3):
x = [rng.uniform(-1, 1) for _ in range(system.size)]
y = system.apply(x)
ref = [sum(a * b for a, b in zip(row, x)) for row in s]
scale_ = max(abs(v) for v in ref)
assert max(abs(a - b) for a, b in zip(y, ref)) <= 1e-9 * scale_
blocks = system.block_jacobi()
for k, i in enumerate(free):
d = [row[6 * k:6 * k + 6] for row in s[6 * k:6 * k + 6]]
prod = mul(blocks[i], d)
assert max(abs(prod[p][q] - (1.0 if p == q else 0.0)) for p in range(6) for q in range(6)) < 1e-8
def test_pcg_with_small_tolerance_matches_the_direct_solve():
_, _, _, _, free, U, V, W, ga, gb, mu = setup()
system = ReducedSystem(U, V, W, ga, gb, mu, free)
e = system.rhs()
direct = solve(explicit_s(U, V, W, mu, free), e)
blocks = system.block_jacobi()
x, its = pcg(system.apply, lambda r: system.precondition(blocks, r), e, 1e-12, 10 * system.size)
assert its <= 10 * system.size
size = max(abs(v) for v in direct)
assert max(abs(a - b) for a, b in zip(x, direct)) <= 1e-7 * size
def test_truncated_steps_have_the_stated_predicted_reduction():
K, cams, pts, obs, free, U, V, W, ga, gb, _ = setup(seed=3, n_pts=15)
f0 = cost(K, cams, pts, obs)
g = [x for i in free for x in ga[i]] + [x for d in gb for x in d]
for mu in (1e-2, 1.0, 1e3, 1e6):
for max_cg in (1, 2, 5):
da, db, its = inexact_newton_step(U, V, W, ga, gb, mu, free, eta=1e-14, max_cg=max_cg)
assert its == max_cg
delta = [x for i in free for x in da[i]] + [x for d in db for x in d]
# the linear model L(delta) = 1/2 ||r + J delta||^2, from the observation blocks
model = 0.0
for i, j, u, v in obs:
R, t = cams[i]
p = project_point(K, R, t, pts[j])
a, b = observation_blocks(K, R, t, pts[j])
for k in range(2):
lin = p[k] - (u, v)[k] + sum(b[k][c] * db[j][c] for c in range(3))
if i in da:
lin += sum(a[k][c] * da[i][c] for c in range(6))
model += 0.5 * lin * lin
pred = f0 - model
assert pred > 0
# the code computes pred = -g^T delta - 1/2 ||J delta||^2 from the blocks
jd = quadratic_form(U, V, W, free, da, db)
assert abs(pred - (-sum(x * y for x, y in zip(g, delta)) - 0.5 * jd)) <= 1e-8 * f0
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 = inexact_newton_bundle_adjustment(K, cams0, pts0, obs, eta=0.1)
assert reprojection_rms(K, cams, pts, obs) < 1e-8
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_with_few_cg_iterations():
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 = inexact_newton_bundle_adjustment(K, cams0, pts0, obs, eta=0.5, max_cg=3)
costs = info["costs"]
assert len(costs) > 3
assert all(c1 < c0 for c0, c1 in zip(costs, costs[1:]))
assert all(1 <= c <= 3 for c in info["cg"])
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, _ = inexact_newton_bundle_adjustment(K, cams0, pts0, obs, eta=0.1)
assert cost(K, cams, pts, obs) <= cost(K, cams_true, pts_true, obs)
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
History
Triggs, McLauchlan, Hartley and Fitzgibbon (2000) described the reduced bundle system and the sparse direct methods to solve it. Inexact Newton methods with a forcing sequence were analyzed by Dembo, Eisenstat and Steihaug in 1982. Agarwal, Snavely, Seitz and Szeliski (2010) combined the two for reconstructions from community photo collections with thousands of cameras and millions of points: inexact Levenberg-Marquardt steps, CG on the reduced camera system with the Schur complement applied implicitly, and block preconditioners. In the same year Byröd and Åström studied preconditioned conjugate gradients for bundle adjustment. The iterative Schur approach became a standard solver in open source bundle adjustment software.
References
- Sameer Agarwal, Noah Snavely, Steven M. Seitz and Richard Szeliski, Bundle adjustment in the large, Computer Vision ECCV 2010, Lecture Notes in Computer Science 6312, Springer, 2010, 29-42, the whole paper (inexact step Levenberg-Marquardt, the implicit and explicit Schur complement, the block Jacobi and Schur-Jacobi preconditioners and the experiments)
- Ron S. Dembo, Stanley C. Eisenstat and Trond Steihaug, Inexact Newton methods, SIAM Journal on Numerical Analysis 19(2), 1982, 400-408, the whole paper (the forcing sequence and the local convergence theorems)
- Martin Byröd and Kalle Åström, Conjugate gradient bundle adjustment, Computer Vision ECCV 2010, Lecture Notes in Computer Science 6312, Springer, 2010, the whole paper (preconditioned conjugate gradients on the bundle adjustment least squares problem)
- Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 5 (the conjugate gradient method, Theorems 5.1 and 5.2, preconditioning) and Section 7.1 (inexact Newton methods)
- 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)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HF6T4X Edit this page History Report an error Markdown