Algorithm Search⌘K

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.

Time
Θ(n) worst · average · best
Space
Θ(1) extra
Where
n = the number of point pairs used for the depth test
Properties
deterministicexactofflineiterative
Origin
H. C. Longuet Higgins, Richard Hartley, 1981

Pose recovery from the essential matrix turns an essential matrix EE into the relative pose (R,t)(R, \mathbf{t}) of two calibrated cameras, with X2=RX1+t\mathbf{X}_2 = R\mathbf{X}_1 + \mathbf{t} and ∥t∥=1\|\mathbf{t}\| = 1. The singular value decomposition E=Udiag⁡(s,s,0)VTE = U\operatorname{diag}(s, s, 0)V^{\mathsf T}, with UU and VV made rotations, gives exactly four candidates: the rotations UWVTUWV^{\mathsf T} and UWTVTUW^{\mathsf T}V^{\mathsf T}, each with the translations ±u3\pm\mathbf{u}_3. 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 EE, with any nonzero scale and sign, and point pairs (x^1,i,x^2,i)(\hat{\mathbf{x}}_{1,i}, \hat{\mathbf{x}}_{2,i}), i=1,…,ni = 1, \ldots, n, n≥1n \ge 1, in normalized image coordinates.

Output. A rotation RR, a unit vector t\mathbf{t} with [t]×R∼E[\mathbf{t}]_\times R \sim E, 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 (R0,t0)(R_0, \mathbf{t}_0) with E∼[t0]×R0E \sim [\mathbf{t}_0]_\times R_0 and ∥t0∥=1\|\mathbf{t}_0\| = 1, the output is (R0,t0)(R_0, \mathbf{t}_0) and the count is nn.

The algorithm

  1. RECOVER-POSE(E, x1_1 .. x1_n, x2_1 .. x2_n)
  2. 1(U, diag(s1, s2, s3), V) <- the SVD of E
  3. 2if det U < 0 then negate the last column of U ; if det V < 0 then negate the last column of V
  4. 3Ra <- U W V^T ; Rb <- U W^T V^T, with W = ((0, -1, 0), (1, 0, 0), (0, 0, 1))
  5. 4the candidates are (Ra, u3), (Ra, -u3), (Rb, u3), (Rb, -u3), where u3 is the last column of U
  6. 5for each candidate (R, t)
  7. 6for each pair, (l1, l2) <- the depths that minimize || l1 R y1 + t - l2 y2 ||, with y = (u, v, 1)
  8. 7c <- the number of pairs with l1 > 0 and l2 > 0
  9. 8return the candidate with the largest c (the first one on a tie), and c

Line L2 does not change the product UΣVTU\Sigma V^{\mathsf T}, because the third singular value is 0, and it makes UU and VV rotations, so RaR_a and RbR_b are rotations. Since ETu3=0E^{\mathsf T}\mathbf{u}_3 = \mathbf{0} and E=[t]×RE = [\mathbf{t}]_\times R gives tTE=0\mathbf{t}^{\mathsf T}E = \mathbf{0}, the translation is a multiple of u3\mathbf{u}_3. The characterization proof shows [u3]×Ra∼E[\mathbf{u}_3]_\times R_a \sim E, and Rb=RπRaR_b = R_\pi R_a with Rπ=2u3u3T−IR_\pi = 2\mathbf{u}_3\mathbf{u}_3^{\mathsf T} - I, the half turn about u3\mathbf{u}_3, which also gives [u3]×Rb∼E[\mathbf{u}_3]_\times R_b \sim E. Line L6 is a small triangulation: λ1Ry1+t\lambda_1R\mathbf{y}_1 + \mathbf{t} is the point on the first ray in the second frame, and λ2y2\lambda_2\mathbf{y}_2 is the point on the second ray. The 2×22 \times 2 normal equations give (λ1,λ2)(\lambda_1, \lambda_2), and parallel rays give (0,0)(0, 0), which counts as not in front. The values λ1\lambda_1 and λ2\lambda_2 are the ZZ coordinates of the point in the two camera frames.

Example

