Algorithmcore
Direct linear transformation for homography
Also called DLT, DLT algorithm, normalized DLT for homographies.
Stack two linear equations per point pair into a system Ah = 0 and take h as the right singular vector of A of least singular value.
- Solves
- Homography estimation
- Time
- Θ(n) worst · average · best
- Space
- Θ(n) extra
- Where
- n = the number of point pairs
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Y. I. Abdel Aziz, H. M. Karara, Richard Hartley, 1971
The direct linear transformation (DLT) for homographies estimates the matrix with from point pairs. Each pair gives two equations that are linear in the nine entries of . The algorithm stacks them into a matrix and returns the unit vector that makes smallest, which is a right singular vector of . This page gives the normalized form (Hartley and Zisserman, Algorithm 4.2): it first moves and scales the points of each image with Hartley normalization, and without that step the result on pixel data is poor. The problem it solves, with its other costs and methods, is on the page homography estimation; the same linear idea for a camera matrix is DLT resectioning.
In plain words
The rule says that points in the same direction as . Two vectors point in the same direction when their cross product is zero, and that gives equations in which the unknown entries of appear only to the first power. Each pair of points gives two useful equations, so four pairs give eight equations for the nine entries, which fixes up to its overall size. With more pairs and noisy points no fits all equations, so the algorithm takes the that leaves the smallest total leftover. Pixel coordinates are large numbers, and the equations mix them with 1, which makes the leftover depend on the units. Moving the points to the origin and shrinking them first fixes this.
The problem
Input. Point pairs , , , given as 2D points, which the algorithm extends to .
Output. A matrix with and with its entry of largest absolute value positive. It minimizes the algebraic error of the normalized points, subject to , and then is moved back to the original coordinates. If the pairs are exact images of the points under an invertible homography , and four of the points have no three on a line, the output is scaled to this form.
The algorithm
DLT-HOMOGRAPHY(x_1 .. x_n, x'_1 .. x'_n)- 1
T <- the similarity that moves the centroid of the x_i to 0 and makes their mean distance to it sqrt(2) - 2
T' <- the same similarity for the x'_i - 3
for i <- 1 to n - 4
y_i <- T x_i ; (u', v', w') <- T' x'_i - 5
append the row [ 0^T , -w' y_i^T , v' y_i^T ] to A - 6
append the row [ w' y_i^T , 0^T , -u' y_i^T ] to A - 7
h <- the right singular vector of A for its smallest singular value - 8
H~ <- the 3 x 3 matrix with rows h[1..3], h[4..6], h[7..9] - 9
H <- T'^-1 H~ T - 10
return H / ||H||_F, with the sign that makes its entry of largest absolute value positive
Lines L1 and L2 are Hartley normalization: each image gets its own similarity. The rows of L5 and L6 come from . Write for row of ; then , and the first two entries of the cross product are and . The third entry is a combination of these two when , so it adds nothing and is left out. Line L7 is the minimizer of over unit vectors, found by the singular value decomposition. Line L9 undoes the normalization: if with and , then . Line L10 picks one of the matrices so that equal homographies give equal outputs.
Example
Map the unit square , , , to the trapezoid , , , .
| line | value |
|---|---|
| L1 | centroid , mean distance , scale 2: , and the are |
| L2 | centroid , mean distance , scale : |
| L3 to L6 | 8 rows; for the third pair, and , so the rows are and |
| L7, L8 | has rank 8, and its null vector gives |
| L9 | |
| L10 | ; the output is that matrix divided by , with largest entry |
A check of one pair: . For the third pair, the rows of the plain DLT without normalization would be and , and both are orthogonal to .
Correctness
Each pair of rows is equivalent to , which is when . On exact data, four pairs with no three of the points on a line make of rank exactly 8. Then the null space of is spanned by the true normalized matrix, so line L7 returns it up to sign, and line L9 gives back the true up to scale. For noisy data, the right singular vector of the smallest singular value minimizes over unit vectors, by the SVD. The full proof is below.
Proof: The normalized DLT minimizes the algebraic error and recovers H exactly from exact datafull
We use the notation of the page. The input is pairs of 2D points, written as and . A set of points of is in general position when no three of them lie on one line, which for three points means that their vectors are linearly independent. For a matrix we write for its rows put one after the other, so . The canonical form of a nonzero matrix is times the sign of its entry of largest absolute value (on a tie, the first such entry in row order).
Claim. (a) The vector of line L7 minimizes over all unit vectors. (b) If there is an invertible with for all , and four of the are in general position, then DLT-HOMOGRAPHY returns the canonical form of .
Lemma 1 (the two rows). Let with , let , and let be a matrix. The rows of lines L5 and L6, applied to , are 0 if and only if , that is, if and only if is a multiple of (possibly the zero multiple).
Proof. Let , so with the row of . The row of L5 applied to is , and the row of L6 is . These are the first two entries of , whose third entry is . If the first two are 0, then and , so the third is and . The converse is clear.
The points have last entry 1, because the last row of the similarity is . So Lemma 1 applies to every pair, and the null space of is exactly the set of with for all .
Lemma 2 (minimum of the algebraic error). Let be an real matrix and let be its smallest singular value, counted as 0 when . Then , and a right singular vector for attains it.
Proof. Let with orthogonal, where are the singular values (with zeros added when ). For a unit vector put , also a unit vector. Then . The last column of , the right singular vector for , gives and equality.
Part (a) of the claim is Lemma 2 applied to line L7.
Lemma 3 (four points fix the matrix). Let be invertible, and let be in general position, with . If a matrix satisfies for , then for some real .
Proof. Write with (it is not 0, since is invertible and ), and , which holds by the cross product condition. Let . Then . The vectors are a basis of , so . None of is 0: if , then would be dependent, so three of the points would be on a line. Apply to both sides:
By the independence of and since , . So acts as on a basis, , and .
Lemma 4 (normalization). Let . Then for all , is invertible, and four of the are in general position. For every nonzero , .
Proof. . It is a product of invertible matrices. The map is an invertible linear map of , so it keeps linear independence, and the four points stay in general position. The last identity is direct.
Proof of part (b). By Lemma 4 and Lemma 1, lies in the null space of , so . By Lemma 3, applied to and the four points in general position, and by Lemma 1, every null vector of is a multiple of . So the null space is the line spanned by , has rank 8, and its other singular values are positive. By Lemma 2, line L7 returns a unit vector with , so and with . By Lemma 4, line L9 gives . Line L10 divides by and fixes the sign by a rule that depends only on the matrix up to a positive factor, so the result is the same for every : it is the canonical form of .
Remark (covariance under similarities). Let and be similarities of the two images. The normalized points of are for a matrix with a orthogonal matrix, because a similarity moves the centroid with the points and multiplies all distances by the same factor; likewise for the second image. For orthogonal , , and the first two entries of are times the first two entries of . So the algebraic error of on the new points equals the algebraic error of on the old ones, and keeps the Frobenius norm. The minimizer moves with the data, and the output for the moved points is the canonical form of whenever the minimizer is unique. The plain DLT, without normalization, has no such property, because a translation of the pixel frame changes by more than an orthogonal change of variables.
Complexity
Counting arithmetic operations, lines L1 and L2 cost , the loop costs , and has rows and a fixed number of 9 columns. The SVD of a matrix costs : for example, a QR decomposition reduces it to a triangle in operations, and the SVD of that triangle takes a fixed amount of work. So the time is . The matrix needs extra space; a version that only keeps needs , at the price of squaring the condition number.
In floating point the accuracy depends on the condition of . Without normalization the entries of a row range from about 1 to the product of two pixel coordinates, around or , and the gap between the smallest and the second smallest singular value is tiny compared with the largest one. Normalization makes all entries about 1. The page on Hartley normalization gives a measured example.
Properties
- Exact on exact data. If for an invertible and four of the points are in general position, the output is in canonical form, for any number of pairs.
- Covariant under similarities. If the points of the first image are moved by a similarity and those of the second by , the output becomes the canonical form of . The plain DLT, without lines L1 and L2, does not have this property: its result depends on where the origin of the pixel frame is and on the unit.
- Linear and non-iterative. No starting point and no iterations; the cost is one SVD.
- Algebraic, not geometric. On noisy data the output minimizes the algebraic error of the normalized points, not a distance in pixels. See algebraic and geometric error.
- Swap gives the inverse. On exact data, exchanging the two images returns the canonical form of .
Variants and improvements
- Plain DLT. Lines L1 and L2 with . It is HZ's basic algorithm and is fine only for small, centered coordinates.
- Fix . Solve an ordinary least squares problem for the other eight entries. It fails when the true is 0 or near 0, which happens when the origin of image 1 maps to a point at or near infinity.
- Normal equations. Take the eigenvector of for its smallest eigenvalue. It needs only a matrix, but squares the condition number.
- Four points in closed form. For exactly four pairs, map both quadruples to the canonical frame , , , and compose; this is fast in a minimal solver inside RANSAC.
- Lines and mixed data. A matched pair of lines satisfies , so gives two more rows that are linear in , and lines and points can share one matrix .
- Refinement. Use the output as the starting point of a geometric fit, the Gold Standard method of homography estimation or a Sampson fit, with Levenberg-Marquardt.
When to use it
Use the normalized DLT whenever a homography must be found from point matches: as the minimal solver inside RANSAC, as the estimate on the inliers, and as the start of a nonlinear refinement. On its own it is accurate enough for many tasks, such as stitching previews or document rectification. When the best accuracy matters, for example in calibration or measurement, refine it with a geometric cost. If the matches contain outliers, do not run it on all of them: one gross outlier can move the result far.
Pitfalls
- No normalization. On pixel coordinates the plain DLT can be wrong by many pixels, even with little noise.
- One normalization for both images. Each image needs its own , computed from its own points.
- Degenerate points. Three of four points on a line, or all points near one line, make the two smallest singular values of both near 0. Check that the second smallest singular value is not close to the smallest one.
- Direction. The result maps image 1 to image 2. For the other direction use , not .
- Comparing results. and are the same homography. Compare canonical forms, or compare the maps on test points.
- Outliers. The algebraic least squares fit has no robustness. Use it inside RANSAC or another robust method.
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()
dlt_homography.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dlt-homography/. The authors are listed in prov/12XVFY.jsonl.
"""Normalized direct linear transformation (DLT) for a 2D homography.
Given n >= 4 point pairs x1[i] <-> x2[i] (pixels, 2 entries each), find the
3 x 3 matrix H with x2[i] ~ H x1[i]. This is the normalized DLT of Hartley
and Zisserman (Algorithm 4.2). The result has Frobenius norm 1, and its
entry of largest absolute value is positive.
Cost: O(n) to build the 2n x 9 matrix A and O(n) for its SVD (the number of
columns is fixed at 9), so O(n) in total.
"""
from __future__ import annotations
import math
from typing import List, Sequence
from cvla import inv, matvec, mul, norm, nullvec, scale, svd
Matrix = List[List[float]]
def normalizing_similarity(pts: Sequence[Sequence[float]]) -> Matrix:
"""The 3 x 3 similarity T that moves the centroid of the points to the
origin and scales them so that their mean distance to it is sqrt(2).
Precondition: the points are not all equal. Cost O(n)."""
n = len(pts)
cx = sum(float(p[0]) for p in pts) / n
cy = sum(float(p[1]) for p in pts) / n
d = sum(math.hypot(float(p[0]) - cx, float(p[1]) - cy) for p in pts) / n
if d == 0.0:
raise ValueError("all points coincide")
s = math.sqrt(2.0) / d
return [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]]
def dlt_rows(y1: Sequence[float], y2: Sequence[float]) -> Matrix:
"""The two rows of A for one pair of homogeneous points y1, y2 = (u, v, w).
They are rows 1 and 2 of [y2]_x (y1 kron I) and say y2 x (H y1) = 0."""
u, v, w = y2
zero = [0.0, 0.0, 0.0]
r1 = zero + [-w * c for c in y1] + [v * c for c in y1] # @line L5
r2 = [w * c for c in y1] + zero + [-u * c for c in y1] # @line L6
return [r1, r2]
def canonical(H: Sequence[Sequence[float]]) -> Matrix:
"""H scaled to Frobenius norm 1, with its entry of largest absolute
value positive (the first such entry, in row order, on a tie)."""
f = norm(H)
if f == 0.0:
raise ValueError("zero matrix")
big = max((x for row in H for x in row), key=abs)
return scale(H, (1.0 if big > 0 else -1.0) / f)
def dlt_homography(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]],
normalize: bool = True) -> Matrix:
"""Estimate H with x2[i] ~ H x1[i] from n >= 4 pairs of 2D points.
With normalize=False the points are used as they are: this is the plain
DLT, which is badly conditioned on pixel data. Raises ValueError for
fewer than 4 pairs or for coincident points. The result is exact (up to
rounding) when the pairs are exact and no 3 of 4 points are collinear.
Cost O(n)."""
n = len(x1)
if n != len(x2) or n < 4:
raise ValueError("need at least 4 point pairs")
if normalize:
T1 = normalizing_similarity(x1) # @line L1
T2 = normalizing_similarity(x2) # @line L2
else:
T1 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
T2 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
a: Matrix = []
for p, q in zip(x1, x2): # @line L3
y1 = matvec(T1, [float(p[0]), float(p[1]), 1.0]) # @line L4
y2 = matvec(T2, [float(q[0]), float(q[1]), 1.0]) # @line L4
a.extend(dlt_rows(y1, y2))
h = nullvec(a) # @line L7
Hn = [h[0:3], h[3:6], h[6:9]] # @line L8
H = mul(mul(inv(T2), Hn), T1) # @line L9
return canonical(H) # @line L10
def apply(H: Sequence[Sequence[float]], p: Sequence[float]) -> List[float]:
"""The image (u, v) of the 2D point p under H. Raises ZeroDivisionError
if p maps to a point at infinity."""
x = matvec(H, [p[0], p[1], 1.0])
return [x[0] / x[2], x[1] / x[2]]
def transfer_errors(H: Sequence[Sequence[float]], x1: Sequence[Sequence[float]],
x2: Sequence[Sequence[float]]) -> List[float]:
"""The distance in the second image between x2[i] and H x1[i]."""
out = []
for p, q in zip(x1, x2):
u, v = apply(H, p)
out.append(math.hypot(u - q[0], v - q[1]))
return out
def dlt_singular_values(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]]) -> List[float]:
"""The 9 singular values (descending) of the normalized DLT matrix,
padded with zero rows when n = 4. A second singular value near zero
shows a degenerate configuration."""
T1, T2 = normalizing_similarity(x1), normalizing_similarity(x2)
a: Matrix = []
for p, q in zip(x1, x2):
a.extend(dlt_rows(matvec(T1, [p[0], p[1], 1.0]), matvec(T2, [q[0], q[1], 1.0])))
a += [[0.0] * 9 for _ in range(max(0, 9 - len(a)))]
return svd(a)[1]
def inverse(H: Sequence[Sequence[float]]) -> Matrix:
"""The inverse homography, in canonical form."""
return canonical(inv(H))
test_dlt_homography.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dlt-homography/. The authors are listed in prov/12XVFY.jsonl.
"""Tests of the normalized DLT for homographies."""
import math
import random
from fractions import Fraction
import pytest
from cvla import inv, matvec, mul, norm, sub
from dlt_homography import (apply, canonical, dlt_homography, dlt_rows,
dlt_singular_values, inverse, normalizing_similarity,
transfer_errors)
def exact_four_point(src, dst):
"""Independent oracle: solve the 8 x 8 linear system with h33 = 1 in
exact rational arithmetic (Gauss-Jordan elimination)."""
a = []
for (x, y), (u, v) in zip(src, dst):
x, y, u, v = Fraction(x), Fraction(y), Fraction(u), Fraction(v)
a.append([x, y, 1, 0, 0, 0, -u * x, -u * y, u])
a.append([0, 0, 0, x, y, 1, -v * x, -v * y, v])
a = [[Fraction(c) for c in row] for row in a]
for c in range(8):
p = next(r for r in range(c, 8) if a[r][c] != 0)
a[c], a[p] = a[p], a[c]
for r in range(8):
if r != c and a[r][c] != 0:
f = a[r][c] / a[c][c]
a[r] = [x - f * y for x, y in zip(a[r], a[c])]
h = [a[i][8] / a[i][i] for i in range(8)] + [Fraction(1)]
return [h[0:3], h[3:6], h[6:9]]
def random_homography(rng):
"""A homography of pixel images that keeps [0, 640] x [0, 480] in front
(third coordinate > 0)."""
return [[1.0 + rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3), rng.uniform(-50, 50)],
[rng.uniform(-0.3, 0.3), 1.0 + rng.uniform(-0.3, 0.3), rng.uniform(-50, 50)],
[rng.uniform(-4e-4, 4e-4), rng.uniform(-4e-4, 4e-4), 1.0]]
def random_points(rng, n):
return [[rng.uniform(0, 640), rng.uniform(0, 480)] for _ in range(n)]
def rel_dist(a, b):
return norm(sub(canonical(a), canonical(b)))
def test_square_to_trapezoid():
src = [(0, 0), (1, 0), (1, 1), (0, 1)]
dst = [(0, 0), (4, 0), (3, 2), (1, 2)]
H = dlt_homography(src, dst)
want = [[4.0, 2.0, 0.0], [0.0, 4.0, 0.0], [0.0, 1.0, 1.0]]
assert rel_dist(H, want) <= 1e-12
assert exact_four_point(src, dst) == [[4, 2, 0], [0, 4, 0], [0, 1, 1]]
u, v = apply(H, (0.5, 0.5))
assert abs(u - 2.0) <= 1e-12 and abs(v - 4.0 / 3.0) <= 1e-12
def test_rows_vanish_on_the_true_homography():
rng = random.Random(1)
for _ in range(50):
H = random_homography(rng)
h = [c for row in H for c in row]
p = random_points(rng, 1)[0]
y1 = [p[0], p[1], 1.0]
y2 = matvec(H, y1)
for row in dlt_rows(y1, y2):
assert abs(sum(a * b for a, b in zip(row, h))) <= 1e-9 * norm(row) * norm(h)
def test_four_points_against_exact_oracle():
rng = random.Random(2)
done = 0
while done < 40:
src = [(rng.randint(0, 640), rng.randint(0, 480)) for _ in range(4)]
dst = [(rng.randint(0, 640), rng.randint(0, 480)) for _ in range(4)]
if any(Fraction(0) == ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))
for pts in (src, dst) for i, a in enumerate(pts) for j, b in enumerate(pts)
for k, c in enumerate(pts) if i < j < k):
continue
Hx = exact_four_point(src, dst)
Hf = [[float(c) for c in row] for row in Hx]
H = dlt_homography(src, dst)
assert rel_dist(H, Hf) <= 1e-8
done += 1
def test_exact_recovery_many_points():
rng = random.Random(3)
for n in (4, 5, 8, 20, 50):
for _ in range(4):
Ht = random_homography(rng)
x1 = random_points(rng, n)
x2 = [apply(Ht, p) for p in x1]
H = dlt_homography(x1, x2)
assert rel_dist(H, Ht) <= 1e-8
assert max(transfer_errors(H, x1, x2)) <= 1e-7
def test_plain_dlt_agrees_on_exact_data():
rng = random.Random(4)
Ht = random_homography(rng)
x1 = random_points(rng, 10)
x2 = [apply(Ht, p) for p in x1]
assert rel_dist(dlt_homography(x1, x2, normalize=False), Ht) <= 1e-6
def test_normalizing_similarity():
rng = random.Random(5)
pts = random_points(rng, 30)
T = normalizing_similarity(pts)
q = [matvec(T, [p[0], p[1], 1.0]) for p in pts]
assert abs(sum(r[0] for r in q)) <= 1e-9 and abs(sum(r[1] for r in q)) <= 1e-9
mean = sum(math.hypot(r[0], r[1]) for r in q) / len(q)
assert abs(mean - math.sqrt(2.0)) <= 1e-12
with pytest.raises(ValueError):
normalizing_similarity([[3.0, 4.0]] * 5)
def test_covariance_under_similarities():
"""Normalized DLT commutes with similarity changes of both frames."""
rng = random.Random(6)
Ht = random_homography(rng)
x1 = random_points(rng, 30)
x2 = [[a + rng.gauss(0, 1.0) for a in apply(Ht, p)] for p in x1]
H = dlt_homography(x1, x2)
c, s = math.cos(0.7), math.sin(0.7)
S1 = [[3 * c, -3 * s, 100.0], [3 * s, 3 * c, -40.0], [0.0, 0.0, 1.0]]
S2 = [[0.5, 0.0, 7.0], [0.0, 0.5, 9.0], [0.0, 0.0, 1.0]]
y1 = [apply(S1, p) for p in x1]
y2 = [apply(S2, p) for p in x2]
G = dlt_homography(y1, y2)
assert rel_dist(G, mul(mul(S2, H), inv(S1))) <= 1e-9
def test_noise_gives_small_transfer_error():
rng = random.Random(7)
sigma = 0.5
for _ in range(5):
Ht = random_homography(rng)
x1 = random_points(rng, 60)
x2 = [[a + rng.gauss(0, sigma) for a in apply(Ht, p)] for p in x1]
H = dlt_homography(x1, x2)
clean = [apply(Ht, p) for p in x1]
err = transfer_errors(H, x1, clean)
assert math.sqrt(sum(e * e for e in err) / len(err)) <= sigma
def test_swap_gives_inverse():
rng = random.Random(8)
Ht = random_homography(rng)
x1 = random_points(rng, 12)
x2 = [apply(Ht, p) for p in x1]
assert rel_dist(dlt_homography(x2, x1), inverse(dlt_homography(x1, x2))) <= 1e-8
def test_three_collinear_points_lose_rank():
src = [(0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (0.0, 3.0)]
dst = [(0.0, 0.0), (1.0, 0.5), (2.0, 1.0), (1.0, 4.0)]
s = dlt_singular_values(src, dst)
assert s[-1] <= 1e-12 * s[0]
assert s[-2] <= 1e-12 * s[0]
good = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
s = dlt_singular_values(good, dst)
assert s[-2] >= 1e-3 * s[0]
def test_bad_input():
with pytest.raises(ValueError):
dlt_homography([(0, 0), (1, 0), (0, 1)], [(0, 0), (1, 0), (0, 1)])
with pytest.raises(ValueError):
dlt_homography([(0, 0)] * 4, [(0, 0), (1, 0), (0, 1), (1, 1)])
History
The name direct linear transformation comes from photogrammetry, where Abdel-Aziz and Karara (1971) estimated the camera from linear equations in the entries of its matrix. In computer vision the same idea gives the homography from four or more point pairs. The method was long held to be inaccurate. Hartley (1997) showed, for the eight-point algorithm and for linear estimates in general, that the poor results came from the bad condition of the system on raw pixel coordinates, and that translating and scaling the points first makes the linear estimate nearly as good as iterative ones. Hartley and Zisserman (2000, second edition 2004) give the normalized DLT for homographies as their Algorithm 4.2.
References
- Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 4.1, The Direct Linear Transformation (DLT) algorithm, and Section 4.4, Transformation invariance and normalization (the normalized DLT, Algorithm 4.2)
- Richard I. Hartley, In defense of the eight-point algorithm, IEEE Transactions on Pattern Analysis and Machine Intelligence 19(6), 1997, 580-593, the normalization of the points and why it improves the condition of the linear system
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 8.1, Pairwise alignment (the linear least squares estimate of a homography)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 12XVFY Edit this page History Report an error Markdown