Algorithmadvanced
Lie-algebraic rotation averaging
Also called Govindu rotation averaging.
Average rotations by repeated linear least squares on their logarithms in the Lie algebra so(3). Robust versions start from an L1 solution and then run IRLS with a robust cost.
- Solves
- Rotation averaging
- Time
- O(k (E + N^3)) totalO(E + N^3) per_iteration
- Space
- O(E + N^2) extra
- Where
- E = the number of edges of the view graph; N = the number of cameras; k = the number of iterations
- Model
- Real RAM
- Properties
- deterministiciterativelocalnot monotoneiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Venu Madhav Govindu, Avishek Chatterjee, 2004
Lie-algebraic rotation averaging is an iterative algorithm for rotation averaging: given measured relative rotations on the edges of a view graph, it finds absolute rotations that fit them. Rotations do not form a vector space, so the algorithm works in the tangent space, the Lie algebra , which is . At each step it measures the disagreement of each edge as a rotation vector with the logarithm map, solves one linear least squares problem for a small rotation of every camera, which is a system with the graph Laplacian, and applies the small rotations. With unit weights this is the Gauss-Newton method for the squared geodesic cost, as given by Govindu (2004). Chatterjee and Govindu made it robust: they start from an solution and then run iteratively reweighted least squares with a robust cost, which removes the effect of wrong edges. It is the rotation step of many global structure from motion systems.
In plain words
Each camera has an unknown direction, and for many pairs you have measured how much one camera is turned compared with the other. Start with a guess for every camera, for example by chaining the measurements along a tree. For each pair, compute how far the guess is from the measurement, as a small turn. Then ask: what small extra turn of every camera would make all these differences as small as possible together? That question has a straight answer from one set of linear equations, because small turns behave almost like ordinary vectors. Apply the turns and repeat. To stop a few bad measurements from pulling everything, give each pair a weight that gets smaller when its difference is large, and recompute the weights each time.
The problem
Input. A connected graph on the cameras with edges, a measured rotation for each edge , in the convention , a loss (squared, or Geman-McClure), its scale , a floor for the weights, a start (optional), a tolerance and an iteration limit .
Output. Rotations with at a stationary point of
where returns the rotation vector of angle in . The residual is zero when the edge agrees with the estimate, and is the geodesic distance between and . The losses are , and .
Update. Each camera gets a small rotation applied on the right, . Then the residual of the edge becomes , to first order in all three vectors. So the linear model asks for on every edge.
The algorithm
LIE-AVERAGE(G, {R_ij}, loss, σ, δ, ε, k_max)- 1
R <- the start, or the rotations chained from R_1 = I along a breadth-first spanning tree - 2
for it <- 1 to k_max - 3
for each edge (i, j): r_ij <- log(R_j^T R_ij R_i) - 4
w_ij <- 1 (squared), 1 / max(||r_ij||, δ) (L1), or σ² / (||r_ij||² + σ²)² (Geman-McClure) - 5
solve L ω = b with ω_1 = 0, where L is the weighted graph Laplacian without row and column 1, and b_k = Σ_(i,k) w_ik r_ik - Σ_(k,j) w_kj r_kj - 6
for each camera k: R_k <- R_k exp([ω_k]_x) - 7
if max_k ||ω_k|| < ε then stop - 8
return R
Line L1 gives a start that fits the tree edges exactly. Lines L3 and L4 compute the residuals and the weights of iteratively reweighted least squares: the weight of the loss, up to a constant factor. Line L5 is the normal equation of with . Its matrix is the same Laplacian for the three coordinates of , so one factorization serves three right-hand sides. Line L6 applies the step on the right, which matches the linear model. The robust run of Chatterjee and Govindu is LIE-AVERAGE with the loss from the tree start, followed by LIE-AVERAGE with a robust loss from its result. The reference code runs 30 iterations of each, with Geman-McClure as the robust loss.
Example
Take three cameras and rotations about the axis: by , by and by . The cycle does not close: degrees. Write for the angle of .
- Start (line L1). The breadth-first tree from camera 1 uses the edges and , so and . The residual of the edge is degrees, and the other two residuals are 0.
- Squared loss. All rotations share one axis, so they commute, the linear model is exact, and line L5 solves , (in degrees): , . After one step, and , each edge has a residual of in size, and the cost drops from to square degrees ( rad squared). The second iteration finds and stops.
- loss. From the start, the two exact edges get the weight and the third gets , so the solve keeps the exact edges almost fixed, and the iteration stays within degrees of the start. The start is one of the minimizers, with the cost rad, but the whole error sits on one edge.
- Geman-McClure loss, rad. All residuals are small compared with , so the loss behaves like the squared loss, and the run ends at , after 13 iterations.
The reference code gives these numbers. On a larger test with 15 cameras and 62 edges, with rad of noise and about 15% of the edges replaced by random rotations, the squared loss ends with a largest relative rotation error of rad, worse than the tree start, and the robust run ends with rad (a benchmark result on this test).
Correctness
The update is exact to first order: for the squared loss, line L5 solves the Gauss-Newton system of in the local coordinates (theorem). The gradient of with respect to at is exactly , because the derivative of along a small rotation is (theorem). The grounded Laplacian of a connected graph with positive weights is positive definite, so line L5 has a unique solution, and is a descent direction whenever (theorem). The solution is if and only if , which is the stationarity condition, so a stop at line L7 with means a stationary point (theorem). On exact data, the tree start already has all residuals 0, so the algorithm returns the true rotations up to the gauge after one iteration (theorem). The full step has no line search, so the cost need not decrease at every step; in practice it does from a good start (heuristic). The proof file below gives the details.
Proof: The Lie-algebraic update is a well defined descent step that stops exactly at stationary points, and the tree start is exact on consistent datafull
We use the notation of the page. The graph is connected, with cameras . For an edge the residual is , and the cost with the squared loss is . The update is with . Line L5 solves , where is the weighted graph Laplacian with row and column 1 removed, applied to each coordinate of , and . All angles of the residuals are below , so the logarithm is smooth at every residual.
Claim. (a) The grounded Laplacian is positive definite when all weights are positive, so line L5 has exactly one solution. (b) With unit weights, the gradient of with respect to at is , and line L5 is the Gauss-Newton step of . (c) If , the step of line L5 is a descent direction of , and if and only if , which holds if and only if is a stationary point of . The same holds for the reweighted cost with the weights fixed. (d) If the edges are exact, , then the tree start of line L1 has all residuals equal to 0, and the algorithm returns , the true rotations up to the gauge.
Proof of (a). For a vector , the weighted Laplacian satisfies . The grounded matrix is restricted to the vectors with . Let and . Every weight is positive, so on every edge. The graph is connected, so is constant, and gives . So is positive definite and invertible.
Proof of (b). Fix an edge and put , so . After the update, the residual is . We use one fact about : for a rotation with angle below and a small rotation vector , , and . To see it, write . The squared geodesic distance has the Riemannian gradient at , in the body frame of the right action and also in the space frame of the left action, because is fixed by : , as is the axis of . So both directional derivatives along are .
Apply this with on the right and on the left. To first order, the residual norm squared is . Summing over the edges, the coefficient of is with unit weights. So .
The same first order expansion of the residual vector itself is with . Gauss-Newton replaces each residual by its linear model. The page uses the model with , the form of Govindu (2004): with . Setting the derivative with respect to , , to zero gives , which is row of . So line L5 solves the linear least squares problem of the model, and its right side is exactly times the true gradient.
Proof of (c). By (a), . The directional derivative of along is , where the sum and the products run over the cameras and the three coordinates. The matrix is positive definite, so this value is negative when . So is a descent direction. Since is invertible, exactly when . The gauge fixes , and does not change when all rotations are multiplied on the right by one rotation, so the gradient with respect to is minus the sum of the other gradients; hence the full gradient is zero if and only if for all . So is the stationarity condition. With fixed positive weights , every step above holds with as a factor in each sum, and is the weighted Laplacian.
Proof of (d). Line L1 chains the rotations along a spanning tree from , setting for each tree edge from the parent to the child . By induction on the depth, : this holds for the root, and if it holds for , then . Then for every edge , tree edge or not, , so . Then , line L5 gives by (a), and line L7 stops in the first iteration with the start unchanged. Every loss gives a finite positive weight at , with the floor for the weight, so this holds for all three losses.
Complexity
In the real RAM model, line L3 costs : one logarithm and two products per edge. Line L5 assembles the Laplacian in and solves it. The reference code uses a dense solve, per iteration. The Laplacian has one nonzero block per edge, so a sparse Cholesky factorization with a fill-reducing order, or the conjugate gradient method, makes the solve close to linear in for the view graphs of SfM. Line L6 costs . So one iteration costs dense or about sparse, and iterations cost times that. The squared loss usually stops in a handful of iterations; the reweighted runs need tens. The space is for the residuals plus the space of the solver, dense.
Properties
- Local (theorem). The method converges to a stationary point near its start, not to the global minimum. A good start, such as a maximum spanning tree on the inlier counts, matters.
- Not monotone. There is no line search, so a step can raise the cost far from a minimum. A damping term with a test that rejects steps which raise the cost, as in Levenberg-Marquardt, makes it monotone.
- Gauge. Fixing removes the gauge. Without it the Laplacian is singular, with the constant vector in its null space.
- Exact on exact data (theorem). A consistent set of edges is fitted exactly.
- Robustness. The start is less affected by wrong edges than the squared loss, and the bounded Geman-McClure weights almost ignore edges with large residuals. Both are heuristics with good benchmark results, not guarantees.
Variants and improvements
- Chordal and quaternion costs. The same scheme works with other distances; the chordal cost leads to the linear relaxation of Martinec and Pajdla (2007).
- by linear programming. Chatterjee and Govindu (2013) solve the problem in the Lie algebra with a linear solver for problems, then refine with reweighted least squares. The reference code solves the part by reweighting too, which is simpler but can stall at the start, as in the example.
- Weiszfeld iterations. Hartley, Aftab and Trumpf (2011) update one rotation at a time towards the geodesic median of its neighbors.
- Certifiable methods. The semidefinite relaxation of the chordal cost, solved directly or by Shonan averaging, gives a certificate of global optimality when it is tight.
- Pose averaging. The same linearization on averages full motions, as in pose graph optimization.
When to use it
Use it for the rotation step of global SfM, and for any rotation averaging problem on a sparse graph with a decent start. Use the robust form whenever the edges come from two-view geometry, since some of them are always wrong. If a certificate of global optimality is needed, use a semidefinite method such as SE-Sync on the chordal cost. If the graph is a chain with few loops, there is little to average, and the result is close to the chained start.
Pitfalls
- Left and right updates. The step must match the residual. With , the linear model is . With a left update or another residual, the signs or the frames of change.
- Angles near . The logarithm is not smooth at angle , and its axis is ambiguous there. Residuals that large mean a wrong edge or a bad start; a robust loss limits their effect.
- The weight floor. With weights , an edge with a zero residual gets an infinite weight. The floor prevents a division by zero, but large weights freeze the start, as the example shows.
- Disconnected graphs. The grounded Laplacian is singular if the graph is not connected. Check the components of the view graph first; the reference code raises an error.
- Units of . The Geman-McClure scale is an angle in radians. Too small a value treats good edges as outliers, and too large a value gives the squared loss.
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/.
"""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()
lie_algebraic_rotation_averaging.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lie-algebraic-rotation-averaging/. The authors are listed in prov/XFRXH0.jsonl.
"""Lie-algebraic rotation averaging (Govindu; Chatterjee and Govindu).
There are N absolute rotations R_0, ..., R_(N-1) to find and a list of
edges (i, j, R_ij), each a measurement of the relative rotation
R_ij ~ R_j R_i^T. The residual of an edge is the rotation vector
r_ij = log(R_j^T R_ij R_i), which is zero when the edge agrees with the
estimate. Each iteration linearizes r_ij - w_j + w_i for the update
R_k <- R_k exp([w_k]_x), solves the weighted least squares problem in the
w_k (a graph Laplacian system with w_0 = 0) and applies the update.
The weights give the cost: "l2" weights 1 (the squared geodesic cost),
"l1" weights 1 / max(||r||, delta) (the sum of geodesic distances, by
iteratively reweighted least squares) and "gm" weights
sigma^2 / (||r||^2 + sigma^2)^2 (the Geman-McClure cost).
"""
import math
from collections import deque
from typing import Dict, List, Sequence, Tuple
from cvla import mul, solve, transpose
Vector = List[float]
Matrix = List[List[float]]
Edge = Tuple[int, int, Matrix]
def so3_exp(w: Sequence[float]) -> Matrix:
"""exp([w]_x) by the Rodrigues formula."""
th = math.sqrt(w[0] * w[0] + w[1] * w[1] + w[2] * w[2])
if th < 1e-8:
a, b = 1.0 - th * th / 6.0, 0.5 - th * th / 24.0
else:
a, b = math.sin(th) / th, (1.0 - math.cos(th)) / (th * th)
x, y, z = w
k = [[0.0, -z, y], [z, 0.0, -x], [-y, x, 0.0]]
k2 = mul(k, k)
return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]
def so3_log(r: Sequence[Sequence[float]]) -> Vector:
"""The rotation vector w with exp([w]_x) = R and ||w|| <= pi."""
c = max(-1.0, min(1.0, (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0))
v = [r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]]
th = math.acos(c)
if th < 1e-6:
return [x * (0.5 + th * th / 12.0) for x in v]
if th < math.pi - 1e-4:
return [x * th / (2.0 * math.sin(th)) for x in v]
# near pi: (R + R^T)/2 - cos(th) I = (1 - cos(th)) a a^T
b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
k = max(range(3), key=lambda i: b[i][i])
col = [b[i][k] for i in range(3)]
nc = math.sqrt(sum(x * x for x in col))
a = [x / nc for x in col]
if sum(x * y for x, y in zip(a, v)) < 0:
a = [-x for x in a]
return [th * x for x in a]
def angle(r1: Sequence[Sequence[float]], r2: Sequence[Sequence[float]]) -> float:
"""The angle of R1^T R2, in radians."""
tr = sum(r1[k][i] * r2[k][i] for i in range(3) for k in range(3))
return math.acos(max(-1.0, min(1.0, (tr - 1.0) / 2.0)))
def residual(rots: Sequence[Matrix], e: Edge) -> Vector:
"""r_ij = log(R_j^T R_ij R_i)."""
i, j, rij = e
return so3_log(mul(mul(transpose(rots[j]), rij), rots[i]))
def tree_init(n: int, edges: Sequence[Edge], root: int = 0) -> List[Matrix]:
"""Rotations from a breadth-first spanning tree: R_root = I and
R_j = R_ij R_i along tree edges. Raises ValueError if the graph is not
connected."""
adj: Dict[int, List[Tuple[int, Matrix]]] = {k: [] for k in range(n)}
for i, j, rij in edges:
adj[i].append((j, rij))
adj[j].append((i, transpose(rij)))
rots: List = [None] * n
rots[root] = [[1.0 if a == b else 0.0 for b in range(3)] for a in range(3)]
queue = deque([root])
while queue:
i = queue.popleft()
for j, rij in adj[i]:
if rots[j] is None:
rots[j] = mul(rij, rots[i])
queue.append(j)
if any(r is None for r in rots):
raise ValueError("tree_init: the view graph is not connected")
return rots
def weight(rnorm: float, loss: str, sigma: float, delta: float) -> float:
"""The IRLS weight psi(||r||) / ||r|| of a residual norm."""
if loss == "l2":
return 1.0
if loss == "l1":
return 1.0 / max(rnorm, delta)
if loss == "gm":
return sigma * sigma / (rnorm * rnorm + sigma * sigma) ** 2
raise ValueError("unknown loss " + loss)
def laplacian_system(n: int, edges: Sequence[Edge], res: Sequence[Vector],
wts: Sequence[float]) -> Tuple[Matrix, Matrix]:
"""The grounded weighted Laplacian (node 0 removed) and the right-hand
sides b_k = sum over edges (i, k) of w r - sum over edges (k, j) of w r."""
lap = [[0.0] * n for _ in range(n)]
b = [[0.0] * 3 for _ in range(n)]
for (i, j, _), r, w in zip(edges, res, wts):
lap[i][i] += w
lap[j][j] += w
lap[i][j] -= w
lap[j][i] -= w
for a in range(3):
b[j][a] += w * r[a]
b[i][a] -= w * r[a]
return [row[1:] for row in lap[1:]], b[1:]
def lie_algebraic_rotation_averaging(n: int, edges: Sequence[Edge], loss: str = "l2",
init: Sequence[Matrix] = None, sigma: float = 0.1,
delta: float = 1e-6, max_iter: int = 100,
eps: float = 1e-12) -> Tuple[List[Matrix], int]:
"""Average the relative rotations. Returns (R, iterations); R_0 = I
unless init says otherwise."""
rots = [list(map(list, r)) for r in init] if init is not None else tree_init(n, edges) # @line L1
it = 0
for it in range(1, max_iter + 1): # @line L2
res = [residual(rots, e) for e in edges] # @line L3
wts = [weight(math.sqrt(sum(x * x for x in r)), loss, sigma, delta) for r in res] # @line L4
lap, b = laplacian_system(n, edges, res, wts) # @line L5
omega = [[0.0, 0.0, 0.0]] + solve(lap, b)
rots = [mul(r, so3_exp(w)) for r, w in zip(rots, omega)] # @line L6
if max(math.sqrt(sum(x * x for x in w)) for w in omega) < eps: # @line L7
break
return rots, it # @line L8
def robust_rotation_averaging(n: int, edges: Sequence[Edge], sigma: float = 0.1,
l1_iter: int = 30, gm_iter: int = 30) -> List[Matrix]:
"""A robust run in the style of Chatterjee and Govindu: a few l1
iterations from the tree start, then Geman-McClure iterations."""
rots, _ = lie_algebraic_rotation_averaging(n, edges, loss="l1", max_iter=l1_iter, eps=1e-9)
rots, _ = lie_algebraic_rotation_averaging(n, edges, loss="gm", init=rots, sigma=sigma,
max_iter=gm_iter, eps=1e-10)
return rots
def cost(rots: Sequence[Matrix], edges: Sequence[Edge], loss: str = "l2",
sigma: float = 0.1) -> float:
"""sum ||r||^2 (l2), sum ||r|| (l1) or sum ||r||^2 / (||r||^2 + sigma^2) (gm)."""
total = 0.0
for e in edges:
r = residual(rots, e)
s = sum(x * x for x in r)
if loss == "l2":
total += s
elif loss == "l1":
total += math.sqrt(s)
else:
total += s / (s + sigma * sigma)
return total
test_lie_algebraic_rotation_averaging.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lie-algebraic-rotation-averaging/. The authors are listed in prov/XFRXH0.jsonl.
import math
import random
import pytest
from cvla import mul, transpose
from lie_algebraic_rotation_averaging import (angle, cost, laplacian_system,
lie_algebraic_rotation_averaging, residual,
robust_rotation_averaging, so3_exp, so3_log,
tree_init)
def random_rot(rng):
w = [rng.gauss(0, 1) for _ in range(3)]
n = math.sqrt(sum(x * x for x in w))
return so3_exp([x / n * rng.uniform(0, math.pi) for x in w])
def make_problem(seed, n=12, p=0.5, noise=0.0, outliers=0.0):
rng = random.Random(seed)
rots = [random_rot(rng) for _ in range(n)]
edges = [(k, k + 1) for k in range(n - 1)]
edges += [(i, j) for i in range(n) for j in range(i + 2, n) if rng.random() < p]
out = []
for i, j in edges:
rij = mul(rots[j], transpose(rots[i]))
if rng.random() < outliers:
rij = random_rot(rng)
elif noise > 0:
rij = mul(so3_exp([rng.gauss(0, noise) for _ in range(3)]), rij)
out.append((i, j, rij))
return rots, out
def relative_error(est, true):
"""The largest angle between R_j R_i^T of the estimate and of the truth."""
worst = 0.0
for i in range(len(true)):
for j in range(i + 1, len(true)):
a = mul(est[j], transpose(est[i]))
b = mul(true[j], transpose(true[i]))
worst = max(worst, angle(a, b))
return worst
def test_exp_and_log_are_inverse():
rng = random.Random(1)
for _ in range(50):
w = [rng.gauss(0, 1) for _ in range(3)]
n = math.sqrt(sum(x * x for x in w))
th = rng.uniform(0, math.pi - 1e-3)
w = [x / n * th for x in w]
assert max(abs(a - b) for a, b in zip(so3_log(so3_exp(w)), w)) < 1e-8
w = [0.0, math.pi - 1e-6, 0.0]
assert max(abs(a - b) for a, b in zip(so3_log(so3_exp(w)), w)) < 1e-5
def test_exact_data_is_recovered_up_to_the_gauge():
true, edges = make_problem(2)
est, it = lie_algebraic_rotation_averaging(len(true), edges)
# acos near 1 limits the angle to about 1e-8
assert relative_error(est, true) < 1e-7
assert it <= 2
def test_gradient_is_minus_two_b():
true, edges = make_problem(3, n=6, noise=0.2)
rots = tree_init(6, edges)
res = [residual(rots, e) for e in edges]
_, b = laplacian_system(6, edges, res, [1.0] * len(edges))
h = 1e-6
for k in range(1, 6):
for a in range(3):
d = [0.0, 0.0, 0.0]
d[a] = h
plus = [mul(r, so3_exp(d)) if m == k else r for m, r in enumerate(rots)]
d[a] = -h
minus = [mul(r, so3_exp(d)) if m == k else r for m, r in enumerate(rots)]
fd = (cost(plus, edges) - cost(minus, edges)) / (2 * h)
assert abs(fd + 2 * b[k - 1][a]) < 1e-5
def test_l2_reaches_a_stationary_point_below_the_tree_start():
true, edges = make_problem(4, n=15, noise=0.05)
start = tree_init(15, edges)
est, it = lie_algebraic_rotation_averaging(15, edges, max_iter=50, eps=1e-11)
assert it < 50
assert cost(est, edges) < cost(start, edges)
res = [residual(est, e) for e in edges]
_, b = laplacian_system(15, edges, res, [1.0] * len(edges))
assert max(abs(x) for row in b for x in row) < 1e-9
assert relative_error(est, true) < 0.15
def test_robust_cost_handles_outliers():
true, edges = make_problem(5, n=15, p=0.6, noise=0.01, outliers=0.15)
l2, _ = lie_algebraic_rotation_averaging(15, edges, max_iter=50)
robust = robust_rotation_averaging(15, edges, sigma=0.05)
assert relative_error(robust, true) < 0.1
assert relative_error(l2, true) > 3 * relative_error(robust, true)
def test_disconnected_graph_is_rejected():
_, edges = make_problem(6, n=5)
with pytest.raises(ValueError):
tree_init(7, edges)
History
Govindu (2001) combined the relative motions of many image pairs into consistent global motions, and in 2004 he formulated the averaging in the Lie algebra and gave the iterative scheme on this page, for rotations and for full motions. Martinec and Pajdla (2007) proposed a linear method for the rotations based on the chordal distance. Hartley, Aftab and Trumpf (2011) gave the Weiszfeld method for averaging, and Hartley, Trumpf, Dai and Li (2013) surveyed the field. Chatterjee and Govindu (2013) combined an start with reweighted least squares for large scale robust averaging, and extended the analysis of the robust costs in their 2018 journal paper.
References
- Venu Madhav Govindu, Lie-algebraic averaging for globally consistent motion estimation, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2004), vol. 1, 684-691, the whole paper (the averaging of relative motions in the Lie algebra, the linear update and the iteration)
- Venu Madhav Govindu, Combining two-view constraints for motion estimation, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2001), vol. 2, 218-225, the averaging of relative rotations over a graph of views
- Avishek Chatterjee and Venu Madhav Govindu, Efficient and robust large-scale rotation averaging, IEEE International Conference on Computer Vision (ICCV 2013), 521-528, the whole paper (the L1 averaging in the Lie algebra and the reweighted refinement)
- Avishek Chatterjee and Venu Madhav Govindu, Robust relative rotation averaging, IEEE Transactions on Pattern Analysis and Machine Intelligence 40(4), 2018, 958-972, the robust cost functions, the iteratively reweighted least squares method and the experiments
- Richard Hartley, Jochen Trumpf, Yuchao Dai and Hongdong Li, Rotation averaging, International Journal of Computer Vision 103(3), 2013, 267-305, the sections on the Lie-algebraic and the L1 methods for multiple rotation averaging
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 XFRXH0 Edit this page History Report an error Markdown