Take the running example: R=(0.800.6010−0.600.8)R = \begin{pmatrix} 0.8 & 0 & 0.6 \\ 0 & 1 & 0 \\ -0.6 & 0 & 0.8 \end{pmatrix}, t=(1,0,0)\mathbf{t} = (1, 0, 0), E=(0000.60−0.8010)E = \begin{pmatrix} 0 & 0 & 0 \\ 0.6 & 0 & -0.8 \\ 0 & 1 & 0 \end{pmatrix}, and the one pair (0,0)↔(1,0)(0, 0) \leftrightarrow (1, 0) from X1=(0,0,5)\mathbf{X}_1 = (0, 0, 5).

line value
L1, L2 U=(00−1010100)U = \begin{pmatrix} 0 & 0 & -1 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \end{pmatrix}, Σ=diag⁡(1,1,0)\Sigma = \operatorname{diag}(1, 1, 0), V=(00.6−0.81000−0.8−0.6)V = \begin{pmatrix} 0 & 0.6 & -0.8 \\ 1 & 0 & 0 \\ 0 & -0.8 & -0.6 \end{pmatrix}, both with determinant 1
L3 Ra=UWVT=RR_a = UWV^{\mathsf T} = R and Rb=UWTVT=(0.800.60−100.60−0.8)R_b = UW^{\mathsf T}V^{\mathsf T} = \begin{pmatrix} 0.8 & 0 & 0.6 \\ 0 & -1 & 0 \\ 0.6 & 0 & -0.8 \end{pmatrix}
L4 u3=(−1,0,0)\mathbf{u}_3 = (-1, 0, 0), so −u3=t-\mathbf{u}_3 = \mathbf{t}
L6, L7 for (Ra,u3)(R_a, \mathbf{u}_3) depths (−5,−4)(-5, -4), c=0c = 0
L6, L7 for (Ra,−u3)(R_a, -\mathbf{u}_3) depths (5,4)(5, 4), c=1c = 1
L6, L7 for (Rb,u3)(R_b, \mathbf{u}_3) depths (57,−47)(\frac57, -\frac47), c=0c = 0
L6, L7 for (Rb,−u3)(R_b, -\mathbf{u}_3) depths (−57,47)(-\frac57, \frac47), c=0c = 0
L8 (R,(1,0,0))(R, (1, 0, 0)) with c=1c = 1

A check of the winner: 5R(0,0,1)T+t=(3,0,4)+(1,0,0)=(4,0,4)=4 (1,0,1)5R(0, 0, 1)^{\mathsf T} + \mathbf{t} = (3, 0, 4) + (1, 0, 0) = (4, 0, 4) = 4\,(1, 0, 1). The four depth pairs follow the pattern of the proof: (λ1,λ2)(\lambda_1, \lambda_2), (−λ1,−λ2)(-\lambda_1, -\lambda_2), and ±(λ1,−λ2)/D\pm(\lambda_1, -\lambda_2)/D for the twisted pair, here with D=7D = 7.

Correctness

A real matrix with singular values (s,s,0)(s, s, 0) has exactly four factorizations [t]×R[\mathbf{t}]_\times R with ∥t∥=s\|\mathbf{t}\| = s and RR a rotation, and they are the four candidates of line L4 up to the scale of t\mathbf{t}. For a point with true depths (λ1,λ2)(\lambda_1, \lambda_2) under one of them, the other three give (−λ1,−λ2)(-\lambda_1, -\lambda_2), (−λ1/D,λ2/D)(-\lambda_1/D, \lambda_2/D) and (λ1/D,−λ2/D)(\lambda_1/D, -\lambda_2/D) for a number DD 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 X2=RX1+t\mathbf{X}_2 = R\mathbf{X}_1 + \mathbf{t}, a point in normalized coordinates is y=(u,v,1)T\mathbf{y} = (u, v, 1)^{\mathsf T}, and the depth of a point in a camera is its ZZ coordinate in that camera. SO(3)SO(3) is the set of rotations, [a]×[\mathbf{a}]_\times is the matrix with [a]×b=a×b[\mathbf{a}]_\times\mathbf{b} = \mathbf{a} \times \mathbf{b}, and

W=(0−10100001),Z=(0−10100000)=[e3]×.W = \begin{pmatrix} 0 & -1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{pmatrix}, \qquad Z = \begin{pmatrix} 0 & -1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix} = [\mathbf{e}_3]_\times .

