Algorithm Search⌘K

Algorithmadvanced

Homography decomposition

Also called Faugeras-Lustman decomposition, Malis-Vargas decomposition.

Recover the rotation, the scaled translation and the plane normal from a calibrated homography of a plane, up to a few solutions told apart by visibility.

Time
Θ(n) worst · average · best
Space
Θ(n) extra
Where
n = the number of point pairs used for the sign and visibility tests
Properties
deterministicexactofflineiterative
Origin
Olivier Faugeras, Francis Lustman, 1988

Homography decomposition takes the homography GG that a plane induces between two calibrated views and returns the camera motion and the plane: the rotation RR, the translation divided by the distance of the plane, t/d\mathbf{t}/d, and the unit normal n\mathbf{n}. In general it finds four candidates in two pairs, and the condition that the points of the plane are in front of the first camera keeps two of them. It is the planar counterpart of essential matrix decomposition, and it is used where the essential matrix fails because the scene is a plane. Homography estimation and the DLT find GG from matches; this page starts from GG.

In plain words

When a camera looks at a flat floor from two places, one 3×33 \times 3 table maps the floor in the first photo onto the floor in the second. That table is built from three things: how the camera turned, how it moved, and how the floor is tilted. This method takes the table apart again. The amount of movement comes out only as a ratio to the distance of the floor, because a scene twice as big seen from twice as far gives the same photos. The math gives four possible answers. Two of them put the floor behind the camera, so they are dropped. The other two both fit the two photos perfectly, and only more information, such as a third photo or a rough idea of where the floor is, can tell which one is true.

The problem

Input. A 3×33 \times 3 matrix GG, known only up to a nonzero factor of either sign, with x2∼Gx1\mathbf{x}_2 \sim G\mathbf{x}_1 for the pixels of a plane in two images; the intrinsic matrices K1K_1 and K2K_2; and at least one pair of pixels x1↔x2\mathbf{x}_1 \leftrightarrow \mathbf{x}_2 of points on the plane, seen in front of both cameras.

Convention. The plane is nTX1=d\mathbf{n}^{\mathsf T}\mathbf{X}_1 = d in the frame of camera 1, with ∥n∥=1\|\mathbf{n}\| = 1 and d>0d > 0, and X2=RX1+t\mathbf{X}_2 = R\mathbf{X}_1 + \mathbf{t}. Then G∼K2(R+tnT/d)K1−1G \sim K_2(R + \mathbf{t}\mathbf{n}^{\mathsf T}/d)K_1^{-1}. Both cameras see the plane from the same side. Hartley and Zisserman write the plane as nTX+d=0\mathbf{n}^{\mathsf T}\mathbf{X} + d = 0 and get a minus sign in the formula.

