Algorithmadvanced
Inverse compositional image alignment
Also called Baker-Matthews alignment, inverse compositional Lucas-Kanade.
Align a template to an image by Gauss-Newton steps that warp the template, so the Hessian is computed once, and compose the inverse of each step into the warp.
- Solves
- Image registration
- Time
- Θ(n^2 m + N (n m + n^3)) worst · averageΘ(n^2 m + n^3) best
- Space
- Θ(n m + n^2) extra
- Where
- N = the number of iterations; m = the number of template pixels; n = the number of warp parameters (6 for an affine warp)
- Model
- Real RAM
- Properties
- deterministicnot exactiterativelocal
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Simon Baker, Iain Matthews, 2001
Inverse compositional alignment finds the parameters of a warp that make the image , warped back, match a template : it minimizes over the template pixels, as the Lucas-Kanade method does. The difference is the roles of the two images in each Gauss-Newton step. The step finds a small warp of the template, , so that matches the current , and then composes the inverse of that small warp into . Because the linearization is always at the template and at , the steepest descent images and the Hessian do not change between iterations: they are computed once, and each iteration costs only one warp of the image and more operations. Baker and Matthews showed that, to first order, the step gives the same update as the classic additive and compositional steps. The method needs warps that form a group, such as translations, affine maps and homographies.
In plain words
You have a small picture, the template, and a large picture that contains a moved and distorted copy of it. You want the stretch and shift that lines them up. The usual way makes a guess, warps the large picture by the guess, compares it with the template, and computes a correction from the slopes of the large picture at the warped places. Those slopes change at every guess, so the costly part of the work is redone. The inverse compositional way asks the opposite question: how should the template move to look like the warped picture? The slopes of the template never change, so the hard part is done once, before the loop. The answer is then undone on the guess: if the template should move a little to the right, the guess moves a little to the left. Near the answer, both ways make the same step.
The problem
The input is a template given on a set of pixels, an image , a warp family with parameters, a start , an iteration limit and a tolerance . Points use the convention of the vision pages: pixel is , with its center at the point . Off-grid values come from bilinear interpolation. The output is the that minimizes
a nonlinear least-squares problem. The warps must form a group: , the composition of two warps of the family is a warp of the family, and each warp has an inverse in the family. The code on this page uses the affine warp in the parameterization of Baker and Matthews,
where is the same warp in homogeneous coordinates. Composition of warps is the product of the matrices.
The algorithm
IC-ALIGN(T, Ω, I, p, k, τ)- 1
for each x in Ω do compute ∇T(x) ▷ central differences of T - 2
for each x in Ω do compute ∂W/∂p at (x; 0) ▷ a 2 × n matrix - 3
for each x in Ω do S(x) ← ∇T(x)ᵀ ∂W/∂p(x; 0) ▷ steepest descent image, 1 × n - 4
H ← Σ_{x ∈ Ω} S(x)ᵀ S(x) ▷ n × n, fixed from now on - 5
repeat up to k times - 6
for each x in Ω do e(x) ← I(W(x; p)) - T(x) - 7
g ← Σ_{x ∈ Ω} S(x)ᵀ e(x) - 8
Δp ← H⁻¹ g - 9
W(·; p) ← W(·; p) ∘ W(·; Δp)⁻¹ ▷ A(p) ← A(p) A(Δp)⁻¹ - 10
if |Δp| < τ then return p - 11
return p
Lines L1 to L4 are the precomputation. Lines L6 to L10 are the loop, and only line L6 reads the image. For the affine warp, at is
so , with . Line L8 solves a system. For a translation, , line L9 is , and the algorithm is the tracking step of the Kanade-Lucas-Tomasi tracker.
The forwards additive algorithm, for comparison. Lucas and Kanade linearize at the current . Each step needs at the warped points , new steepest descent images and a new Hessian, then sets . That is per iteration instead of .
Example
One dimension by hand. Let on the pixels , and let the image be , so the true warp is the translation : . The central differences of are , and , so and , once. From :
| Step | new | ||||
|---|---|---|---|---|---|
| 1 | |||||
| 2 | |||||
| 3 | |||||
| 4 | to 15 digits |
The error is squared at each step, up to a factor of about 0.21: the residual at the answer is zero, and the central difference of a quadratic is its exact derivative.
An affine warp. The template is a texture of 12 Gaussian blobs (seeded, widths 2.5 to 4.5 pixels), and is the block , so and . The image is the texture warped so that with . From , the cost goes 643132, 101084, 1623.6, 122.7, 120.06 and then stays at 120.11 after 9 steps. The result moves every point of to within 0.031 pixel of its true place. The cost cannot reach zero, because the image is sampled and the template gradient is a central difference, so the last steps move the cost by about 0.05 in either direction. The forwards additive algorithm on the same data ends within 0.0004 pixel of the inverse compositional result, with a new Hessian at every step.
A whole-pixel shift. With , every sample falls on a pixel, so the cost at is exactly zero. The cost goes from to in 10 steps, and all six parameters are within of .
Correctness
The full proof is in proofs/correctness.md. It shows four facts.
- The step solves the linearized problem. Line L8 minimizes , the first-order form of . If the steepest descent images are linearly independent as functions on , is positive definite and the step is unique.
- The update stays in the family. Line L9 is the matrix product , which is affine with last row ; so the update is exact and the result has a parameter vector.
- An exact alignment is a fixed point. If for all , then , and does not change.
- Local convergence. If is continuously differentiable and on an open set around the template, then the warp error after one step is of the error before it, so from every start close enough to the iteration converges to , faster than any fixed linear rate. The proof writes the current warp as and shows that the step equals to first order.
Baker and Matthews prove, also to first order, that the inverse compositional and forwards compositional updates are the same warp, and that both agree with the forwards additive update. This equivalence is a first-order statement. It does not say that the iterations follow the same path, and it gives no global convergence: a start far from can converge to another local minimum.
Proof: The inverse compositional step solves the linearized problem, stays in the warp group, fixes an exact alignment, and converges superlinearly near a zero-residual solutionfull
Notation as on the page: is the set of template pixels, is the steepest descent image of line L3, , and . We work with the affine warp, , and write , which is the matrix with the entries of in its first two rows and zeros in its last row. The map is linear and one to one, so and are equivalent norms: there are constants with .
Claim 1: the step solves the linearized problem
The step asks for the small warp of the template that best matches the current warped image:
Since , the chain rule gives . Dropping the remainder gives
which is line L7. For any and , , and . So every solution of minimizes , and at a minimizer the gradient vanishes. If the functions on are linearly independent, then for all forces , so for : is positive definite, and of line L8 is the unique minimizer. depends only on and , so lines L1 to L4 can compute it once.
Claim 2: the update stays in the family
has last row and is invertible when , which holds for small. The inverse of a matrix with last row has last row , and so does a product of two such matrices. So for exactly one , read from its first two rows. The action of a product of homogeneous matrices on is the composition of the actions, so .
Claim 3: an exact alignment is a fixed point
If for every , then at line L6 gives , line L7 gives , and line L8 gives . Then , so does not change, and line L10 stops.
Claim 4: local superlinear convergence
Hypotheses. is continuously differentiable on the plane; is positive definite; and there is an open set with for all . (On sampled images this holds only approximately; the claim describes the smooth model.)
Error coordinates. For near , define by , that is . This is affine with last row , so exists, it depends continuously on , and exactly when . The warp error is .
The residual. . For small, for every ( is finite and is open), so
by the chain rule at (as in Claim 1).
The step. By line L8, . So with . In particular for small.
The new error. The new warp is , so the new error has . Write and . For the Neumann series gives with . Then
So . With and , , and . By the norm equivalence, .
Conclusion. There is such that implies , and all the conditions used above hold. By induction, a start with gives , so by the continuity of . Since and , the ratio tends to 0: the convergence is superlinear.
What is not claimed
The claims say nothing about starts far from , where the iteration can converge to another stationary point or leave the image. The cost is not proved to decrease at every step: the step minimizes a linearization at the template, not the true cost, and the plain algorithm has no test before it accepts a step. The first-order equivalence of Baker and Matthews with the forwards additive and forwards compositional updates is their result; Claim 4 uses a similar first-order expansion, but it is a separate statement about the inverse compositional iteration alone.
Complexity
- Precomputation. Lines L1 to L3 cost . Line L4 forms sums of terms, .
- One iteration. Line L6 is warps and bilinear samples, for a warp with parameters. Line L7 is , line L8 is by elimination (or with a factorization of stored once), and line L9 is for a matrix.
- Total. for iterations, in the real RAM. The forwards additive algorithm costs . With and , the per-iteration sums drop from about products to about .
- Space. for the steepest descent images and for .
Properties
- Fixed Hessian. The Gauss-Newton matrix is evaluated once, at the template. This is the source of the speed, and it also means the step uses the template gradient, not the image gradient at the current warp.
- Same first-order step. Near the solution, the update matches the forwards additive and forwards compositional updates.
- Group warps only. The algorithm needs the inverse of and a composition that stays in the family.
- No step control. The plain algorithm accepts every step. Near the noise floor the cost can rise slightly, as in the affine example; far from the solution it can diverge.
- Deterministic and local. The result depends only on the start and the pixels near the warped template.
Variants and improvements
- Other warp groups. Translations, similarities, affine maps and homographies (8 parameters, with a general matrix) all form groups.
- Robust and weighted errors. Reweight to reduce the effect of outliers. A weight that changes per iteration makes change too, so the saving is partly lost unless the weights are approximated by fixed ones.
- Linear appearance change. Add a linear model of brightness change (for example, gain and bias, or a few basis images). Projecting the error out of the appearance subspace keeps a fixed Hessian.
- Levenberg-Marquardt. Add a damping term to and test the cost before accepting a step, as in Levenberg-Marquardt.
- Coarse to fine. Run the algorithm on an image pyramid to widen the range of convergence.
- Direct visual odometry. The same structure, a fixed Jacobian at a reference frame and composed updates of a camera pose, appears in direct image alignment with a photometric error.
When to use it
Use it to align or track a fixed template (a planar patch, a face model, a reference image) through many images or frames, where the template does not change but the image does. The precomputation is paid once and each frame costs only a few image warps. Use the forwards additive form when the template changes at every frame, when the warp family is not a group, or when each step needs a different weight per pixel.
Pitfalls
- Additive update of a compositional step. Adding to is right for a translation only. For an affine warp, the update must be the matrix product of line L9; the additive form gives a wrong warp off the identity.
- Order of composition. The update is , applied first to the template coordinates. Composing in the other order gives the right answer only for commuting warps such as translations.
- Template gradient on the border. Central differences need one pixel around . Take the gradient from the full template image, or shrink .
- Region coordinates. The parameters to multiply the coordinates, so a template far from the origin couples the linear part with the translation and conditions badly. Put the origin of the template coordinates at its center, or scale them.
- Large motion. The start must be inside the range of the linearization, about the size of the smallest structures in the template; use a pyramid or a coarse search first.
- Noise and the floor. With noise or sampling error, the cost has a floor, and a test on the change of the cost may never stop the loop. Test the size of , with a limit on the number of iterations.
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()
inverse_compositional_alignment.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inverse-compositional-alignment/. The authors are listed in prov/ZVVMQX.jsonl.
"""Inverse compositional image alignment (Baker and Matthews) for an affine
warp, with the forwards additive Lucas-Kanade algorithm as a reference.
Images are lists of rows, indexed img[v][u]; the center of pixel (u, v) is
the point (u, v). The template T is an image and the region is a list of
integer points (u, v) of T, each at least one pixel inside T. The affine warp
has the parameters p = (p1, ..., p6) of Baker and Matthews:
W(x; p) = ((1 + p1) u + p3 v + p5, p2 u + (1 + p4) v + p6),
so p = 0 is the identity. The goal is the p that minimizes
sum over the region of (I(W(x; p)) - T(x))^2.
"""
import math
from cvla import inv, mul, solve
def sample(img, u, v):
"""Bilinear sample at the real point (u, v), indices clamped."""
h, w = len(img), len(img[0])
u0, v0 = math.floor(u), math.floor(v)
fu, fv = u - u0, v - v0
def at(vv, uu):
return img[min(max(vv, 0), h - 1)][min(max(uu, 0), w - 1)]
top = (1 - fu) * at(v0, u0) + fu * at(v0, u0 + 1)
bottom = (1 - fu) * at(v0 + 1, u0) + fu * at(v0 + 1, u0 + 1)
return (1 - fv) * top + fv * bottom
def warp_matrix(p):
"""The 3 x 3 matrix of W(.; p) in homogeneous coordinates."""
return [[1 + p[0], p[2], p[4]], [p[1], 1 + p[3], p[5]], [0.0, 0.0, 1.0]]
def params(a):
"""The parameters p of an affine 3 x 3 matrix (last row 0, 0, 1)."""
return [a[0][0] - 1, a[1][0], a[0][1], a[1][1] - 1, a[0][2], a[1][2]]
def warp(p, u, v):
"""The point W((u, v); p)."""
return ((1 + p[0]) * u + p[2] * v + p[4], p[1] * u + (1 + p[3]) * v + p[5])
def warp_jacobian(u, v):
"""dW/dp at (u, v): a 2 x 6 matrix, the same for every p."""
return [[u, 0.0, v, 0.0, 1.0, 0.0], [0.0, u, 0.0, v, 0.0, 1.0]]
def compose_inverse(p, dp):
"""The parameters of W(.; p) composed with the inverse of W(.; dp)."""
return params(mul(warp_matrix(p), inv(warp_matrix(dp))))
def cost(t, region, img, p):
"""The sum of squared differences of the problem."""
return sum((sample(img, *warp(p, u, v)) - t[v][u]) ** 2 for u, v in region)
def precompute(t, region):
"""Steepest descent images S(x) = grad T(x) dW/dp(x; 0) and the Hessian
H = sum S(x)^T S(x). The gradient is the central difference of T."""
sd = []
for u, v in region:
gu = (t[v][u + 1] - t[v][u - 1]) / 2 # @line L1
gv = (t[v + 1][u] - t[v - 1][u]) / 2
jac = warp_jacobian(u, v) # @line L2
sd.append([gu * jac[0][i] + gv * jac[1][i] for i in range(6)]) # @line L3
hess = [[sum(s[i] * s[j] for s in sd) for j in range(6)] for i in range(6)] # @line L4
return sd, hess
def ic_align(t, region, img, p0=None, iters=100, tol=1e-8):
"""Inverse compositional alignment. Returns (p, costs), where costs[j] is
the cost before step j. Raises ValueError if the Hessian is singular."""
p = list(p0) if p0 is not None else [0.0] * 6
sd, hess = precompute(t, region)
costs = []
for _ in range(iters): # @line L5
err = [sample(img, *warp(p, u, v)) - t[v][u] for u, v in region] # @line L6
costs.append(sum(e * e for e in err))
g = [sum(s[i] * e for s, e in zip(sd, err)) for i in range(6)] # @line L7
dp = solve(hess, g) # @line L8
p = compose_inverse(p, dp) # @line L9
if math.sqrt(sum(x * x for x in dp)) < tol: # @line L10
break
costs.append(cost(t, region, img, p))
return p, costs # @line L11
def fa_align(t, region, img, p0=None, iters=100, tol=1e-8):
"""Forwards additive Lucas-Kanade, the reference: the gradient of the
image at the warped points and a new Hessian at every step."""
p = list(p0) if p0 is not None else [0.0] * 6
for _ in range(iters):
sd, err = [], []
for u, v in region:
wu, wv = warp(p, u, v)
gu = (sample(img, wu + 1, wv) - sample(img, wu - 1, wv)) / 2
gv = (sample(img, wu, wv + 1) - sample(img, wu, wv - 1)) / 2
jac = warp_jacobian(u, v)
sd.append([gu * jac[0][i] + gv * jac[1][i] for i in range(6)])
err.append(t[v][u] - sample(img, wu, wv))
hess = [[sum(s[i] * s[j] for s in sd) for j in range(6)] for i in range(6)]
g = [sum(s[i] * e for s, e in zip(sd, err)) for i in range(6)]
dp = solve(hess, g)
p = [a + b for a, b in zip(p, dp)]
if math.sqrt(sum(x * x for x in dp)) < tol:
break
return p
test_inverse_compositional_alignment.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inverse-compositional-alignment/. The authors are listed in prov/ZVVMQX.jsonl.
import math
import random
import pytest
from cvla import inv
from inverse_compositional_alignment import (
compose_inverse,
fa_align,
ic_align,
params,
precompute,
sample,
warp,
warp_jacobian,
warp_matrix,
)
N = 40
REGION = [(u, v) for v in range(10, 31) for u in range(10, 31)]
TRUE_P = [0.05, -0.03, 0.02, -0.04, 1.5, -1.0]
def texture():
rng = random.Random(5)
blobs = [(rng.uniform(5, 35), rng.uniform(5, 35), rng.uniform(2.5, 4.5), rng.uniform(50, 150))
for _ in range(12)]
def f(u, v):
return sum(a * math.exp(-((u - x) ** 2 + (v - y) ** 2) / (2 * s * s)) for x, y, s, a in blobs)
return f
def affine_pair(p):
"""Template T = f on the grid, and image I with I(W(x; p)) = T(x)."""
f = texture()
t = [[f(u, v) for u in range(N)] for v in range(N)]
q = params(inv(warp_matrix(p)))
img = [[f(*warp(q, u, v)) for u in range(N)] for v in range(N)]
return t, img
def point_error(p, q):
return max(math.dist(warp(p, u, v), warp(q, u, v)) for u, v in REGION)
def test_warp_jacobian_matches_finite_differences():
rng = random.Random(1)
p = [rng.uniform(-0.1, 0.1) for _ in range(6)]
h = 1e-6
for u, v in [(0, 0), (3, -2), (12.5, 7.25)]:
jac = warp_jacobian(u, v)
for i in range(6):
pp, pm = list(p), list(p)
pp[i] += h
pm[i] -= h
a, b = warp(pp, u, v), warp(pm, u, v)
assert abs((a[0] - b[0]) / (2 * h) - jac[0][i]) < 1e-6
assert abs((a[1] - b[1]) / (2 * h) - jac[1][i]) < 1e-6
def test_compose_inverse_undoes_the_increment():
rng = random.Random(2)
for _ in range(5):
p = [rng.uniform(-0.2, 0.2) for _ in range(6)]
dp = [rng.uniform(-0.2, 0.2) for _ in range(6)]
r = compose_inverse(p, dp)
for u, v in [(0, 0), (5, 9), (-3, 4)]:
a = warp(r, *warp(dp, u, v))
b = warp(p, u, v)
assert math.dist(a, b) < 1e-12
def test_steepest_descent_images_by_the_chain_rule():
ramp = [[2.0 * u + 3.0 * v + 1.0 for u in range(N)] for v in range(N)]
region = [(u, v) for v in range(5, 9) for u in range(5, 9)]
sd, hess = precompute(ramp, region)
h = 1e-4
for (u, v), s in zip(region, sd):
for i in range(6):
dp = [0.0] * 6
dp[i] = h
num = (sample(ramp, *warp(dp, u, v)) - sample(ramp, u, v)) / h
assert abs(num - s[i]) < 1e-6
for i in range(6):
for j in range(6):
assert abs(hess[i][j] - sum(s[i] * s[j] for s in sd)) < 1e-9
assert hess[i][j] == hess[j][i]
def test_integer_translation_is_recovered_exactly():
f = texture()
t = [[f(u, v) for u in range(N)] for v in range(N)]
img = [[f(u - 3, v + 2) for u in range(N)] for v in range(N)]
p, costs = ic_align(t, REGION, img)
assert max(abs(a - b) for a, b in zip(p, [0, 0, 0, 0, 3, -2])) < 1e-8
assert costs[-1] < 1e-12
def test_affine_warp_is_recovered():
t, img = affine_pair(TRUE_P)
p, costs = ic_align(t, REGION, img)
assert point_error(p, TRUE_P) < 0.1
# the cost drops at every step until it reaches the floor set by interpolation
final = costs[-1]
for a, b in zip(costs, costs[1:]):
if a > 1.05 * final:
assert b < a
assert costs[0] > 1000 * final
def test_agrees_with_forwards_additive():
t, img = affine_pair(TRUE_P)
p, _ = ic_align(t, REGION, img)
q = fa_align(t, REGION, img)
assert point_error(p, q) < 0.02
def test_flat_template_has_a_singular_hessian():
flat = [[5.0] * N for _ in range(N)]
with pytest.raises(ValueError):
ic_align(flat, REGION, flat)
History
Lucas and Kanade (1981) introduced the forwards additive iteration for image registration. Baker and Matthews presented the inverse compositional algorithm at CVPR 2001 and, in their 2004 paper, put it with the forwards additive, forwards compositional and inverse additive forms in one framework, with proofs of their first-order equivalence, their costs per iteration and an experimental comparison. They noted that the inverse compositional form is the efficient one that works for any warp group.
References
- Simon Baker and Iain Matthews, Lucas-Kanade 20 years on, a unifying framework, International Journal of Computer Vision 56(3), 2004, 221 to 255, Section 2 (the forwards additive algorithm and its cost), Section 3.1 (the forwards compositional algorithm and the group requirement) and Section 3.2 (the inverse compositional algorithm, its first-order equivalence with the forwards compositional one, and its cost)
- Simon Baker and Iain Matthews, Equivalence and efficiency of image alignment algorithms, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2001, the whole paper (the first statement of the inverse compositional algorithm and of its equivalence to the forwards additive algorithm)
- Bruce D. Lucas and Takeo Kanade, An iterative image registration technique with an application to stereo vision, Proceedings of the 7th International Joint Conference on Artificial Intelligence (IJCAI), Vancouver, 1981, volume 2, pages 674 to 679, the whole paper (the forwards additive iteration that this algorithm reorganizes)
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 9, Motion estimation (the sections on incremental refinement and parametric motion)
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 ZVVMQX Edit this page History Report an error Markdown