Claim. Let E=s[t0]×R0E = s[\mathbf{t}_0]_\times R_0 with s≠0s \ne 0, ∥t0∥=1\|\mathbf{t}_0\| = 1 and R0∈SO(3)R_0 \in SO(3). (a) The four pairs of line L4 are exactly the pairs (R,t)∈SO(3)×R3(R, \mathbf{t}) \in SO(3) \times \mathbb{R}^3 with ∥t∥=1\|\mathbf{t}\| = 1 and [t]×R=λE[\mathbf{t}]_\times R = \lambda E for some real λ≠0\lambda \ne 0, and (R0,t0)(R_0, \mathbf{t}_0) is one of them. (b) Let a point have positive depths λ1\lambda_1 and λ2\lambda_2 in the true pose (R0,t0)(R_0, \mathbf{t}_0), and let it not lie on the line through the two camera centers. Then, for the four candidates, the depths of line L6 are (λ1,λ2)(\lambda_1, \lambda_2), (−λ1,−λ2)(-\lambda_1, -\lambda_2), (−λ1/D,λ2/D)(-\lambda_1/D, \lambda_2/D) and (λ1/D,−λ2/D)(\lambda_1/D, -\lambda_2/D), with D=1+2λ1 t0TR0y1D = 1 + 2\lambda_1\,\mathbf{t}_0^{\mathsf T}R_0\mathbf{y}_1, where the last two need D≠0D \ne 0. So only the true pose has both depths positive. (c) On exact data in which at least one point satisfies (b), RECOVER-POSE returns (R0,t0)(R_0, \mathbf{t}_0).

Lemma 1 (rotations and the cross product). For U∈SO(3)U \in SO(3) and a∈R3\mathbf{a} \in \mathbb{R}^3, [Ua]×=U[a]×UT[U\mathbf{a}]_\times = U[\mathbf{a}]_\times U^{\mathsf T}.

Proof. For every b\mathbf{b}, U[a]×UTb=U(a×UTb)=Ua×UUTb=Ua×bU[\mathbf{a}]_\times U^{\mathsf T}\mathbf{b} = U(\mathbf{a} \times U^{\mathsf T}\mathbf{b}) = U\mathbf{a} \times UU^{\mathsf T}\mathbf{b} = U\mathbf{a} \times \mathbf{b}, because a rotation keeps cross products: Up×Uq=U(p×q)U\mathbf{p} \times U\mathbf{q} = U(\mathbf{p} \times \mathbf{q}) when det⁡U=1\det U = 1. □\square

Lemma 2 (the SVD with rotations). The singular values of EE are (∣s∣,∣s∣,0)(|s|, |s|, 0). After line L2, E=Udiag⁡(∣s∣,∣s∣,0)VTE = U\operatorname{diag}(|s|, |s|, 0)V^{\mathsf T} with U,V∈SO(3)U, V \in SO(3), and the third column u3\mathbf{u}_3 of UU spans the null space of ETE^{\mathsf T}.

Proof. EET=s2[t0]×[t0]×T=s2(I−t0t0T)EE^{\mathsf T} = s^2[\mathbf{t}_0]_\times[\mathbf{t}_0]_\times^{\mathsf T} = s^2(I - \mathbf{t}_0\mathbf{t}_0^{\mathsf T}), whose eigenvalues are s2,s2,0s^2, s^2, 0. Line L1 gives an SVD with orthogonal UU and VV. Line L2 changes the sign of the third column of UU or of VV when the determinant is −1-1. The third singular value is 0, so the third columns do not enter the product, and the product stays EE. Now det⁡U=det⁡V=1\det U = \det V = 1. Finally ETu3=Vdiag⁡(∣s∣,∣s∣,0)UTu3=Vdiag⁡(∣s∣,∣s∣,0)e3=0E^{\mathsf T}\mathbf{u}_3 = V\operatorname{diag}(|s|, |s|, 0)U^{\mathsf T}\mathbf{u}_3 = V\operatorname{diag}(|s|, |s|, 0)\mathbf{e}_3 = \mathbf{0}, and the null space has dimension 1. □\square