Output. Every triple (R,t′=t/d,n)(R, \mathbf{t}' = \mathbf{t}/d, \mathbf{n}) with RR a rotation, n\mathbf{n} a unit vector, K2−1GK1∼R+t′nTK_2^{-1}GK_1 \sim R + \mathbf{t}'\mathbf{n}^{\mathsf T}, and nTK1−1x1>0\mathbf{n}^{\mathsf T}K_1^{-1}\mathbf{x}_1 > 0 for the given points. In the general case there are two. If the camera did not move (t=0\mathbf{t} = \mathbf{0}), the output is RR alone, since then every plane induces the same homography and n\mathbf{n} is not defined.

The algorithm

  1. DECOMPOSE-HOMOGRAPHY(G, K1, K2, pairs (x1_i, x2_i))
  2. 1H <- K2^-1 G K1 ; y1_i <- K1^-1 x1_i ; y2_i <- K2^-1 x2_i
  3. 2H <- H / sigma2(H) ▷ the middle singular value
  4. 3if y2_i^T H y1_i < 0 for most i then H <- -H
  5. 4(v1, v2, v3), (s1, s2, s3) <- right singular vectors and singular values of H ; l1 <- s1^2 ; l3 <- s3^2
  6. 5if l1 - l3 < eps then return [ (the orthogonal factor of H, 0, undefined) ]
  7. 6for u in { (sqrt(1 - l3) v1 + sqrt(l1 - 1) v3) / sqrt(l1 - l3) , (sqrt(1 - l3) v1 - sqrt(l1 - 1) v3) / sqrt(l1 - l3) }
  8. 7U <- [ v2, u, v2 x u ] ; W <- [ H v2, H u, H v2 x H u ] ▷ columns
  9. 8R <- W U^T ; n <- v2 x u ; t <- (H - R) n
  10. 9add (R, t, n) and (R, -t, -n) to the candidates
  11. 10keep the candidates with n^T y1_i > 0 for most i
  12. 11return the kept candidates

Line L1 removes the calibration, so that H∼R+t′nTH \sim R + \mathbf{t}'\mathbf{n}^{\mathsf T}. The middle singular value of every matrix of the form R+t′nTR + \mathbf{t}'\mathbf{n}^{\mathsf T} is exactly 1, so line L2 fixes the scale up to sign. Line L3 fixes the sign: for a point of the plane with depths z1,z2>0z_1, z_2 > 0 in the two cameras, (R+t′nT)y1=(z2/z1)y2(R + \mathbf{t}'\mathbf{n}^{\mathsf T})\mathbf{y}_1 = (z_2/z_1)\mathbf{y}_2, so y2THy1>0\mathbf{y}_2^{\mathsf T}H\mathbf{y}_1 > 0 for the right sign. Lines L4 to L8 use the fact that HH acts as the rotation RR on the plane of vectors orthogonal to n\mathbf{n}, where it keeps lengths. The vector v2v_2 and each of the two vectors uu of line L6 span a plane on which HH keeps lengths, and there are no other such planes. On the right one, RR is fixed by its action on v2v_2 and uu, and n\mathbf{n} is the normal of the plane up to sign. Line L9 adds the other sign of n\mathbf{n} with the matching t′\mathbf{t}'. Line L10 is the visibility test: a point X1=z1y1\mathbf{X}_1 = z_1\mathbf{y}_1 of the plane in front of camera 1 has nTy1=d/z1>0\mathbf{n}^{\mathsf T}\mathbf{y}_1 = d/z_1 > 0. Of each pair (R,t,n)(R, \mathbf{t}, \mathbf{n}), (R,−t,−n)(R, -\mathbf{t}, -\mathbf{n}) exactly one passes. The majority votes in L3 and L10 make the tests robust to a few bad points.

Example

Take K1=K2=IK_1 = K_2 = I, 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)T\mathbf{t} = (1, 0, 0)^{\mathsf T}, n=(0,0,1)T\mathbf{n} = (0, 0, 1)^{\mathsf T} and d=2d = 2, so G=R+tnT/2=(0.801.1010−0.600.8)G = R + \mathbf{t}\mathbf{n}^{\mathsf T}/2 = \begin{pmatrix} 0.8 & 0 & 1.1 \\ 0 & 1 & 0 \\ -0.6 & 0 & 0.8 \end{pmatrix}. The points (0,0)(0, 0), (0.2,0.1)(0.2, 0.1), (−0.2,0.1)(-0.2, 0.1) of image 1 map to (1.375,0)(1.375, 0), (1.8529,0.1471)(1.8529, 0.1471), (1.0217,0.1087)(1.0217, 0.1087).

line value
L1 to L3 H=GH = G; the singular values are 1.41731.4173, 11, 0.91730.9173; all three votes are positive
L4 v1=(0.3686,0,0.9296)v_1 = (0.3686, 0, 0.9296), v2=(0,1,0)v_2 = (0, 1, 0), v3=(0.9296,0,−0.3686)v_3 = (0.9296, 0, -0.3686); l1=2.0086l_1 = 2.0086, l3=0.8414l_3 = 0.8414
L6, first uu u=(1,0,0)u = (1, 0, 0), n=v2×u=(0,0,−1)\mathbf{n} = v_2 \times u = (0, 0, -1), RR is the true RR, t′=(−0.5,0,0)\mathbf{t}' = (-0.5, 0, 0)
L6, second uu u=(−0.7283,0,0.6853)u = (-0.7283, 0, 0.6853), n=(0.6853,0,0.7283)\mathbf{n} = (0.6853, 0, 0.7283), R=(0.550500.8349010−0.834900.5505)R = \begin{pmatrix} 0.5505 & 0 & 0.8349 \\ 0 & 1 & 0 \\ -0.8349 & 0 & 0.5505 \end{pmatrix}, t′=(0.3641,0,0.3427)\mathbf{t}' = (0.3641, 0, 0.3427)
L9 four candidates: the two above and the two with −t′-\mathbf{t}' and −n-\mathbf{n}
L10 n=(0,0,−1)\mathbf{n} = (0, 0, -1) and (−0.6853,0,−0.7283)(-0.6853, 0, -0.7283) fail at y1=(0,0,1)\mathbf{y}_1 = (0, 0, 1); two remain

The two answers are the true motion, t′=(0.5,0,0)\mathbf{t}' = (0.5, 0, 0) with n=(0,0,1)\mathbf{n} = (0, 0, 1), and a turn of about 56.656.6 degrees about the yy axis with the plane tilted. Both satisfy R+t′nT=HR + \mathbf{t}'\mathbf{n}^{\mathsf T} = H exactly, so the two images cannot tell them apart.

Correctness

Every matrix R+t′nTR + \mathbf{t}'\mathbf{n}^{\mathsf T} has middle singular value 1, and the sign test is positive for the right sign, so after L3 HH equals R+t′nTR + \mathbf{t}'\mathbf{n}^{\mathsf T} exactly. The quadratic form wT(HTH−I)w\mathbf{w}^{\mathsf T}(H^{\mathsf T}H - I)\mathbf{w} vanishes on the plane orthogonal to the true n\mathbf{n}. Its zero set is the union of the two planes spanned by v2v_2 and the two vectors of line L6, so the true plane is one of them, and the true solution is one of the four candidates. Every candidate satisfies R+t′nT=HR + \mathbf{t}'\mathbf{n}^{\mathsf T} = H and has RR a rotation. The visibility test keeps exactly one of each pair. The full proof is below.

Proof: The decomposition returns the true motion and plane, and every candidate it returns reproduces the homographyfull

We use the notation of the page. The true motion is a rotation R0R_0, a vector t0=t/d\mathbf{t}_0 = \mathbf{t}/d and a unit normal n0\mathbf{n}_0, and the input is G=μK2(R0+t0n0T)K1−1G = \mu K_2(R_0 + \mathbf{t}_0\mathbf{n}_0^{\mathsf T})K_1^{-1} with an unknown real μ≠0\mu \ne 0. The given pairs are images of points X1\mathbf{X}_1 of the plane n0TX1=d>0\mathbf{n}_0^{\mathsf T}\mathbf{X}_1 = d > 0 with positive depths z1z_1 in camera 1 and z2z_2 in camera 2, so X1=z1y1\mathbf{X}_1 = z_1\mathbf{y}_1 and X2=R0X1+t=z2y2\mathbf{X}_2 = R_0\mathbf{X}_1 + \mathbf{t} = z_2\mathbf{y}_2, where yk=Kk−1xk\mathbf{y}_k = K_k^{-1}\mathbf{x}_k has last entry 1. Both cameras are on the same side of the plane. Write H0=R0+t0n0TH_0 = R_0 + \mathbf{t}_0\mathbf{n}_0^{\mathsf T}.

Claim. If t0≠0\mathbf{t}_0 \ne \mathbf{0}, DECOMPOSE-HOMOGRAPHY returns a list of triples (R,t′,n)(R, \mathbf{t}', \mathbf{n}) such that (a) each has RR a rotation, ∥n∥=1\|\mathbf{n}\| = 1 and R+t′nT=H0R + \mathbf{t}'\mathbf{n}^{\mathsf T} = H_0; (b) each has nTy1>0\mathbf{n}^{\mathsf T}\mathbf{y}_1 > 0 for the given points; (c) (R0,t0,n0)(R_0, \mathbf{t}_0, \mathbf{n}_0) is in the list; (d) the list has at most two distinct triples. If t0=0\mathbf{t}_0 = \mathbf{0}, it returns R0R_0.

Lemma 1 (the middle singular value). For every rotation RR, vector t\mathbf{t} and unit vector n\mathbf{n}, the matrix M=R+tnTM = R + \mathbf{t}\mathbf{n}^{\mathsf T} has singular values s1≥s2=1≥s3s_1 \ge s_2 = 1 \ge s_3.

Proof. Let u=RTt\mathbf{u} = R^{\mathsf T}\mathbf{t}. Then MTM=I+nuT+unT+∥u∥2nnT=I+anT+naTM^{\mathsf T}M = I + \mathbf{n}\mathbf{u}^{\mathsf T} + \mathbf{u}\mathbf{n}^{\mathsf T} + \|\mathbf{u}\|^2\mathbf{n}\mathbf{n}^{\mathsf T} = I + \mathbf{a}\mathbf{n}^{\mathsf T} + \mathbf{n}\mathbf{a}^{\mathsf T} with a=u+12∥u∥2n\mathbf{a} = \mathbf{u} + \frac12\|\mathbf{u}\|^2\mathbf{n}. The symmetric matrix S=anT+naTS = \mathbf{a}\mathbf{n}^{\mathsf T} + \mathbf{n}\mathbf{a}^{\mathsf T} is 0 on the vectors orthogonal to both a\mathbf{a} and n\mathbf{n}. If a\mathbf{a} and n\mathbf{n} are independent, its other two eigenvalues are aTn±∥a∥\mathbf{a}^{\mathsf T}\mathbf{n} \pm \|\mathbf{a}\|, as a direct check on the vectors n±a/∥a∥\mathbf{n} \pm \mathbf{a}/\|\mathbf{a}\| shows; one is ≥0\ge 0 and one is ≤0\le 0. If a=αn\mathbf{a} = \alpha\mathbf{n}, then S=2αnnTS = 2\alpha\mathbf{n}\mathbf{n}^{\mathsf T} has eigenvalues 2α,0,02\alpha, 0, 0. In both cases the eigenvalues of MTM=I+SM^{\mathsf T}M = I + S, sorted, are s12≥1≥s32s_1^2 \ge 1 \ge s_3^2 with the middle one equal to 1. □\square

Lemma 2 (scale and sign). After line L3, H=H0H = H_0.

Proof. After line L1, H=μH0H = \mu H_0. By Lemma 1 the middle singular value of HH is ∣μ∣|\mu|, so after line L2, H=±H0H = \pm H_0. For a given pair, H0y1=(R0X1+t n0TX1/d)/z1=X2/z1=(z2/z1)y2H_0\mathbf{y}_1 = (R_0\mathbf{X}_1 + \mathbf{t}\,\mathbf{n}_0^{\mathsf T}\mathbf{X}_1/d)/z_1 = \mathbf{X}_2/z_1 = (z_2/z_1)\mathbf{y}_2, using n0TX1=d\mathbf{n}_0^{\mathsf T}\mathbf{X}_1 = d. So y2TH0y1=(z2/z1)∥y2∥2>0\mathbf{y}_2^{\mathsf T}H_0\mathbf{y}_1 = (z_2/z_1)\|\mathbf{y}_2\|^2 > 0 for every pair, every vote of line L3 has the sign of the factor ±1\pm 1, and the line makes it +1+1. □\square

From now on H=H0H = H_0, and l1=s12l_1 = s_1^2, l3=s32l_3 = s_3^2, with right singular vectors v1,v2,v3v_1, v_2, v_3, so HTHvk=sk2vkH^{\mathsf T}H v_k = s_k^2 v_k and s2=1s_2 = 1.

Lemma 3 (pure rotation). l1=l3l_1 = l_3 if and only if HTH=IH^{\mathsf T}H = I. Under the same side condition, this holds if and only if t0=0\mathbf{t}_0 = \mathbf{0}, and then H=R0H = R_0.

Proof. By Lemma 1, l1=l3l_1 = l_3 means that all eigenvalues of HTHH^{\mathsf T}H are 1. In the notation of Lemma 1 this is S=0S = 0. Applying SS to n\mathbf{n} gives a+(aTn)n=0\mathbf{a} + (\mathbf{a}^{\mathsf T}\mathbf{n})\mathbf{n} = \mathbf{0}, so a=−(aTn)n\mathbf{a} = -(\mathbf{a}^{\mathsf T}\mathbf{n})\mathbf{n}, and taking the inner product with n\mathbf{n} gives aTn=0\mathbf{a}^{\mathsf T}\mathbf{n} = 0 and then a=0\mathbf{a} = \mathbf{0}. So u=−12∥u∥2n\mathbf{u} = -\frac12\|\mathbf{u}\|^2\mathbf{n}: either u=0\mathbf{u} = \mathbf{0}, or ∥u∥=2\|\mathbf{u}\| = 2 and u=−2n\mathbf{u} = -2\mathbf{n}. In the second case H=R0(I−2nnT)H = R_0(I - 2\mathbf{n}\mathbf{n}^{\mathsf T}) has determinant −1-1. But det⁡H=1+n0TR0Tt0\det H = 1 + \mathbf{n}_0^{\mathsf T}R_0^{\mathsf T}\mathbf{t}_0, and the center of camera 2, C2=−R0Tt\mathbf{C}_2 = -R_0^{\mathsf T}\mathbf{t}, is on the side of camera 1 exactly when n0TC2<d\mathbf{n}_0^{\mathsf T}\mathbf{C}_2 < d, that is, when det⁡H>0\det H > 0. So under the same side condition only u=0\mathbf{u} = \mathbf{0} remains, which is t0=0\mathbf{t}_0 = \mathbf{0}, and H=R0H = R_0 is orthogonal; its orthogonal factor, returned by line L5, is R0R_0 itself. □\square

Assume now t0≠0\mathbf{t}_0 \ne \mathbf{0}, so l1>l3l_1 > l_3 and line L6 is well defined: 1−l3≥01 - l_3 \ge 0 and l1−1≥0l_1 - 1 \ge 0 by Lemma 1.

Lemma 4 (the planes on which HH keeps lengths). Let Q(w)=wT(HTH−I)wQ(\mathbf{w}) = \mathbf{w}^{\mathsf T}(H^{\mathsf T}H - I)\mathbf{w}. A 2-dimensional subspace PP of R3\mathbb{R}^3 has Q=0Q = 0 on all of PP if and only if PP is spanned by v2v_2 and one of the two vectors uu of line L6.

Proof. In the coordinates w=av1+bv2+cv3\mathbf{w} = a v_1 + b v_2 + c v_3, Q(w)=(l1−1)a2−(1−l3)c2Q(\mathbf{w}) = (l_1 - 1)a^2 - (1 - l_3)c^2, with both coefficients ≥0\ge 0 and not both 0. If both are positive, Q=0Q = 0 exactly on the two planes l1−1 a=±1−l3 c\sqrt{l_1 - 1}\,a = \pm\sqrt{1 - l_3}\,c, which contain v2v_2 and the vectors 1−l3 v1±l1−1 v3\sqrt{1 - l_3}\,v_1 \pm \sqrt{l_1 - 1}\,v_3, the vectors of line L6 up to a positive factor. If l1=1l_1 = 1, Q=−(1−l3)c2Q = -(1 - l_3)c^2 vanishes only on the plane c=0c = 0, spanned by v2v_2 and v1v_1; line L6 then gives u=v1u = v_1 twice. If l3=1l_3 = 1, the zero set is the plane a=0a = 0, spanned by v2v_2 and v3v_3, and line L6 gives u=±v3u = \pm v_3. So the zero set of QQ is a union of at most two planes, each of the stated form. A 2-dimensional subspace inside a union of two planes through the origin is one of them, since a vector space is never the union of two proper subspaces. Conversely, QQ vanishes on each stated plane. □\square

Lemma 5 (the candidates). Let uu be one of the vectors of line L6, and let RR, n\mathbf{n} and t\mathbf{t} be as in lines L7 and L8. Then ∥u∥=1\|u\| = 1, u⊥v2u \perp v_2, RR is a rotation, ∥n∥=1\|\mathbf{n}\| = 1, and R+tnT=HR + \mathbf{t}\mathbf{n}^{\mathsf T} = H. The same holds for (R,−t,−n)(R, -\mathbf{t}, -\mathbf{n}).

Proof. ∥u∥2=((1−l3)+(l1−1))/(l1−l3)=1\|u\|^2 = ((1 - l_3) + (l_1 - 1))/(l_1 - l_3) = 1, and uu is a combination of v1v_1 and v3v_3, so u⊥v2u \perp v_2. So U=[v2,u,v2×u]U = [v_2, u, v_2 \times u] is a rotation. Next, ∥Hu∥2=uTHTHu=(l1(1−l3)+l3(l1−1))/(l1−l3)=1\|Hu\|^2 = u^{\mathsf T}H^{\mathsf T}Hu = (l_1(1 - l_3) + l_3(l_1 - 1))/(l_1 - l_3) = 1, ∥Hv2∥2=1\|Hv_2\|^2 = 1, and (Hv2)T(Hu)=v2THTHu=0(Hv_2)^{\mathsf T}(Hu) = v_2^{\mathsf T}H^{\mathsf T}Hu = 0, because HTHuH^{\mathsf T}Hu is a combination of v1v_1 and v3v_3. So W=[Hv2,Hu,Hv2×Hu]W = [Hv_2, Hu, Hv_2 \times Hu] is also a rotation, and R=WUTR = WU^{\mathsf T} is a rotation with Rv2=Hv2Rv_2 = Hv_2 and Ru=HuRu = Hu. The vector n=v2×u\mathbf{n} = v_2 \times u is a unit vector orthogonal to v2v_2 and uu. Let t=(H−R)n\mathbf{t} = (H - R)\mathbf{n}. Then (R+tnT)(R + \mathbf{t}\mathbf{n}^{\mathsf T}) agrees with HH on v2v_2 and on uu, because nTv2=nTu=0\mathbf{n}^{\mathsf T}v_2 = \mathbf{n}^{\mathsf T}u = 0, and on n\mathbf{n}, because Rn+t=HnR\mathbf{n} + \mathbf{t} = H\mathbf{n}. These three vectors are a basis, so R+tnT=HR + \mathbf{t}\mathbf{n}^{\mathsf T} = H. Finally R+(−t)(−n)T=R+tnTR + (-\mathbf{t})(-\mathbf{n})^{\mathsf T} = R + \mathbf{t}\mathbf{n}^{\mathsf T}. □\square

Lemma 6 (the true triple is a candidate). (R0,t0,n0)(R_0, \mathbf{t}_0, \mathbf{n}_0) is one of the four triples of line L9.

Proof. For w⊥n0\mathbf{w} \perp \mathbf{n}_0, Hw=R0wH\mathbf{w} = R_0\mathbf{w}, so ∥Hw∥=∥w∥\|H\mathbf{w}\| = \|\mathbf{w}\| and Q=0Q = 0 on the plane P0=n0⊥P_0 = \mathbf{n}_0^{\perp}. By Lemma 4, P0P_0 is spanned by v2v_2 and one vector uu of line L6. For this uu, R0R_0 and the matrix RR of line L8 agree on the orthonormal basis v2,uv_2, u of P0P_0 (both equal HH there), and they are rotations, so they also agree on v2×uv_2 \times u: R=R0R = R_0. The normal of P0P_0 is n0=±(v2×u)=±n\mathbf{n}_0 = \pm(v_2 \times u) = \pm\mathbf{n}. If n0=n\mathbf{n}_0 = \mathbf{n}, then t0=(H−R0)n0=t\mathbf{t}_0 = (H - R_0)\mathbf{n}_0 = \mathbf{t}; if n0=−n\mathbf{n}_0 = -\mathbf{n}, then t0=−t\mathbf{t}_0 = -\mathbf{t}. Either way the true triple is one of the two triples that line L9 adds for this uu. □\square

Proof of the claim. The case t0=0\mathbf{t}_0 = \mathbf{0} is Lemma 3. Otherwise, by Lemma 2 the algorithm works with H=H0H = H_0. Part (a) is Lemma 5 for every candidate. Line L10 keeps only triples with a majority of positive values nTy1\mathbf{n}^{\mathsf T}\mathbf{y}_1. For the true triple, n0Ty1=n0TX1/z1=d/z1>0\mathbf{n}_0^{\mathsf T}\mathbf{y}_1 = \mathbf{n}_0^{\mathsf T}\mathbf{X}_1/z_1 = d/z_1 > 0 for every pair, so it is kept, which with Lemma 6 gives (c). Every other kept triple (R,t,n)(R, \mathbf{t}, \mathbf{n}) satisfies R+tnT=H0R + \mathbf{t}\mathbf{n}^{\mathsf T} = H_0, so the plane it describes is n⊥\mathbf{n}^{\perp} for one of the two planes of Lemma 4; the votes for n\mathbf{n} and −n-\mathbf{n} are opposite, so of each pair of line L9 at most one is kept, which gives (b) and (d): two vectors uu, one triple each. ■\blacksquare

Remark (why two remain). The second triple is a genuine other motion and plane that produce the same HH, so no test on the two images can remove it in general. In the example of the page it passes every test above. A further test, such as positive depth in camera 2 for points computed with the second plane, removes it only in some configurations.

Complexity

The work on HH is a fixed number of operations on 3×33 \times 3 matrices, including two SVDs, so it costs Θ(1)\Theta(1) in the real RAM with square roots. The two majority votes look at each of the nn pairs once, so they cost Θ(n)\Theta(n). The implementation stores the nn normalized points, Θ(n)\Theta(n) extra space; the votes can also be computed while reading the pairs, in Θ(1)\Theta(1) space. The estimate of GG that comes before, by the DLT, costs Θ(n)\Theta(n) as well.

Properties

  • Exact. On an exact GG every returned triple reproduces GG up to scale, and the true triple is always returned.
  • Two answers in general. Of the four candidates, two have positive depths (Ma et al., Theorem 5.19). Both reproduce HH exactly, so the two views alone do not decide between them.
  • One answer in special cases. If t\mathbf{t} is parallel to RnR\mathbf{n}, the camera moves along the normal of the plane, the smallest or largest singular value equals 1, and the two vectors of line L6 are ±\pm one singular vector. The two pairs then coincide, and the kept list holds one triple twice.
  • Scale. Only t/d\mathbf{t}/d is recovered. The absolute translation needs the distance dd of the plane from another source.
  • Free of the scale and sign of GG. GG and μG\mu G give the same output for every μ≠0\mu \ne 0.

Variants and improvements

  • Faugeras and Lustman (1988). They work with the SVD H=UΛVTH = U\Lambda V^{\mathsf T} and solve for the motion in the frame of the singular vectors, with a case analysis on equal singular values, and use the depth conditions to discard solutions.
  • Malis and Vargas (2007). Closed-form expressions for the solutions in terms of the entries of HTH−IH^{\mathsf T}H - I, with no SVD, and formulas that relate the two physically valid solutions to each other. They are convenient for visual servoing.
  • Choosing between the two answers. Use a rough prior on the normal (for a ground plane, the vertical direction), a third view, a second plane, or the reprojection error of points off the plane.
  • Known normal or known rotation. If n\mathbf{n} is known, for example from an inertial sensor, HH equals RR on the plane orthogonal to n\mathbf{n}, which fixes RR, and then t′=(H−R)n\mathbf{t}' = (H - R)\mathbf{n}: the solution is unique.
  • Pose from a planar target. When the plane is a calibration target with known metric coordinates, the pose comes more simply from the columns of K−1GK^{-1}G (as in Zhang's method), which is the planar case of perspective-n-point.

When to use it

Use it to get the camera motion between two views of a scene that is mostly one plane: a drone over flat ground, a robot looking at a wall, a camera over a table or a document, the initialization of visual odometry and of SLAM systems that test both a homography and an essential matrix. In such scenes the essential matrix is badly determined, since all points lie on a plane, while the homography is well determined. If the scene has depth, use the essential matrix instead; a homography then describes only the points of one plane.

Pitfalls

  • Wrong calibration. The method needs K1K_1 and K2K_2. With wrong intrinsics HH is not of the form R+t′nTR + \mathbf{t}'\mathbf{n}^{\mathsf T}, the middle singular value is not exactly 1, and the output is biased.
  • Sign conventions. Check how the plane is written. With nTX+d=0\mathbf{n}^{\mathsf T}\mathbf{X} + d = 0 the formula has a minus sign, and a formula with the wrong sign returns −t-\mathbf{t}.
  • Almost no translation. When ∥t∥/d\|\mathbf{t}\|/d is small, s1s_1 and s3s_3 are close to 1, and n\mathbf{n} and t′\mathbf{t}' are badly determined by noise, although RR is still accurate. Choose the threshold ε\varepsilon of line L5 with the noise level in mind.
  • Picking one answer by default. Returning the first candidate that passes the test gives the wrong motion about half the time. Keep both until other information decides.
  • Cameras on both sides of the plane. If camera 2 is the mirror image of camera 1 in the plane, HH is orthogonal with determinant −1-1, and line L5 misreads it as a pure rotation. This needs a transparent plane and is outside the convention above.

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.

cvgeom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Camera geometry and synthetic scenes for the computer vision pages.

Conventions (prompts of the area, also stated on the pages):
- The camera frame has X to the right, Y down and Z forward. A point is in
  front of the camera if Z > 0.
- K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]] in pixels.
- A world point Xw maps to the camera frame by Xc = R Xw + t. The camera
  matrix is P = K [R | t], and the center is C = -R^T t.
- Rotations are active and right-handed. Quaternions are (w, x, y, z) in the
  Hamilton convention.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import math
import random
from typing import Dict, List, Optional, Sequence, Tuple

from cvla import det, matvec, mul, solve, transpose

Matrix = List[List[float]]
Vector = List[float]


def to_h(x: Sequence[float]) -> Vector:
    """Append a 1: the homogeneous vector of a point."""
    return [float(v) for v in x] + [1.0]


def from_h(x: Sequence[float]) -> Vector:
    """Divide by the last entry and drop it. Raises ValueError if the last
    entry is zero (a point at infinity)."""
    w = x[-1]
    if w == 0:
        raise ValueError("from_h: point at infinity")
    return [v / w for v in x[:-1]]


def make_K(fx: float, fy: float, cx: float, cy: float, s: float = 0.0) -> Matrix:
    """The intrinsic matrix [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
    return [[float(fx), float(s), float(cx)],
            [0.0, float(fy), float(cy)],
            [0.0, 0.0, 1.0]]


def camera_matrix(K: Sequence[Sequence[float]], R: Sequence[Sequence[float]],
                  t: Sequence[float]) -> Matrix:
    """The 3 x 4 camera matrix P = K [R | t]."""
    rt = [list(R[i]) + [t[i]] for i in range(3)]
    return mul(K, rt)


def project(P: Sequence[Sequence[float]], X):
    """Pixel coordinates (u, v) of a point X under the camera P.

    X is a 3D point (3 entries) or a homogeneous point (4 entries). If X is
    a list of points, the result is the list of their projections."""
    if len(X) > 0 and isinstance(X[0], (list, tuple)):
        return [project(P, x) for x in X]
    xh = to_h(X) if len(X) == 3 else list(X)
    return from_h(matvec(P, xh))


def camera_center(P: Sequence[Sequence[float]]) -> Vector:
    """The center C of a finite camera P = [M | p4]: C = -M^-1 p4, so that
    P (C, 1) = 0."""
    m = [list(row[:3]) for row in P]
    p4 = [row[3] for row in P]
    return [-v for v in solve(m, p4)]


def rot_x(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the X axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def axis_angle_to_R(axis: Sequence[float], theta: Optional[float] = None) -> Matrix:
    """Rotation by theta (radians) about the axis, by the right-hand rule
    (Rodrigues formula). The axis need not be a unit vector. If theta is
    None, axis is the rotation vector w = theta a, with theta = ||w||."""
    n = math.sqrt(sum(float(v) * float(v) for v in axis))
    if theta is None:
        theta = n
    if n == 0.0 or theta == 0.0:
        return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    x, y, z = (float(v) / n for v in axis)
    c, s = math.cos(theta), math.sin(theta)
    d = 1.0 - c
    return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
            [y * x * d + z * s, c + y * y * d, y * z * d - x * s],
            [z * x * d - y * s, z * y * d + x * s, c + z * z * d]]


def quat_to_R(q: Sequence[float]) -> Matrix:
    """Rotation matrix of the quaternion q = (w, x, y, z), Hamilton
    convention. q is normalized first; q and -q give the same matrix."""
    n = math.sqrt(sum(float(v) * float(v) for v in q))
    if n == 0.0:
        raise ValueError("quat_to_R: zero quaternion")
    w, x, y, z = (float(v) / n for v in q)
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def random_rotation(rng: random.Random) -> Matrix:
    """A rotation drawn from the uniform (Haar) distribution: a uniform
    random unit quaternion by the method of Shoemake (1992)."""
    u1, u2, u3 = rng.random(), rng.random(), rng.random()
    a, b = math.sqrt(1.0 - u1), math.sqrt(u1)
    q = (b * math.cos(2 * math.pi * u3), a * math.sin(2 * math.pi * u2),
         a * math.cos(2 * math.pi * u2), b * math.sin(2 * math.pi * u3))
    return quat_to_R(q)


def _small_rotation(rng: random.Random, max_angle: float) -> Matrix:
    axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
    return axis_angle_to_R(axis, rng.uniform(0.0, max_angle))


def random_scene(rng: random.Random, n: int = 20, n_cams: int = 2,
                 K: Optional[Sequence[Sequence[float]]] = None,
                 cams: Optional[Sequence[Tuple]] = None,
                 radius: float = 1.0, distance: float = 5.0,
                 max_angle: float = 0.3, planar: bool = False,
                 first_identity: bool = False,
                 size: Optional[Tuple[float, float]] = None,
                 min_depth: float = 0.1) -> Dict[str, list]:
    """A synthetic scene with known cameras and points.

    Cameras: if cams is given, it is a list of (K, R, t) and is used as it
    is. Otherwise n_cams cameras look at the world origin from the distance
    `distance`. Each one is the camera at center (0, 0, -distance) with
    R = I, turned about the origin by a random rotation of angle at most
    max_angle (radians). K defaults to make_K(800, 800, 320, 240). With
    first_identity, the world frame is moved to the frame of camera 0, so
    that camera 0 has R = I and t = 0 (the points move with it).

    Points: n points drawn uniformly in the cube [-radius, radius]^3 (with
    Z = 0 if planar, before any move of the world frame). A point is kept
    only if its depth is at least min_depth in every camera, and, if size =
    (W, H) is given, if its projection lies in [0, W] x [0, H] in every
    camera. Raises ValueError if 1000 n draws are not enough.

    Returns a dict with lists "K", "R", "t", "P" (one entry per camera),
    "X" (the 3D points) and "x" (x[i][j] is the pixel of point j in
    camera i, without noise)."""
    if cams is not None:
        Ks = [[list(r) for r in c[0]] for c in cams]
        Rs = [[list(r) for r in c[1]] for c in cams]
        ts = [list(c[2]) for c in cams]
    else:
        k0 = [list(r) for r in K] if K is not None else make_K(800, 800, 320, 240)
        Ks, Rs, ts = [], [], []
        c0 = [0.0, 0.0, -float(distance)]
        for _ in range(n_cams):
            q = _small_rotation(rng, max_angle)
            r = transpose(q)
            center = matvec(q, c0)
            Ks.append([list(row) for row in k0])
            Rs.append(r)
            ts.append([-v for v in matvec(r, center)])
    pts: List[Vector] = []
    tries = 0
    while len(pts) < n:
        tries += 1
        if tries > 1000 * max(n, 1):
            raise ValueError("random_scene: cannot place the points")
        x = [rng.uniform(-radius, radius) for _ in range(3)]
        if planar:
            x[2] = 0.0
        ok = True
        for k, r, t in zip(Ks, Rs, ts):
            xc = [a + b for a, b in zip(matvec(r, x), t)]
            if xc[2] < min_depth:
                ok = False
                break
            if size is not None:
                u = (k[0][0] * xc[0] + k[0][1] * xc[1]) / xc[2] + k[0][2]
                v = k[1][1] * xc[1] / xc[2] + k[1][2]
                if not (0.0 <= u <= size[0] and 0.0 <= v <= size[1]):
                    ok = False
                    break
        if ok:
            pts.append(x)
    if first_identity and Rs:
        r0, t0 = Rs[0], ts[0]
        pts = [[a + b for a, b in zip(matvec(r0, x), t0)] for x in pts]
        r0t = transpose(r0)
        newR, newt = [], []
        for r, t in zip(Rs, ts):
            rr = mul(r, r0t)
            newR.append(rr)
            newt.append([a - b for a, b in zip(t, matvec(rr, t0))])
        Rs, ts = newR, newt
        Rs[0] = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
        ts[0] = [0.0, 0.0, 0.0]
    Ps = [camera_matrix(k, r, t) for k, r, t in zip(Ks, Rs, ts)]
    xs = [[project(p, x) for x in pts] for p in Ps]
    return {"K": Ks, "R": Rs, "t": ts, "P": Ps, "X": pts, "x": xs}


def add_noise(rng: random.Random, pts: Sequence[Sequence[float]], sigma: float) -> List[Vector]:
    """A copy of the points with independent Gaussian noise of standard
    deviation sigma added to every coordinate."""
    return [[float(v) + rng.gauss(0.0, sigma) for v in p] for p in pts]


def self_test() -> None:
    """Check random_scene and quat_to_R. Raises AssertionError."""
    rng = random.Random(11)
    scene = random_scene(rng, n=30, n_cams=4)
    for r, t in zip(scene["R"], scene["t"]):
        for x in scene["X"]:
            assert matvec(r, x)[2] + t[2] > 0.0
    for _ in range(5):
        q = [rng.gauss(0.0, 1.0) for _ in range(4)]
        r = quat_to_R(q)
        rtr = mul(transpose(r), r)
        assert all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) <= 1e-12
                   for i in range(3) for j in range(3))
        assert abs(det(r) - 1.0) <= 1e-12


if __name__ == "__main__":
    self_test()
cvla.py 494 lines
# 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()
homography_decomposition.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/homography-decomposition/. The authors are listed in prov/NHSK5N.jsonl.
"""Decomposition of a plane-induced homography into motion and plane.

Convention: the plane is n^T X1 = d in the frame of camera 1, with d > 0
and n a unit vector, and X2 = R X1 + t. Then a pixel x1 of a point of the
plane maps to x2 ~ G x1 with G = K2 (R + t n^T / d) K1^-1. The scale d is
not observable, so the method returns t' = t / d.

The method is the SVD construction of Ma, Soatto, Kosecka and Sastry (An
Invitation to 3-D Vision, Section 5.3.3): four candidates (R, t', n), of
which the visibility test n^T K1^-1 x1 > 0 keeps at most two.

Cost: a fixed number of 3 x 3 operations plus O(n) for n point pairs.
"""

from __future__ import annotations

import math
from typing import List, Optional, Sequence, Tuple

from cvla import cross, inv, matvec, mul, scale, sub, svd, transpose

Matrix = List[List[float]]
Vector = List[float]
Solution = Tuple[Matrix, Vector, Optional[Vector]]


def _columns(cols: Sequence[Sequence[float]]) -> Matrix:
    """The 3 x 3 matrix with the given columns."""
    return transpose([list(c) for c in cols])


def homography_decomposition(G: Sequence[Sequence[float]], K1: Sequence[Sequence[float]],
                             K2: Sequence[Sequence[float]],
                             x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]],
                             eps: float = 1e-9) -> List[Solution]:
    """Return the motions (R, t / d, n) compatible with the pixel homography G.

    x1, x2 are pixel pairs on the plane (at least one; more make the sign
    and visibility votes robust). If H = K2^-1 G K1 is a rotation (its
    singular values agree within eps), the camera did not move and the
    result is [(R, [0, 0, 0], None)]: the plane cannot be recovered.
    Otherwise the result has the candidates with n^T K1^-1 x1 > 0 for a
    majority of the points: at most two. Cost O(1) for the 3 x 3 work and
    O(n) for the votes."""
    if len(x1) == 0 or len(x1) != len(x2):
        raise ValueError("need at least one point pair")
    k1i, k2i = inv(K1), inv(K2)
    y1 = [matvec(k1i, [p[0], p[1], 1.0]) for p in x1]
    y2 = [matvec(k2i, [p[0], p[1], 1.0]) for p in x2]
    H = mul(mul(k2i, G), K1)  # @line L1
    _, s, _ = svd(H)
    H = scale(H, 1.0 / s[1])  # @line L2
    votes = sum(1 if sum(a * b for a, b in zip(q, matvec(H, p))) > 0 else -1
                for p, q in zip(y1, y2))
    if votes < 0:
        H = scale(H, -1.0)  # @line L3
    _, s, V = svd(H)  # @line L4
    v1, v2, v3 = ([V[i][k] for i in range(3)] for k in range(3))
    l1, l3 = s[0] * s[0] / (s[1] * s[1]), s[2] * s[2] / (s[1] * s[1])
    if l1 - l3 < eps:  # @line L5
        U, _, W = svd(H)
        return [(mul(U, transpose(W)), [0.0, 0.0, 0.0], None)]
    a = math.sqrt(max(0.0, 1.0 - l3))
    b = math.sqrt(max(0.0, l1 - 1.0))
    c = math.sqrt(l1 - l3)
    cands: List[Solution] = []
    for sign in (1.0, -1.0):
        u = [(a * p + sign * b * q) / c for p, q in zip(v1, v3)]  # @line L6
        hv2, hu = matvec(H, v2), matvec(H, u)
        U = _columns([v2, u, cross(v2, u)])  # @line L7
        W = _columns([hv2, hu, cross(hv2, hu)])  # @line L7
        R = mul(W, transpose(U))  # @line L8
        n = cross(v2, u)  # @line L8
        t = matvec(sub(H, R), n)  # @line L8
        cands.append((R, t, n))  # @line L9
        cands.append((R, [-x for x in t], [-x for x in n]))  # @line L9
    keep = []
    for R, t, n in cands:  # @line L10
        good = sum(1 if sum(a * b for a, b in zip(n, p)) > 0 else -1 for p in y1)
        if good > 0:
            keep.append((R, t, n))
    return keep  # @line L11


def plane_homography(K1: Sequence[Sequence[float]], K2: Sequence[Sequence[float]],
                     R: Sequence[Sequence[float]], t: Sequence[float],
                     n: Sequence[float], d: float) -> Matrix:
    """G = K2 (R + t n^T / d) K1^-1 for the plane n^T X1 = d."""
    E = [[R[i][j] + t[i] * n[j] / d for j in range(3)] for i in range(3)]
    return mul(mul(K2, E), inv(K1))
test_homography_decomposition.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/homography-decomposition/. The authors are listed in prov/NHSK5N.jsonl.
"""Tests of the SVD decomposition of a plane-induced homography."""

import math
import random

import pytest

from cvgeom import axis_angle_to_R, camera_matrix, make_K, project
from cvla import cross, det, eye, matvec, mul, norm, scale, sub, transpose
from homography_decomposition import homography_decomposition, plane_homography


def rot_angle(R1, R2):
    """The angle of R1^T R2, from the Frobenius distance (accurate near 0)."""
    return 2.0 * math.asin(min(1.0, norm(sub(R1, R2)) / (2.0 * math.sqrt(2.0))))


def plane_basis(n):
    a = [1.0, 0.0, 0.0] if abs(n[0]) < 0.9 else [0.0, 1.0, 0.0]
    e1 = cross(n, a)
    e1 = scale(e1, 1.0 / norm(e1))
    return e1, cross(n, e1)


def random_case(rng, rotation_only=False):
    K1 = make_K(800, 820, 320, 240)
    K2 = make_K(700, 700, 300, 250, 0.5)
    R = axis_angle_to_R([rng.gauss(0, 1) for _ in range(3)], rng.uniform(0.0, 0.5))
    t = [0.0, 0.0, 0.0] if rotation_only else [rng.gauss(0, 0.5) for _ in range(3)]
    n = [rng.gauss(0, 0.3), rng.gauss(0, 0.3), 1.0]
    n = scale(n, 1.0 / norm(n))
    d = rng.uniform(2.0, 6.0)
    e1, e2 = plane_basis(n)
    X = []
    while len(X) < 12:
        a, b = rng.uniform(-2, 2), rng.uniform(-2, 2)
        p = [d * n[i] + a * e1[i] + b * e2[i] for i in range(3)]
        q = [u + v for u, v in zip(matvec(R, p), t)]
        if p[2] > 0.1 and q[2] > 0.1:
            X.append(p)
    P1 = camera_matrix(K1, eye(3), [0.0, 0.0, 0.0])
    P2 = camera_matrix(K2, R, t)
    x1 = [project(P1, p) for p in X]
    x2 = [project(P2, p) for p in X]
    return K1, K2, R, t, n, d, x1, x2


def euclidean_h(R, t, n, d=1.0):
    return [[R[i][j] + t[i] * n[j] / d for j in range(3)] for i in range(3)]


def test_worked_example():
    R = [[0.8, 0.0, 0.6], [0.0, 1.0, 0.0], [-0.6, 0.0, 0.8]]
    t, n, d = [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], 2.0
    K = eye(3)
    G = plane_homography(K, K, R, t, n, d)
    assert norm(sub(G, [[0.8, 0.0, 1.1], [0.0, 1.0, 0.0], [-0.6, 0.0, 0.8]])) <= 1e-15
    x1 = [[0.0, 0.0], [0.2, 0.1], [-0.2, 0.1]]
    x2 = []
    for p in x1:
        q = [a + b for a, b in zip(matvec(R, [d * p[0], d * p[1], d]), t)]
        x2.append([q[0] / q[2], q[1] / q[2]])
    sols = homography_decomposition(G, K, K, x1, x2)
    assert len(sols) == 2
    true = [s for s in sols if rot_angle(s[0], R) <= 1e-9]
    assert len(true) == 1
    assert norm(sub(true[0][1], [0.5, 0.0, 0.0])) <= 1e-9
    assert norm(sub(true[0][2], n)) <= 1e-9
    other = [s for s in sols if rot_angle(s[0], R) > 1e-9][0]
    assert abs(other[0][0][0] - 0.5505) <= 1e-4 and abs(other[0][0][2] - 0.8349) <= 1e-4
    assert abs(other[2][0] - 0.6854) <= 1e-4 and abs(other[2][2] - 0.7282) <= 1e-4


def test_random_scenes():
    rng = random.Random(1)
    sizes = {1: 0, 2: 0}
    for _ in range(120):
        K1, K2, R, t, n, d, x1, x2 = random_case(rng)
        G = scale(plane_homography(K1, K2, R, t, n, d), rng.choice([-1.0, 1.0]) * rng.uniform(0.1, 10.0))
        sols = homography_decomposition(G, K1, K2, x1, x2)
        assert len(sols) in (1, 2)
        sizes[len(sols)] += 1
        Ht = euclidean_h(R, t, n, d)
        found = 0
        for Rs, ts, ns in sols:
            assert norm(sub(mul(transpose(Rs), Rs), eye(3))) <= 1e-9
            assert abs(det(Rs) - 1.0) <= 1e-9
            assert abs(norm(ns) - 1.0) <= 1e-9
            assert norm(sub(euclidean_h(Rs, ts, ns), Ht)) <= 1e-8 * norm(Ht)
            if rot_angle(Rs, R) <= 1e-8 and norm(sub(ns, n)) <= 1e-8 \
                    and norm(sub(ts, scale(t, 1.0 / d))) <= 1e-8:
                found += 1
        assert found == 1
    assert sizes[2] > sizes[1]


def test_visibility_of_kept_solutions():
    rng = random.Random(2)
    for _ in range(40):
        K1, K2, R, t, n, d, x1, x2 = random_case(rng)
        G = plane_homography(K1, K2, R, t, n, d)
        for _, _, ns in homography_decomposition(G, K1, K2, x1, x2):
            y = [matvec([[1 / 800.0, 0.0, -320 / 800.0], [0.0, 1 / 820.0, -240 / 820.0], [0.0, 0.0, 1.0]],
                        [p[0], p[1], 1.0]) for p in x1]
            assert sum(1 for q in y if sum(a * b for a, b in zip(ns, q)) > 0) * 2 > len(y)


def test_pure_rotation():
    rng = random.Random(3)
    for _ in range(20):
        K1, K2, R, t, n, d, x1, x2 = random_case(rng, rotation_only=True)
        G = plane_homography(K1, K2, R, t, n, d)
        sols = homography_decomposition(G, K1, K2, x1, x2)
        assert len(sols) == 1
        Rs, ts, ns = sols[0]
        assert ns is None and ts == [0.0, 0.0, 0.0]
        assert rot_angle(Rs, R) <= 1e-8


def test_scale_and_sign_do_not_matter():
    rng = random.Random(4)
    K1, K2, R, t, n, d, x1, x2 = random_case(rng)
    G = plane_homography(K1, K2, R, t, n, d)
    a = homography_decomposition(G, K1, K2, x1, x2)
    b = homography_decomposition(scale(G, -3.5), K1, K2, x1, x2)
    assert len(a) == len(b)
    for (Ra, ta, na), (Rb, tb, nb) in zip(a, b):
        assert rot_angle(Ra, Rb) <= 1e-9
        assert norm(sub(ta, tb)) <= 1e-9 and norm(sub(na, nb)) <= 1e-9


def test_noise_keeps_the_true_solution_close():
    rng = random.Random(5)
    for _ in range(20):
        K1, K2, R, t, n, d, x1, x2 = random_case(rng)
        if norm(t) / d < 0.05:
            continue
        G = plane_homography(K1, K2, R, t, n, d)
        G = [[g * (1.0 + rng.gauss(0.0, 1e-7)) for g in row] for row in G]
        sols = homography_decomposition(G, K1, K2, x1, x2)
        assert min(rot_angle(s[0], R) for s in sols) <= 1e-4


def test_bad_input():
    with pytest.raises(ValueError):
        homography_decomposition(eye(3), eye(3), eye(3), [], [])

History

Faugeras and Lustman (1988) gave the decomposition of the plane-induced homography by an SVD, counted the solutions and used it for motion in piecewise planar scenes. Ma, Soatto, Kosecka and Sastry (2004) gave the construction from the singular vectors of HTHH^{\mathsf T}H used on this page and proved that two solutions remain with positive depths. Malis and Vargas (2007) gave closed-form solutions without an SVD, motivated by visual servoing.

References

  1. Olivier Faugeras and Francis Lustman, Motion and structure from motion in a piecewise planar environment, International Journal of Pattern Recognition and Artificial Intelligence 2(3), 1988, 485-508, the decomposition of the homography by an SVD and the count of solutions
  2. Yi Ma, Stefano Soatto, Jana Kosecka and S. Shankar Sastry, An Invitation to 3-D Vision, Springer, 2004, Section 5.3.3, Decomposing the planar homography matrix (the normalization by the second singular value, the construction from the SVD of H^T H, Theorem 5.19 with four solutions of which two have positive depth)
  3. Ezio Malis and Manuel Vargas, Deeper understanding of the homography decomposition for vision-based control, INRIA Research Report RR-6303, 2007, the analytical decomposition without SVD and the relations between the solutions
  4. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 13.1, Homographies given the plane and vice versa (the plane-induced homography, with the plane written as n^T X + d = 0)

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