Algorithmcore
Pose recovery from the essential matrix
Also called essential matrix decomposition.
Factor E by SVD into four candidate rotation and translation pairs and keep the one that puts triangulated points in front of both cameras.
- Solves
- Relative pose estimation
- Time
- Θ(n) worst · average · best
- Space
- Θ(1) extra
- Where
- n = the number of point pairs used for the depth test
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- H. C. Longuet Higgins, Richard Hartley, 1981
Pose recovery from the essential matrix turns an essential matrix into the relative pose of two calibrated cameras, with and . The singular value decomposition , with and made rotations, gives exactly four candidates: the rotations and , each with the translations . All four satisfy the epipolar constraint, so the images cannot tell them apart by it. Only one puts the scene points in front of both cameras, and the algorithm finds it by the cheirality test: it computes the depths of the matched points under each candidate and keeps the one with the most positive depths. It is the last step after the five-point algorithm or the eight-point algorithm in the relative pose problem.
In plain words
The essential matrix packs the turn and the direction of travel of the camera into one table. Pulling them out again is easy with a standard matrix tool, but it gives four possible answers, not one. Two answers differ in the direction of travel: forward or backward. The other two differ by a half turn of one camera about the line that joins the two cameras. All four agree with the matched points in the same way. But in three of them some scene points end up behind a camera, which a real camera cannot see. So the algorithm rebuilds a few points for each answer and keeps the answer in which the points sit in front of both cameras.
The problem
Input. An essential matrix , with any nonzero scale and sign, and point pairs , , , in normalized image coordinates.
Output. A rotation , a unit vector with , and the number of pairs whose reconstructed point has positive depth in both cameras, for the candidate with the largest such number. If the pairs are exact images of points in front of both cameras of a pose with and , the output is and the count is .
The algorithm
RECOVER-POSE(E, x1_1 .. x1_n, x2_1 .. x2_n)- 1
(U, diag(s1, s2, s3), V) <- the SVD of E - 2
if det U < 0 then negate the last column of U ; if det V < 0 then negate the last column of V - 3
Ra <- U W V^T ; Rb <- U W^T V^T, with W = ((0, -1, 0), (1, 0, 0), (0, 0, 1)) - 4
the candidates are (Ra, u3), (Ra, -u3), (Rb, u3), (Rb, -u3), where u3 is the last column of U - 5
for each candidate (R, t) - 6
for each pair, (l1, l2) <- the depths that minimize || l1 R y1 + t - l2 y2 ||, with y = (u, v, 1) - 7
c <- the number of pairs with l1 > 0 and l2 > 0 - 8
return the candidate with the largest c (the first one on a tie), and c
Line L2 does not change the product , because the third singular value is 0, and it makes and rotations, so and are rotations. Since and gives , the translation is a multiple of . The characterization proof shows , and with , the half turn about , which also gives . Line L6 is a small triangulation: is the point on the first ray in the second frame, and is the point on the second ray. The normal equations give , and parallel rays give , which counts as not in front. The values and are the coordinates of the point in the two camera frames.
Example
Take the running example: , , , and the one pair from .
| line | value |
|---|---|
| L1, L2 | , , , both with determinant 1 |
| L3 | and |
| L4 | , so |
| L6, L7 for | depths , |
| L6, L7 for | depths , |
| L6, L7 for | depths , |
| L6, L7 for | depths , |
| L8 | with |
A check of the winner: . The four depth pairs follow the pattern of the proof: , , and for the twisted pair, here with .
Correctness
A real matrix with singular values has exactly four factorizations with and a rotation, and they are the four candidates of line L4 up to the scale of . For a point with true depths under one of them, the other three give , and for a number that depends on the point. So for exact data with all points in front of both cameras, only the true pose has all depths positive, and the count rule returns it. Under noise, the majority over many points is a practical rule, not a theorem. The full proof is below.
Proof: An essential matrix has exactly four factorizations into a rotation and a unit translation, and exactly one of them puts a given point in front of both camerasfull
We use the notation of the page. Poses follow , a point in normalized coordinates is , and the depth of a point in a camera is its coordinate in that camera. is the set of rotations, is the matrix with , and
Claim. Let with , and . (a) The four pairs of line L4 are exactly the pairs with and for some real , and is one of them. (b) Let a point have positive depths and in the true pose , and let it not lie on the line through the two camera centers. Then, for the four candidates, the depths of line L6 are , , and , with , where the last two need . So only the true pose has both depths positive. (c) On exact data in which at least one point satisfies (b), RECOVER-POSE returns .
Lemma 1 (rotations and the cross product). For and , .
Proof. For every , , because a rotation keeps cross products: when .
Lemma 2 (the SVD with rotations). The singular values of are . After line L2, with , and the third column of spans the null space of .
Proof. , whose eigenvalues are . Line L1 gives an SVD with orthogonal and . Line L2 changes the sign of the third column of or of when the determinant is . The third singular value is 0, so the third columns do not enter the product, and the product stays . Now . Finally , and the null space has dimension 1.
Proof of part (a). Let with and . Then , so by Lemma 2, . Write with . By Lemma 1, . Put . The equation becomes , that is,
The rows of are , where is row of . So and . Rows of an orthogonal matrix are unit vectors, so , and is the unit vector that makes , which is in both cases. For , ; for , . So or , and is one of the four pairs of lines L3 and L4.
Conversely, each of the four pairs has (a product of rotations) and , and the computation above, read backwards, gives . The two rotations differ, because , so the four pairs are distinct. The true pose satisfies , so it is one of them.
Lemma 3 (the twisted pair). , where is the rotation by about .
Proof. , so , and . This matrix keeps and reverses every vector orthogonal to it.
Since , also . By part (a) and Lemma 3, the four candidates are , , and .
Lemma 4 (the depths of line L6). For a pose and a pair , let and assume that and are linearly independent. Then the function depths returns the unique minimizer of . If has a solution, this minimizer is that solution, and and are the depths of the point in the two cameras.
Proof. The function is the norm of with , a matrix of rank 2. The normal equations have a positive definite matrix, with determinant by the Cauchy-Schwarz inequality, and the code solves them by Cramer's rule. A solution of the equation makes the norm 0, so it is the minimizer. The point has third entry , and has third entry .
Proof of part (b). The true pose gives with . The point is not on the line through the centers, so and are independent, and then and are independent too. The rotated ray of a candidate is or . Since and are independent, is a multiple of exactly when and , that is, when . So Lemma 4 applies to all four candidates when .
For the solution is . For the equation is solved by .
For we need . Since and , are independent, the right side is a multiple exactly when and . Then , so , and . For , the solution is the negative of this one, . In both cases . If , the rays of the two twisted candidates are parallel, as shown above. The function depths then finds a zero determinant and returns , so neither twisted candidate counts the point.
Proof of part (c). By part (b), the true pose counts every point that satisfies (b), and each other candidate counts none of them. A point on the line through the centers gives parallel rays for all candidates, and the code gives it depths , so no candidate counts it. So on exact data the true pose has the strictly largest count, and line L8 returns it.
Remark (noise). With noisy points the depths of Lemma 4 are least squares values, the depths of the midpoint method. A point far away or near the baseline can then get the wrong sign in the true pose, and a few points can get two positive depths in another pose. The majority rule of line L8 is a rule for this case, not a theorem: it picks the right pose when most points are well inside the region where the sign of the depths is stable.
Complexity
The SVD of a matrix and the four candidates take a fixed amount of work. The depth test costs for each pair and each of the four candidates, so the total time is . The extra space is , since only the four candidates and the counts are kept. In the real RAM model the SVD is exact; in floating point it is found by an iterative method that converges in a few sweeps for matrices.
Properties
- Exactly four candidates. For each essential matrix, up to the scale of .
- Sign of does not matter. gives the same four candidates in another order.
- Scale of is lost. The output has ; the true length needs other information.
- One point is enough on exact data. A single point in front of both cameras, not on the baseline, picks the right pose.
- Twisted pair. with the half turn about the baseline; the two rotations differ by 180 degrees.
- Robust by voting. With noisy data or a few wrong matches, the majority of the depth tests still picks the right pose in most cases.
Variants and improvements
- Test with one point. Many systems test only one point, or the first inlier. It is cheaper but fragile when that point is far away or noisy.
- Triangulation method. Line L6 can use linear triangulation or the midpoint method instead of the least squares; any method that gives the signs of the depths works.
- Far points. Points with very large depth give unreliable signs. Some implementations ignore points whose depth is above a threshold.
- Closed forms without the SVD. The translation is the null vector of , found from a cross product of two rows of , and the rotation can be written from the rows of and ; this is Longuet-Higgins' original form.
- Homography case. For a planar scene or a homography, the analogous step is homography decomposition, which has its own four candidates.
When to use it
Use it after any method that estimates : the five-point algorithm in RANSAC, the eight-point algorithm on inliers, or from a fundamental matrix. Run the depth test on the inliers, not on all matches. If the estimate of is not exactly essential, the SVD step still works, because it uses only and ; that is the same as first projecting onto the closest essential matrix.
Pitfalls
- Forgetting line L2. If or , the matrices have determinant and are reflections, not rotations.
- Two candidates only. Testing only for one rotation misses the twisted pair, and can return a pose that puts the points behind a camera.
- Wrong frame convention. This page uses and . Libraries that use the camera center or the other direction give and .
- Pure rotation. If the true is zero, is zero or pure noise, and the result has no meaning.
- Points near the epipoles. A point close to the baseline gives rays that are nearly parallel, and its depths are unreliable.
- Ties. On degenerate data two candidates can get the same count. Report the count, so that the caller can detect a weak decision.
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()
essential_matrix_decomposition.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/essential-matrix-decomposition/. The authors are listed in prov/CHAEFS.jsonl.
"""Pose recovery from the essential matrix.
Given an essential matrix E (any nonzero scale and sign) and n >= 1 point
pairs x1[i] <-> x2[i] in normalized image coordinates (2 entries each), find
the relative pose (R, t) with X2 = R X1 + t, E ~ [t]_x R and ||t|| = 1.
The SVD E = U diag(s, s, 0) V^T, with det U = det V = +1, gives four
candidates (U W V^T, +u3), (U W V^T, -u3), (U W^T V^T, +u3) and
(U W^T V^T, -u3), where u3 is the last column of U. For each candidate
the depths of every point in both cameras come from a 2 x 2 least-squares
problem; the candidate with the most points of positive depth in both
cameras wins (the cheirality test, by a majority over the points).
Cost: O(1) for the SVD of the 3 x 3 matrix (a fixed number of Jacobi sweeps
in practice) and O(n) for the depth tests.
"""
from __future__ import annotations
from typing import List, Sequence, Tuple
from cvla import det, mul, svd, transpose
Matrix = List[List[float]]
W_MAT = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
def pose_candidates(E: Sequence[Sequence[float]]) -> List[Tuple[Matrix, List[float]]]:
"""The four pairs (R, t) with det R = 1, ||t|| = 1 and [t]_x R = +-E/s."""
u, _, v = svd(E) # @line L1
if det(u) < 0: # @line L2
u = [[row[0], row[1], -row[2]] for row in u] # @line L2
if det(v) < 0: # @line L2
v = [[row[0], row[1], -row[2]] for row in v] # @line L2
vt = transpose(v)
Ra = mul(mul(u, W_MAT), vt) # @line L3
Rb = mul(mul(u, transpose(W_MAT)), vt) # @line L3
u3 = [u[0][2], u[1][2], u[2][2]] # @line L4
neg = [-c for c in u3]
return [(Ra, u3), (Ra, neg), (Rb, u3), (Rb, neg)] # @line L4
def depths(R: Sequence[Sequence[float]], t: Sequence[float], p1: Sequence[float],
p2: Sequence[float]) -> Tuple[float, float]:
"""(lambda1, lambda2) that minimize ||lambda1 R y1 - lambda2 y2 + t||, with
y = (u, v, 1). Then X1 = lambda1 y1 and X2 = lambda2 y2, so the lambdas
are the depths (Z coordinates) in the two cameras. The 2 x 2 normal
equations are solved by Cramer's rule; parallel rays give (0, 0)."""
y1 = [float(p1[0]), float(p1[1]), 1.0]
y2 = [float(p2[0]), float(p2[1]), 1.0]
a = [sum(R[i][j] * y1[j] for j in range(3)) for i in range(3)] # R y1
b = [-c for c in y2]
aa = sum(c * c for c in a)
ab = sum(c * d for c, d in zip(a, b))
bb = sum(c * c for c in b)
at = sum(c * d for c, d in zip(a, t))
bt = sum(c * d for c, d in zip(b, t))
d = aa * bb - ab * ab
if d <= 1e-14 * aa * bb:
return 0.0, 0.0
lam1 = (-at * bb + bt * ab) / d
lam2 = (-bt * aa + at * ab) / d
return lam1, lam2
def count_in_front(R, t, x1, x2) -> int:
"""The number of pairs with positive depth in both cameras."""
count = 0
for p1, p2 in zip(x1, x2):
l1, l2 = depths(R, t, p1, p2) # @line L6
if l1 > 0.0 and l2 > 0.0: # @line L7
count += 1 # @line L7
return count
def recover_pose(E: Sequence[Sequence[float]], x1: Sequence[Sequence[float]],
x2: Sequence[Sequence[float]]) -> Tuple[Matrix, List[float], int]:
"""(R, t, count): the candidate with the most points in front of both
cameras, and that number. Ties go to the first candidate in the order of
pose_candidates."""
if len(x1) != len(x2) or not x1:
raise ValueError("need at least one point pair")
best = None
for R, t in pose_candidates(E): # @line L5
c = count_in_front(R, t, x1, x2)
if best is None or c > best[2]: # @line L8
best = (R, t, c)
return best # @line L8
test_essential_matrix_decomposition.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/essential-matrix-decomposition/. The authors are listed in prov/CHAEFS.jsonl.
"""Tests of pose recovery from the essential matrix."""
import math
import random
import pytest
from cvla import det, matvec, mul, norm, scale, skew, sub, transpose
from essential_matrix_decomposition import (count_in_front, depths,
pose_candidates, recover_pose)
R_EX = [[0.8, 0.0, 0.6], [0.0, 1.0, 0.0], [-0.6, 0.0, 0.8]]
T_EX = [1.0, 0.0, 0.0]
E_EX = [[0.0, 0.0, 0.0], [0.6, 0.0, -0.8], [0.0, 1.0, 0.0]]
def rotation(axis, angle):
"""Rodrigues formula, written out."""
a = [c / norm(axis) for c in axis]
k = skew(a)
k2 = mul(k, k)
s, c = math.sin(angle), math.cos(angle)
return [[(1.0 if i == j else 0.0) + s * k[i][j] + (1.0 - c) * k2[i][j]
for j in range(3)] for i in range(3)]
def rotation_angle(R1, R2):
"""The angle of R1^T R2. It equals arccos((tr(R1^T R2) - 1) / 2), but
the form 2 asin(||R1 - R2||_F / (2 sqrt 2)) keeps its accuracy near 0."""
d = norm(sub(R1, R2)) / (2.0 * math.sqrt(2.0))
return 2.0 * math.asin(min(1.0, d))
def direction_angle(a, b):
"""The angle between two directions, as 2 asin(||a' - b'|| / 2) for the
unit vectors a' and b'."""
d = norm(sub(scale(a, 1.0 / norm(a)), scale(b, 1.0 / norm(b)))) / 2.0
return 2.0 * math.asin(min(1.0, d))
def scene(rng, n, R, t):
x1, x2 = [], []
while len(x1) < n:
X1 = [rng.uniform(-2.0, 2.0), rng.uniform(-2.0, 2.0), rng.uniform(4.0, 8.0)]
X2 = [a + b for a, b in zip(matvec(R, X1), t)]
if X2[2] > 0.5:
x1.append([X1[0] / X1[2], X1[1] / X1[2]])
x2.append([X2[0] / X2[2], X2[1] / X2[2]])
return x1, x2
def random_pose(rng):
R = rotation([rng.uniform(-1, 1) for _ in range(3)], rng.uniform(0.05, 0.8))
t = [rng.uniform(-1, 1), rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)]
return R, scale(t, 1.0 / norm(t))
def test_worked_example():
# X1 = (0, 0, 5) and X2 = (4, 0, 4): x1 = (0, 0), x2 = (1, 0).
R, t, count = recover_pose(E_EX, [[0.0, 0.0]], [[1.0, 0.0]])
assert count == 1
assert norm(sub(R, R_EX)) <= 1e-12
assert norm(sub(t, T_EX)) <= 1e-12
l1, l2 = depths(R, t, [0.0, 0.0], [1.0, 0.0])
assert abs(l1 - 5.0) <= 1e-12 and abs(l2 - 4.0) <= 1e-12
def test_four_candidates_of_the_example():
cands = pose_candidates(E_EX)
twisted = [[0.8, 0.0, 0.6], [0.0, -1.0, 0.0], [0.6, 0.0, -0.8]] # (2 t t^T - I) R
rots = [R for R, _ in cands]
assert sum(norm(sub(R, R_EX)) <= 1e-12 for R in rots) == 2
assert sum(norm(sub(R, twisted)) <= 1e-12 for R in rots) == 2
ts = [t for _, t in cands]
assert sum(norm(sub(t, T_EX)) <= 1e-12 for t in ts) == 2
assert sum(norm(sub(t, scale(T_EX, -1.0))) <= 1e-12 for t in ts) == 2
# depths for the four candidates: one has both positive
signs = sorted((depths(R, t, [0.0, 0.0], [1.0, 0.0])[0] > 0, depths(R, t, [0.0, 0.0], [1.0, 0.0])[1] > 0)
for R, t in cands)
assert signs == [(False, False), (False, True), (True, False), (True, True)]
@pytest.mark.parametrize("seed", range(5))
def test_candidates_are_valid_factorizations(seed):
rng = random.Random(seed)
R, t = random_pose(rng)
E = scale(mul(skew(t), R), rng.choice([-1.0, 1.0]) * rng.uniform(0.1, 10.0))
En = scale(E, 1.0 / norm(E))
for Rc, tc in pose_candidates(E):
assert abs(det(Rc) - 1.0) <= 1e-12
assert norm(sub(mul(transpose(Rc), Rc), [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])) <= 1e-12
assert abs(norm(tc) - 1.0) <= 1e-12
F = mul(skew(tc), Rc)
F = scale(F, 1.0 / norm(F))
assert min(norm(sub(F, En)), norm(sub(F, scale(En, -1.0)))) <= 1e-12
@pytest.mark.parametrize("seed", range(5, 11))
def test_exact_recovery(seed):
rng = random.Random(seed)
R, t = random_pose(rng)
x1, x2 = scene(rng, 20, R, t)
E = scale(mul(skew(t), R), rng.choice([-1.0, 1.0]) * rng.uniform(0.1, 10.0))
Rr, tr, count = recover_pose(E, x1, x2)
assert count == 20
assert rotation_angle(Rr, R) <= 1e-8
assert direction_angle(tr, t) <= 1e-8
# exactly one candidate puts all points in front of both cameras
counts = sorted(count_in_front(Rc, tc, x1, x2) for Rc, tc in pose_candidates(E))
assert counts[-1] == 20 and counts[-2] < 20
def test_twisted_pair_flips_one_depth():
# (R, t) and ((2 t t^T - I) R, t) give depths of opposite sign product.
rng = random.Random(12)
R, t = random_pose(rng)
tw = mul(sub([[2.0 * a * b for b in t] for a in t], [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), R)
x1, x2 = scene(rng, 10, R, t)
for p, q in zip(x1, x2):
l1, l2 = depths(R, t, p, q)
m1, m2 = depths(tw, t, p, q)
assert l1 > 0 and l2 > 0
assert m1 * m2 < 0
def test_majority_with_noise():
# sigma = 0.001 in normalized coordinates (0.5 pixel at f = 500), 50 points.
rng = random.Random(13)
R, t = random_pose(rng)
x1, x2 = scene(rng, 50, R, t)
x1 = [[c + rng.gauss(0.0, 0.001) for c in p] for p in x1]
x2 = [[c + rng.gauss(0.0, 0.001) for c in p] for p in x2]
Rr, tr, count = recover_pose(mul(skew(t), R), x1, x2)
assert count >= 45
assert rotation_angle(Rr, R) <= 1e-8
assert direction_angle(tr, t) <= 1e-8
def test_parallel_rays_give_zero_depths():
I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
assert depths(I3, [1.0, 0.0, 0.0], [0.2, 0.1], [0.2, 0.1]) == (0.0, 0.0)
def test_rejects_empty_input():
with pytest.raises(ValueError):
recover_pose(E_EX, [], [])
History
Longuet-Higgins (1981) introduced the essential matrix, recovered the rotation and the translation from it, and used the sign of the reconstructed depths to choose among the solutions. The SVD form of the factorization, with the matrix and the four candidates, is given by Hartley and Zisserman (2000, second edition 2004) as Results 9.18 and 9.19, with the twisted pair in Section 9.6.3. Hartley (1998) developed the general theory of cheirality, the condition that points lie in front of the cameras, and its use to remove such ambiguities.
References
- Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 9.6, The essential matrix (Results 9.18 and 9.19 on the factorizations and the four solutions, and Section 9.6.3 on the twisted pair)
- H. C. Longuet-Higgins, A computer algorithm for reconstructing a scene from two projections, Nature 293, 1981, 133-135, the recovery of the rotation and the translation from the essential matrix and the choice by positive depths
- Richard I. Hartley, Chirality, International Journal of Computer Vision 26(1), 1998, 41-61, the conditions for points to lie in front of the cameras and their use to remove ambiguities
- Yi Ma, Stefano Soatto, Jana Kosecka and S. Shankar Sastry, An Invitation to 3-D Vision, Springer, 2004, Chapter 5, Section 5.1.2 (pose recovery from the essential matrix)
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 CHAEFS Edit this page History Report an error Markdown