Proof of part (a). Let [t]×R=λE[\mathbf{t}]_\times R = \lambda E with ∥t∥=1\|\mathbf{t}\| = 1 and λ≠0\lambda \ne 0. Then ETt=λ−1RT[t]×Tt=−λ−1RT(t×t)=0E^{\mathsf T}\mathbf{t} = \lambda^{-1}R^{\mathsf T}[\mathbf{t}]_\times^{\mathsf T}\mathbf{t} = -\lambda^{-1}R^{\mathsf T}(\mathbf{t} \times \mathbf{t}) = \mathbf{0}, so by Lemma 2, t=±u3\mathbf{t} = \pm\mathbf{u}_3. Write t=ϵu3=ϵUe3\mathbf{t} = \epsilon\mathbf{u}_3 = \epsilon U\mathbf{e}_3 with ϵ=±1\epsilon = \pm 1. By Lemma 1, [t]×=ϵUZUT[\mathbf{t}]_\times = \epsilon UZU^{\mathsf T}. Put Q=UTRV∈SO(3)Q = U^{\mathsf T}RV \in SO(3). The equation becomes ϵUZQVT=λ∣s∣ Udiag⁡(1,1,0)VT\epsilon UZQV^{\mathsf T} = \lambda|s|\,U\operatorname{diag}(1, 1, 0)V^{\mathsf T}, that is,

ZQ=μdiag⁡(1,1,0),μ=ϵλ∣s∣≠0.ZQ = \mu\operatorname{diag}(1, 1, 0), \qquad \mu = \epsilon\lambda|s| \ne 0 .

The rows of ZQZQ are (−q2T,q1T,0T)(-\mathbf{q}_2^{\mathsf T}, \mathbf{q}_1^{\mathsf T}, \mathbf{0}^{\mathsf T}), where qjT\mathbf{q}_j^{\mathsf T} is row jj of QQ. So q1=μe2\mathbf{q}_1 = \mu\mathbf{e}_2 and q2=−μe1\mathbf{q}_2 = -\mu\mathbf{e}_1. Rows of an orthogonal matrix are unit vectors, so μ=±1\mu = \pm 1, and q3\mathbf{q}_3 is the unit vector that makes det⁡Q=1\det Q = 1, which is e3\mathbf{e}_3 in both cases. For μ=1\mu = 1, Q=WTQ = W^{\mathsf T}; for μ=−1\mu = -1, Q=WQ = W. So R=UWVTR = UWV^{\mathsf T} or R=UWTVTR = UW^{\mathsf T}V^{\mathsf T}, and (R,t)(R, \mathbf{t}) is one of the four pairs of lines L3 and L4.

Conversely, each of the four pairs has R∈SO(3)R \in SO(3) (a product of rotations) and ∥t∥=1\|\mathbf{t}\| = 1, and the computation above, read backwards, gives [t]×R=ϵUZQVT=±Udiag⁡(1,1,0)VT=±E/∣s∣[\mathbf{t}]_\times R = \epsilon UZ Q V^{\mathsf T} = \pm U\operatorname{diag}(1, 1, 0)V^{\mathsf T} = \pm E/|s|. The two rotations differ, because W≠WTW \ne W^{\mathsf T}, so the four pairs are distinct. The true pose satisfies [t0]×R0=E/s[\mathbf{t}_0]_\times R_0 = E/s, so it is one of them. □\square

Lemma 3 (the twisted pair). UWTVT=Rπ UWVTUW^{\mathsf T}V^{\mathsf T} = R_\pi\,UWV^{\mathsf T}, where Rπ=2u3u3T−IR_\pi = 2\mathbf{u}_3\mathbf{u}_3^{\mathsf T} - I is the rotation by π\pi about u3\mathbf{u}_3.

Proof. WTWT=diag⁡(−1,−1,1)W^{\mathsf T}W^{\mathsf T} = \operatorname{diag}(-1, -1, 1), so UWTVT=Udiag⁡(−1,−1,1)UT UWVTUW^{\mathsf T}V^{\mathsf T} = U\operatorname{diag}(-1, -1, 1)U^{\mathsf T}\,UWV^{\mathsf T}, and Udiag⁡(−1,−1,1)UT=2u3u3T−IU\operatorname{diag}(-1, -1, 1)U^{\mathsf T} = 2\mathbf{u}_3\mathbf{u}_3^{\mathsf T} - I. This matrix keeps u3\mathbf{u}_3 and reverses every vector orthogonal to it. □\square

Since t0=±u3\mathbf{t}_0 = \pm\mathbf{u}_3, also Rπ=2t0t0T−IR_\pi = 2\mathbf{t}_0\mathbf{t}_0^{\mathsf T} - I. By part (a) and Lemma 3, the four candidates are (R0,t0)(R_0, \mathbf{t}_0), (R0,−t0)(R_0, -\mathbf{t}_0), (RπR0,t0)(R_\pi R_0, \mathbf{t}_0) and (RπR0,−t0)(R_\pi R_0, -\mathbf{t}_0).

Lemma 4 (the depths of line L6). For a pose (R,t)(R, \mathbf{t}) and a pair (y1,y2)(\mathbf{y}_1, \mathbf{y}_2), let a=Ry1\mathbf{a} = R\mathbf{y}_1 and assume that a\mathbf{a} and y2\mathbf{y}_2 are linearly independent. Then the function depths returns the unique minimizer (μ1,μ2)(\mu_1, \mu_2) of ∥μ1a−μ2y2+t∥\|\mu_1\mathbf{a} - \mu_2\mathbf{y}_2 + \mathbf{t}\|. If μ2y2=μ1a+t\mu_2\mathbf{y}_2 = \mu_1\mathbf{a} + \mathbf{t} has a solution, this minimizer is that solution, and μ1\mu_1 and μ2\mu_2 are the depths of the point μ1y1\mu_1\mathbf{y}_1 in the two cameras.

Proof. The function is the norm of Nμ+tN\boldsymbol{\mu} + \mathbf{t} with N=[a,−y2]N = [\mathbf{a}, -\mathbf{y}_2], a 3×23 \times 2 matrix of rank 2. The normal equations NTNμ=−NTtN^{\mathsf T}N\boldsymbol{\mu} = -N^{\mathsf T}\mathbf{t} have a positive definite matrix, with determinant ∥a∥2∥y2∥2−(aTy2)2>0\|\mathbf{a}\|^2\|\mathbf{y}_2\|^2 - (\mathbf{a}^{\mathsf T}\mathbf{y}_2)^2 > 0 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 X1=μ1y1\mathbf{X}_1 = \mu_1\mathbf{y}_1 has third entry μ1\mu_1, and X2=RX1+t=μ2y2\mathbf{X}_2 = R\mathbf{X}_1 + \mathbf{t} = \mu_2\mathbf{y}_2 has third entry μ2\mu_2. □\square

Proof of part (b). The true pose gives λ2y2=λ1a+t0\lambda_2\mathbf{y}_2 = \lambda_1\mathbf{a} + \mathbf{t}_0 with a=R0y1\mathbf{a} = R_0\mathbf{y}_1. The point is not on the line through the centers, so a\mathbf{a} and t0\mathbf{t}_0 are independent, and then a\mathbf{a} and y2\mathbf{y}_2 are independent too. The rotated ray of a candidate is a\mathbf{a} or Rπa=2(t0Ta)t0−aR_\pi\mathbf{a} = 2(\mathbf{t}_0^{\mathsf T}\mathbf{a})\mathbf{t}_0 - \mathbf{a}. Since a\mathbf{a} and t0\mathbf{t}_0 are independent, RπaR_\pi\mathbf{a} is a multiple c(λ1a+t0)c(\lambda_1\mathbf{a} + \mathbf{t}_0) of y2\mathbf{y}_2 exactly when −1=cλ1-1 = c\lambda_1 and 2t0Ta=c2\mathbf{t}_0^{\mathsf T}\mathbf{a} = c, that is, when D=0D = 0. So Lemma 4 applies to all four candidates when D≠0D \ne 0.

For (R0,t0)(R_0, \mathbf{t}_0) the solution is (λ1,λ2)(\lambda_1, \lambda_2). For (R0,−t0)(R_0, -\mathbf{t}_0) the equation μ2y2=μ1a−t0\mu_2\mathbf{y}_2 = \mu_1\mathbf{a} - \mathbf{t}_0 is solved by (−λ1,−λ2)(-\lambda_1, -\lambda_2).

For (RπR0,t0)(R_\pi R_0, \mathbf{t}_0) we need μ2y2=μ1Rπa+t0=−μ1a+(1+2μ1t0Ta) t0\mu_2\mathbf{y}_2 = \mu_1R_\pi\mathbf{a} + \mathbf{t}_0 = -\mu_1\mathbf{a} + (1 + 2\mu_1\mathbf{t}_0^{\mathsf T}\mathbf{a})\,\mathbf{t}_0. Since λ2y2=λ1a+t0\lambda_2\mathbf{y}_2 = \lambda_1\mathbf{a} + \mathbf{t}_0 and a\mathbf{a}, t0\mathbf{t}_0 are independent, the right side is a multiple kλ2y2k\lambda_2\mathbf{y}_2 exactly when −μ1=kλ1-\mu_1 = k\lambda_1 and 1+2μ1t0Ta=k1 + 2\mu_1\mathbf{t}_0^{\mathsf T}\mathbf{a} = k. Then k(1+2λ1t0Ta)=1k(1 + 2\lambda_1\mathbf{t}_0^{\mathsf T}\mathbf{a}) = 1, so k=1/Dk = 1/D, μ1=−λ1/D\mu_1 = -\lambda_1/D and μ2=kλ2=λ2/D\mu_2 = k\lambda_2 = \lambda_2/D. For (RπR0,−t0)(R_\pi R_0, -\mathbf{t}_0), the solution is the negative of this one, (λ1/D,−λ2/D)(\lambda_1/D, -\lambda_2/D). In both cases μ1μ2=−λ1λ2/D2<0\mu_1\mu_2 = -\lambda_1\lambda_2/D^2 < 0. If D=0D = 0, the rays of the two twisted candidates are parallel, as shown above. The function depths then finds a zero determinant and returns (0,0)(0, 0), so neither twisted candidate counts the point. □\square

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 (0,0)(0, 0), so no candidate counts it. So on exact data the true pose has the strictly largest count, and line L8 returns it. ■\blacksquare

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 3×33 \times 3 matrix and the four candidates take a fixed amount of work. The depth test costs Θ(1)\Theta(1) for each pair and each of the four candidates, so the total time is Θ(n)\Theta(n). The extra space is Θ(1)\Theta(1), 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 3×33 \times 3 matrices.

Properties

  • Exactly four candidates. For each essential matrix, up to the scale of t\mathbf{t}.
  • Sign of EE does not matter. −E-E gives the same four candidates in another order.
  • Scale of t\mathbf{t} is lost. The output has ∥t∥=1\|\mathbf{t}\| = 1; 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. Rb=RπRaR_b = R_\pi R_a with RπR_\pi 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 2×22 \times 2 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 ETE^{\mathsf T}, found from a cross product of two rows of EE, and the rotation can be written from the rows of EE and t\mathbf{t}; 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 EE: the five-point algorithm in RANSAC, the eight-point algorithm on inliers, or E=K2TFK1E = K_2^{\mathsf T}FK_1 from a fundamental matrix. Run the depth test on the inliers, not on all matches. If the estimate of EE is not exactly essential, the SVD step still works, because it uses only UU and VV; that is the same as first projecting onto the closest essential matrix.

Pitfalls

  • Forgetting line L2. If det⁡U=−1\det U = -1 or det⁡V=−1\det V = -1, the matrices UWVTUWV^{\mathsf T} have determinant −1-1 and are reflections, not rotations.
  • Two candidates only. Testing only ±t\pm\mathbf{t} 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 X2=RX1+t\mathbf{X}_2 = R\mathbf{X}_1 + \mathbf{t} and x^2TEx^1=0\hat{\mathbf{x}}_2^{\mathsf T}E\hat{\mathbf{x}}_1 = 0. Libraries that use the camera center or the other direction give RTR^{\mathsf T} and −RTt-R^{\mathsf T}\mathbf{t}.
  • Pure rotation. If the true t\mathbf{t} is zero, EE 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.

cvla.pyI0RawGitHub
# 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 WW 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

  1. 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)
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example