Algorithm Search⌘K

Algorithmadvanced

Hartley-Sturm optimal triangulation

Also called polynomial triangulation, optimal two-view triangulation.

Find the two-view triangulation of least reprojection error exactly, by reducing it to the roots of a degree 6 polynomial over the pencil of epipolar lines.

Time
Θ(1) worst · average · best
Space
Θ(1) extra
Where
d = the degree of the polynomial, always 6
Properties
deterministicexactofflineiterative
Origin
Richard Hartley, Peter Sturm, 1997

Optimal triangulation finds the 3D point whose two projections are closest to the measured image points, in the sense of the sum of the squared image distances: the reprojection error. Under independent Gaussian noise on the image points this is the maximum likelihood estimate. The method of Hartley and Sturm does not search over 3D points. It looks for the corrected image points x^1\hat{\mathbf{x}}_1, x^2\hat{\mathbf{x}}_2 that satisfy the epipolar constraint x^2TFx^1=0\hat{\mathbf{x}}_2^{\mathsf T}F\hat{\mathbf{x}}_1 = 0 of the fundamental matrix and are closest to the measured points. Each such pair lies on a pair of matching epipolar lines, and these lines form a family with one parameter tt. After a Euclidean change of each image frame, the cost is a simple rational function of tt, and its stationary points are the real roots of a polynomial of degree 6. The best root gives the corrected points, which back-project to rays that meet, so any linear triangulation gives the point exactly. The result depends only on FF and the image points, so the method is projective invariant.

In plain words

Each photo shows the point a little off from where it should be, so the two lines of sight do not quite meet. The method asks: what is the smallest shift of the two dots that makes the lines meet? It does not try 3D points. Instead it looks at the pairs of lines in the two photos on which matching dots must lie. These pairs can be described with one number. For each value of that number, the needed shift is easy to write down. The best value is found by solving one equation, and the shifted dots give the point directly.

The problem

Input. A fundamental matrix FF of rank 2, or two camera matrices P1P_1, P2P_2 from which F=[e2]×P2P1+F = [\mathbf{e}_2]_\times P_2P_1^+ is formed, and two measured points x1\mathbf{x}_1, x2\mathbf{x}_2 in Euclidean image coordinates (pixels with square pixels and no skew, or normalized coordinates).

Output. The pair (x^1,x^2)(\hat{\mathbf{x}}_1, \hat{\mathbf{x}}_2) with x^2TFx^1=0\hat{\mathbf{x}}_2^{\mathsf T}F\hat{\mathbf{x}}_1 = 0 that minimizes d(x1,x^1)2+d(x2,x^2)2d(\mathbf{x}_1, \hat{\mathbf{x}}_1)^2 + d(\mathbf{x}_2, \hat{\mathbf{x}}_2)^2, and the 3D point X^\hat{\mathbf{X}} that projects to them.

The algorithm

Lines L1 to L3 move x1\mathbf{x}_1 and x2\mathbf{x}_2 to the origin of their images and turn each image about the origin so that the epipoles lie on the xx axis, at (1,0,f)(1, 0, f) and (1,0,f′)(1, 0, f'). Then FF has the form

F=(ff′d−f′c−f′d−fbab−fdcd).F = \begin{pmatrix} ff'd & -f'c & -f'd \\ -fb & a & b \\ -fd & c & d \end{pmatrix}.

The epipolar line in image 1 through (0,t)(0, t) is l1(t)=(tf,1,−t)\mathbf{l}_1(t) = (tf, 1, -t), and the matching line in image 2 is l2(t)=(−f′(ct+d),at+b,ct+d)\mathbf{l}_2(t) = (-f'(ct + d), at + b, ct + d). The cost of the best pair on these two lines is the sum of the squared distances from the origin to them:

s(t)=t21+f2t2+(ct+d)2(at+b)2+f′2(ct+d)2.s(t) = \frac{t^2}{1 + f^2t^2} + \frac{(ct + d)^2}{(at + b)^2 + f'^2(ct + d)^2}.
  1. OPTIMAL-TRIANGULATION(F, x_1, x_2)
  2. 1T_1, T_2 <- translations that move x_1, x_2 to the origin; F <- T_2^-T F T_1^-1
  3. 2e_1, e_2 <- right and left null vectors of F, scaled so that e_x^2 + e_y^2 = 1
  4. 3R_1, R_2 <- rotations with R_1 e_1 = (1, 0, f), R_2 e_2 = (1, 0, f'); F <- R_2 F R_1^T
  5. 4f, f' <- third entries of e_1, e_2; a, b, c, d <- F_22, F_23, F_32, F_33
  6. 5g(t) <- t ((a t + b)^2 + f'^2 (c t + d)^2)^2 - (a d - b c)(1 + f^2 t^2)^2 (a t + b)(c t + d)
  7. 6t_min <- the real root of g, or t = infinity, with the least s(t)
  8. 7l_1 <- (t f, 1, -t); l_2 <- (-f'(c t + d), a t + b, c t + d), at t = t_min
  9. 8x^_1, x^_2 <- the points of l_1, l_2 closest to the origin
  10. 9x^_i <- T_i^-1 R_i^T x^_i
  11. 10X <- the linear triangulation of x^_1, x^_2

The point of the line (λ,μ,ν)(\lambda, \mu, \nu) closest to the origin is (−λν,−μν,λ2+μ2)(-\lambda\nu, -\mu\nu, \lambda^2 + \mu^2). At t=∞t = \infty the lines are (f,0,−1)(f, 0, -1) and (−f′c,a,c)(-f'c, a, c), and s(∞)=1/f2+c2/(a2+f′2c2)s(\infty) = 1/f^2 + c^2/(a^2 + f'^2c^2).

Example

Take P1=[I∣0]P_1 = [I \mid \mathbf{0}] and P2=[Ry(−0.3)∣(−1,0,0.2)T]P_2 = [R_y(-0.3) \mid (-1, 0, 0.2)^{\mathsf T}], in normalized coordinates. The point (1,2,4)(1, 2, 4) has the images (0.25,0.5)(0.25, 0.5) and (−0.2842,0.4633)(-0.2842, 0.4633). Move the second one by (0.01,0.02)(0.01, 0.02) to (−0.2742,0.4833)(-0.2742, 0.4833).

line value
L2 to L4 f=−0.4649f = -0.4649, f′=−0.2105f' = -0.2105, a=−0.0927a = -0.0927, b=1.0228b = 1.0228, c=−0.9739c = -0.9739, d=0.0194d = 0.0194
L5 g(t)=−0.0042t6+0.0489t5−0.0591t4+0.5716t3−0.4987t2+2.0865t−0.0197g(t) = -0.0042t^6 + 0.0489t^5 - 0.0591t^4 + 0.5716t^3 - 0.4987t^2 + 2.0865t - 0.0197
L6 real roots 0.0094560.009456 and 11.41911.419, with s=1.880×10−4s = 1.880 \times 10^{-4} and 27.0327.03; s(∞)=23.36s(\infty) = 23.36; so tmin⁡=0.009456t_{\min} = 0.009456
L9 x^1=(0.2478,0.5092)\hat{\mathbf{x}}_1 = (0.2478, 0.5092), x^2=(−0.2732,0.4734)\hat{\mathbf{x}}_2 = (-0.2732, 0.4734)
L10 X^=(1.0543,2.1667,4.2553)\hat{\mathbf{X}} = (1.0543, 2.1667, 4.2553), reprojection error 1.880×10−41.880 \times 10^{-4}

On the same data, linear triangulation gives (1.0540,2.1704,4.2563)(1.0540, 2.1704, 4.2563) with the larger reprojection error 1.891×10−41.891 \times 10^{-4}. In the simpler case P2=[I∣(−1,0,0)T]P_2 = [I \mid (-1, 0, 0)^{\mathsf T}], with the images (0.25,0.5)(0.25, 0.5) and (0,0.52)(0, 0.52), the epipolar lines are horizontal, the polynomial has degree 1, and the method moves both points to the height 0.510.51. The result is (1,2.04,4)(1, 2.04, 4), with reprojection error 2×10−42 \times 10^{-4}.

Correctness

Translations and rotations of the images keep distances and transform FF in a matching way, so the normal form above loses nothing. Every corrected point x^1\hat{\mathbf{x}}_1 other than the epipole lies on one line l1(t)\mathbf{l}_1(t) of the pencil, and its epipolar line in image 2 is l2(t)\mathbf{l}_2(t). So the least cost for a given tt is the sum of the squared distances from the origin to the two lines, s(t)s(t), and pairs that contain an epipole are never better. On the projective line of tt the function ss reaches its minimum, either at t=∞t = \infty or where s′(t)=0s'(t) = 0. Clearing denominators in s′(t)=0s'(t) = 0 gives exactly g(t)=0g(t) = 0. So line L6 finds the optimal tt, and the feet of the perpendiculars are the optimal pair. The corrected points satisfy the epipolar constraint, so their rays meet, and the point where they meet has a reprojection error equal to the optimal cost. The full proof is in the proof file of this page.

Proof: The real roots of the degree 6 polynomial and the point at infinity of the pencil contain the minimizer of the two-view reprojection errorfull

We use the notation of the page. FF is a fundamental matrix of rank 2 with x~2TFx~1=0\tilde{\mathbf{x}}_2^{\mathsf T}F\tilde{\mathbf{x}}_1 = 0 for matching points. The measured points x1\mathbf{x}_1, x2\mathbf{x}_2 are not at the epipoles. Image coordinates are Euclidean, so d(⋅,⋅)d(\cdot, \cdot) is the Euclidean distance in each image. The arithmetic is exact (real RAM). The cost of a pair is C(x^1,x^2)=d(x1,x^1)2+d(x2,x^2)2C(\hat{\mathbf{x}}_1, \hat{\mathbf{x}}_2) = d(\mathbf{x}_1, \hat{\mathbf{x}}_1)^2 + d(\mathbf{x}_2, \hat{\mathbf{x}}_2)^2.

Claim. (a) The pair (x^1,x^2)(\hat{\mathbf{x}}_1, \hat{\mathbf{x}}_2) returned by lines L1 to L9 satisfies x^2TFx^1=0\hat{\mathbf{x}}_2^{\mathsf T}F\hat{\mathbf{x}}_1 = 0 and has the least cost among all pairs that satisfy it. (b) If FF comes from finite cameras P1P_1, P2P_2 with distinct centers and the rays of the corrected points meet at a finite point X^\hat{\mathbf{X}}, then line L10 returns X^\hat{\mathbf{X}}, and X^\hat{\mathbf{X}} has the least reprojection error d(x1,P1X)2+d(x2,P2X)2d(\mathbf{x}_1, P_1\mathbf{X})^2 + d(\mathbf{x}_2, P_2\mathbf{X})^2 among all points X\mathbf{X} off the baseline.

Lemma 1 (Euclidean changes of frame). Let A1A_1, A2A_2 be Euclidean motions of the two images (here Ai=RiTiA_i = R_iT_i). Replacing each point p\mathbf{p} of image ii by AipA_i\mathbf{p} and FF by A2−TFA1−1A_2^{-\mathsf T}FA_1^{-1} keeps the epipolar constraint and all distances. So it is enough to prove part (a) in the new frames.

Proof. (A2p~2)TA2−TFA1−1(A1p~1)=p~2TFp~1(A_2\tilde{\mathbf{p}}_2)^{\mathsf T}A_2^{-\mathsf T}FA_1^{-1}(A_1\tilde{\mathbf{p}}_1) = \tilde{\mathbf{p}}_2^{\mathsf T}F\tilde{\mathbf{p}}_1, and Euclidean motions keep distances. Line L9 applies the inverse motions. □\square

Lemma 2 (the normal form of FF). After lines L1 to L3, x1=x2=(0,0)\mathbf{x}_1 = \mathbf{x}_2 = (0, 0), the epipoles are e1=(1,0,f)\mathbf{e}_1 = (1, 0, f) and e2=(1,0,f′)\mathbf{e}_2 = (1, 0, f'), and

F=(ff′d−f′c−f′d−fbab−fdcd),ad−bc≠0.F = \begin{pmatrix} ff'd & -f'c & -f'd \\ -fb & a & b \\ -fd & c & d \end{pmatrix}, \qquad ad - bc \ne 0 .

Proof. Line L1 moves the points to the origin. Line L2 scales the epipole e=(e1,e2,e3)\mathbf{e} = (e_1, e_2, e_3) so that e12+e22=1e_1^2 + e_2^2 = 1; this is possible because the point at the origin is not the epipole, so (e1,e2)≠(0,0)(e_1, e_2) \ne (0, 0). The rotation RR of line L3 maps it to (e12+e22,−e2e1+e1e2,e3)=(1,0,e3)(e_1^2 + e_2^2, -e_2e_1 + e_1e_2, e_3) = (1, 0, e_3) and fixes the origin. Now Fe1=0F\mathbf{e}_1 = \mathbf{0} says that the first column of FF is −f-f times the third, and e2TF=0\mathbf{e}_2^{\mathsf T}F = \mathbf{0} says that the first row is −f′-f' times the third. Naming the lower right block (abcd)\begin{pmatrix} a & b \\ c & d\end{pmatrix} gives the form above. The first row and the first column are combinations of the others, so the rank of FF equals the rank of this block, which must be 2. □\square

Lemma 3 (the pencil). For t∈Rt \in \mathbb{R}, let l1(t)=(tf,1,−t)\mathbf{l}_1(t) = (tf, 1, -t), the line through e1\mathbf{e}_1 and (0,t)(0, t), and l2(t)=F(0,t,1)T=(−f′(ct+d),at+b,ct+d)\mathbf{l}_2(t) = F(0, t, 1)^{\mathsf T} = (-f'(ct + d), at + b, ct + d). For t=∞t = \infty, let l1=(f,0,−1)\mathbf{l}_1 = (f, 0, -1), the line through e1\mathbf{e}_1 in the direction (0,1)(0, 1), and l2=F(0,1,0)T=(−f′c,a,c)\mathbf{l}_2 = F(0, 1, 0)^{\mathsf T} = (-f'c, a, c). Then every point x^1≠e1\hat{\mathbf{x}}_1 \ne \mathbf{e}_1 lies on exactly one l1(t)\mathbf{l}_1(t), and its epipolar line Fx^1F\hat{\mathbf{x}}_1 is l2(t)\mathbf{l}_2(t) up to a nonzero factor.

Proof. The lines through e1\mathbf{e}_1 meet the line x=0x = 0 in one point (0,t)(0, t), or are parallel to it (t=∞t = \infty); the two vectors (e1,(0,t,1))(\mathbf{e}_1, (0, t, 1)) span the line, and the cross product gives l1(t)\mathbf{l}_1(t). A point x^1≠e1\hat{\mathbf{x}}_1 \ne \mathbf{e}_1 on this line is αe1+β(0,t,1)\alpha\mathbf{e}_1 + \beta(0, t, 1) with β≠0\beta \ne 0, so Fx^1=βF(0,t,1)TF\hat{\mathbf{x}}_1 = \beta F(0, t, 1)^{\mathsf T}. This is not zero, because the null space of FF is spanned by e1\mathbf{e}_1, whose first entry is 1. The case t=∞t = \infty is the same with (0,1,0)(0, 1, 0). □\square

Lemma 4 (the cost along the pencil). The distance from the origin to the line (λ,μ,ν)(\lambda, \mu, \nu) is ∣ν∣/λ2+μ2|\nu|/\sqrt{\lambda^2 + \mu^2}, reached at the point (−λν,−μν,λ2+μ2)(-\lambda\nu, -\mu\nu, \lambda^2 + \mu^2). So

s(t)=d(0,l1(t))2+d(0,l2(t))2=t21+f2t2+(ct+d)2(at+b)2+f′2(ct+d)2,s(t) = d(\mathbf{0}, \mathbf{l}_1(t))^2 + d(\mathbf{0}, \mathbf{l}_2(t))^2 = \frac{t^2}{1 + f^2t^2} + \frac{(ct + d)^2}{(at + b)^2 + f'^2(ct + d)^2},

with the value +∞+\infty where the second denominator is 0, and s(∞)=1/f2+c2/(a2+f′2c2)s(\infty) = 1/f^2 + c^2/(a^2 + f'^2c^2).

Proof. The foot of the perpendicular from the origin to λx+μy+ν=0\lambda x + \mu y + \nu = 0 is −ν(λ,μ)/(λ2+μ2)-\nu(\lambda, \mu)/(\lambda^2 + \mu^2), which is the stated homogeneous point, at the stated distance. Insert the lines of Lemma 3. The second denominator is 0 only if f′=0f' = 0 and at+b=0at + b = 0, and then l2(t)\mathbf{l}_2(t) is the line at infinity (it is not 0\mathbf{0}, since at+bat + b and ct+dct + d do not vanish together when ad−bc≠0ad - bc \ne 0). □\square

Lemma 5 (reduction to the pencil). The least cost over pairs that satisfy the epipolar constraint equals min⁡ts(t)\min_t s(t) over t∈R∪{∞}t \in \mathbb{R} \cup \{\infty\}, and the feet of the perpendiculars at a minimizing tt give an optimal pair.

Proof. Take a pair that satisfies the constraint with x^1≠e1\hat{\mathbf{x}}_1 \ne \mathbf{e}_1. By Lemma 3, x^1\hat{\mathbf{x}}_1 lies on l1(t)\mathbf{l}_1(t) and x^2\hat{\mathbf{x}}_2 on l2(t)\mathbf{l}_2(t) for one tt, so its cost is at least s(t)s(t). Conversely, the two feet at any tt satisfy the constraint: the foot on l1(t)\mathbf{l}_1(t) is e1\mathbf{e}_1, for which Fe1=0F\mathbf{e}_1 = \mathbf{0}, or a point whose epipolar line is l2(t)\mathbf{l}_2(t), which contains the second foot. Their cost is s(t)s(t).

It remains to treat the pairs with x^1=e1\hat{\mathbf{x}}_1 = \mathbf{e}_1, which have cost at least d(0,e1)2=1/f2d(\mathbf{0}, \mathbf{e}_1)^2 = 1/f^2 (infinite if f=0f = 0). If c≠0c \ne 0, then t=−d/ct = -d/c gives s(t)=t2/(1+f2t2)≤1/f2s(t) = t^2/(1 + f^2t^2) \le 1/f^2. If c=0c = 0, then a≠0a \ne 0 and s(∞)=1/f2s(\infty) = 1/f^2. So such pairs are never better than the pencil. The pairs with x^2=e2\hat{\mathbf{x}}_2 = \mathbf{e}_2 cost at least 1/f′21/f'^2, and s(0)=d2/(b2+f′2d2)≤1/f′2s(0) = d^2/(b^2 + f'^2d^2) \le 1/f'^2, with d≠0d \ne 0 if b=0b = 0. So they are never better either. □\square

Lemma 6 (the stationary points). Where the second denominator Q(t)=(at+b)2+f′2(ct+d)2Q(t) = (at + b)^2 + f'^2(ct + d)^2 is positive,

s′(t)=2t(1+f2t2)2−2(ad−bc)(at+b)(ct+d)Q(t)2,s'(t) = \frac{2t}{(1 + f^2t^2)^2} - \frac{2(ad - bc)(at + b)(ct + d)}{Q(t)^2},

so s′(t)=0s'(t) = 0 if and only if g(t)=tQ(t)2−(ad−bc)(1+f2t2)2(at+b)(ct+d)=0g(t) = tQ(t)^2 - (ad - bc)(1 + f^2t^2)^2(at + b)(ct + d) = 0.

Proof. The derivative of t2/(1+f2t2)t^2/(1 + f^2t^2) is 2t/(1+f2t2)22t/(1 + f^2t^2)^2. For the second term,

ddt(ct+d)2Q=2(ct+d)[cQ−(ct+d)(a(at+b)+f′2c(ct+d))]Q2=2(ct+d)(at+b)[c(at+b)−a(ct+d)]Q2,\frac{d}{dt}\frac{(ct + d)^2}{Q} = \frac{2(ct + d)\left[cQ - (ct + d)\left(a(at + b) + f'^2c(ct + d)\right)\right]}{Q^2} = \frac{2(ct + d)(at + b)\left[c(at + b) - a(ct + d)\right]}{Q^2},

and c(at+b)−a(ct+d)=bc−adc(at + b) - a(ct + d) = bc - ad. Multiplying s′(t)s'(t) by the positive number (1+f2t2)2Q2/2(1 + f^2t^2)^2Q^2/2 gives g(t)g(t). □\square

Proof of part (a). On the projective line R∪{∞}\mathbb{R} \cup \{\infty\}, which is compact, ss is continuous as a map to [0,+∞][0, +\infty], so it reaches its minimum, and the minimum is finite by Lemma 5 (for example s(0)s(0) or s(−d/c)s(-d/c) is finite). A minimizer is either t=∞t = \infty or a finite point with Q>0Q > 0 where s′=0s' = 0, that is, a real root of gg by Lemma 6. If gg is the zero polynomial, then ss is constant where Q>0Q > 0, and t=∞t = \infty is also a minimizer. Line L6 evaluates ss at all real roots of gg and at ∞\infty and keeps the least, so it finds a minimizer. Lines L7 and L8 build the feet of Lemma 4, which form an optimal pair by Lemma 5, and line L9 maps them back by Lemma 1. □\square

Proof of part (b). The corrected points satisfy the epipolar constraint, so their back-projected rays lie in one epipolar plane. By assumption they meet at the finite point X^\hat{\mathbf{X}}, so PiX^∼x^iP_i\hat{\mathbf{X}} \sim \hat{\mathbf{x}}_i, and the linear method of line L10 returns X^\hat{\mathbf{X}} (see linear triangulation). The reprojection error of X^\hat{\mathbf{X}} equals the cost of the corrected pair. Any point X\mathbf{X} off the baseline projects to a pair that satisfies the epipolar constraint, so by part (a) its reprojection error is at least that cost. □\square

Remark (projective invariance). The output of lines L1 to L9 depends only on FF and the measured points. If the cameras are replaced by PiH−1P_iH^{-1} for an invertible 4×44 \times 4 matrix HH, the fundamental matrix stays the same up to scale, so the corrected points do not change, and the triangulated point becomes HX^H\hat{\mathbf{X}}.

Remark (floating point). The roots of gg are found numerically, so line L6 compares a few values of ss that carry rounding errors; near a double root the chosen tt can be off by about the square root of the machine precision, which changes ss only to second order.

Complexity

All steps work on objects of fixed size: 3×33 \times 3 matrices, a polynomial of degree 6 and at most 7 candidate values of tt. So the method takes Θ(1)\Theta(1) time and space per point. In practice it is several times slower than linear triangulation, mostly because of the root finding.

Properties

  • Optimal. It gives the global minimum of the two-view reprojection error, not a local one; it is the maximum likelihood estimate under independent isotropic Gaussian image noise.
  • Projective invariant. It uses only FF and the image points. A projective change of the world frame gives the same corrected points and the transformed 3D point.
  • Exact on exact data. If the measured points already satisfy the epipolar constraint, the cost is 0, they are not moved, and the point is exact.
  • Two views only. The pencil argument needs one pair of epipolar lines. For three or more views the problem has many more stationary points, and other methods are used.
  • Euclidean images. The cost is a distance in each image, so the image coordinates must have square pixels and no skew, or be normalized.

Variants and improvements

  • Iterative correction. Lindstrom (2010) finds the same optimal pair with a short iteration that needs no polynomial roots; in practice two steps are enough, and the result is much faster to compute.
  • First-order correction. One step of correction along the gradient of the epipolar constraint gives the pair that minimizes the Sampson distance, a first-order approximation of the optimal cost.
  • Triangulation in more views. For three or more views, local minimization of the reprojection error from a linear start, or a full bundle adjustment, is the usual approach.
  • Calibrated cameras. With an essential matrix, for example from the five-point algorithm, the same method works on normalized image points, and the cost is then measured in normalized units instead of pixels.

When to use it

Use it when two views must give the best possible point under image noise, for example to evaluate other methods, to triangulate in a projective reconstruction where Euclidean methods do not apply, or to initialize a reconstruction with as little bias as possible. When speed matters and many points must be triangulated, linear triangulation followed by a few Gauss-Newton steps, or the iterative correction of Lindstrom, gives almost the same result.

Pitfalls

  • Non-Euclidean image frames. Running the method on pixel coordinates with skew, or on coordinates after a projective normalization, minimizes the wrong distance.
  • Points near the epipole. The rotation of line L3 is not defined when a measured point is at the epipole, and it is badly conditioned near it.
  • Root finding. Two real roots can be close or form a double root; take the real parts of nearly real complex roots as candidates, and do not forget the candidate t=∞t = \infty.
  • Back-transformation. The corrected points must be mapped back with the inverses of both the rotation and the translation, in that order.
  • Points behind a camera. The method minimizes an image distance and can return a point behind a camera. Check cheirality if the cameras are known in a Euclidean frame.

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()
optimal_triangulation.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-triangulation/. The authors are listed in prov/FJGF9W.jsonl.
"""Hartley-Sturm optimal two-view triangulation.

Given a fundamental matrix F (x2^T F x1 = 0) and two measured image points
x1, x2, find the points x1h, x2h with x2h^T F x1h = 0 that minimize
d(x1, x1h)^2 + d(x2, x2h)^2. The epipolar lines through x1h and x2h form a
pencil with one parameter t; after a Euclidean change of each image frame
the cost is a rational function s(t), and its stationary points are the
real roots of a polynomial g(t) of degree 6 (Hartley and Sturm 1997,
Hartley and Zisserman 2004, Algorithm 12.1). The corrected points are
then triangulated exactly by the linear method.

The image coordinates must be in a Euclidean frame (pixels with square
pixels and no skew, or normalized coordinates), because the cost is a
Euclidean distance in the image.

Cost: Theta(1).
"""

from __future__ import annotations

import math
from typing import List, Sequence, Tuple

from cvla import inv, matvec, mul, nullvec, polyroots_real, skew, transpose

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


# ------------------------------------------------------------ polynomials

def _pmul(p: Sequence[float], q: Sequence[float]) -> Vector:
    """Product of two polynomials, coefficients highest power first."""
    out = [0.0] * (len(p) + len(q) - 1)
    for i, a in enumerate(p):
        for j, b in enumerate(q):
            out[i + j] += a * b
    return out


def _padd(p: Sequence[float], q: Sequence[float]) -> Vector:
    n = max(len(p), len(q))
    p = [0.0] * (n - len(p)) + list(p)
    q = [0.0] * (n - len(q)) + list(q)
    return [a + b for a, b in zip(p, q)]


def _pscale(p: Sequence[float], k: float) -> Vector:
    return [k * a for a in p]


def cost_polynomial(a: float, b: float, c: float, d: float, f: float, f2: float) -> Vector:
    """The coefficients (degree 6 first) of
    g(t) = t ((a t + b)^2 + f2^2 (c t + d)^2)^2
           - (a d - b c) (1 + f^2 t^2)^2 (a t + b) (c t + d)."""
    atb, ctd = [a, b], [c, d]
    q = _padd(_pmul(atb, atb), _pscale(_pmul(ctd, ctd), f2 * f2))
    left = _pmul([1.0, 0.0], _pmul(q, q))
    r = [f * f, 0.0, 1.0]
    right = _pscale(_pmul(_pmul(r, r), _pmul(atb, ctd)), a * d - b * c)
    return _padd(left, _pscale(right, -1.0))


def cost_s(t: float, a: float, b: float, c: float, d: float, f: float, f2: float) -> float:
    """s(t) = t^2 / (1 + f^2 t^2) + (c t + d)^2 / ((a t + b)^2 + f2^2 (c t + d)^2).
    t = math.inf gives the limit 1/f^2 + c^2 / (a^2 + f2^2 c^2)."""
    if math.isinf(t):
        first = math.inf if f == 0 else 1.0 / (f * f)
        den = a * a + f2 * f2 * c * c
        return first + (c * c / den if den > 0 else math.inf)
    den = (a * t + b) ** 2 + f2 * f2 * (c * t + d) ** 2
    second = (c * t + d) ** 2 / den if den > 0 else math.inf
    return t * t / (1.0 + f * f * t * t) + second


# ------------------------------------------------------------ geometry

def fundamental_from_cameras(P1: Sequence[Sequence[float]],
                             P2: Sequence[Sequence[float]]) -> Matrix:
    """F = [e2]_x P2 P1^+, with e2 = P2 C1 and P1^+ = P1^T (P1 P1^T)^-1."""
    C1 = nullvec(P1)
    e2 = matvec(P2, C1)
    P1t = transpose(P1)
    pinv = mul(P1t, inv(mul(P1, P1t)))
    return mul(skew(e2), mul(P2, pinv))


def _translation(x: Sequence[float]) -> Matrix:
    return [[1.0, 0.0, -x[0]], [0.0, 1.0, -x[1]], [0.0, 0.0, 1.0]]


def _unit_epipole(e: Sequence[float]) -> Vector:
    n = math.hypot(e[0], e[1])
    if n <= 1e-12 * max(1.0, abs(e[2])):
        raise ValueError("optimal triangulation: an image point is at the epipole")
    return [e[0] / n, e[1] / n, e[2] / n]


def _closest_to_origin(line: Sequence[float]) -> Vector:
    lam, mu, nu = line
    return [-lam * nu, -mu * nu, lam * lam + mu * mu]


def optimal_correction(F: Sequence[Sequence[float]], x1: Sequence[float],
                       x2: Sequence[float], details: bool = False):
    """The corrected points (x1h, x2h) with x2h^T F x1h = 0 of least
    d(x1, x1h)^2 + d(x2, x2h)^2, and that least cost."""
    T1, T2 = _translation(x1), _translation(x2)                     # @line L1
    T1i, T2i = inv(T1), inv(T2)                                      # @line L1
    Fn = mul(transpose(T2i), mul(F, T1i))                            # @line L1
    e1 = _unit_epipole(nullvec(Fn))                                  # @line L2
    e2 = _unit_epipole(nullvec(transpose(Fn)))                       # @line L2
    R1 = [[e1[0], e1[1], 0.0], [-e1[1], e1[0], 0.0], [0.0, 0.0, 1.0]]  # @line L3
    R2 = [[e2[0], e2[1], 0.0], [-e2[1], e2[0], 0.0], [0.0, 0.0, 1.0]]  # @line L3
    Fr = mul(R2, mul(Fn, transpose(R1)))                             # @line L3
    f, f2 = e1[2], e2[2]                                             # @line L4
    a, b, c, d = Fr[1][1], Fr[1][2], Fr[2][1], Fr[2][2]              # @line L4
    g = cost_polynomial(a, b, c, d, f, f2)                           # @line L5
    cands = polyroots_real(g) + [math.inf]                           # @line L6
    t = min(cands, key=lambda u: cost_s(u, a, b, c, d, f, f2))       # @line L6
    if math.isinf(t):                                                # @line L7
        l1, l2 = [f, 0.0, -1.0], [-f2 * c, a, c]                     # @line L7
    else:                                                            # @line L7
        l1 = [t * f, 1.0, -t]                                        # @line L7
        l2 = [-f2 * (c * t + d), a * t + b, c * t + d]               # @line L7
    p1, p2 = _closest_to_origin(l1), _closest_to_origin(l2)          # @line L8
    q1 = matvec(T1i, matvec(transpose(R1), p1))                      # @line L9
    q2 = matvec(T2i, matvec(transpose(R2), p2))                      # @line L9
    x1h = [q1[0] / q1[2], q1[1] / q1[2]]                             # @line L9
    x2h = [q2[0] / q2[2], q2[1] / q2[2]]                             # @line L9
    cost = ((x1h[0] - x1[0]) ** 2 + (x1h[1] - x1[1]) ** 2
            + (x2h[0] - x2[0]) ** 2 + (x2h[1] - x2[1]) ** 2)
    if details:
        return x1h, x2h, cost, {"F": Fr, "f": f, "f2": f2, "abcd": (a, b, c, d),
                                "g": g, "roots": cands[:-1], "t": t,
                                "s": cost_s(t, a, b, c, d, f, f2)}
    return x1h, x2h, cost


def triangulate_dlt(P1, P2, x1, x2) -> Vector:
    """The linear (DLT) triangulation of two image points."""
    A = []
    for P, (u, v) in ((P1, x1), (P2, x2)):
        A.append([u * P[2][k] - P[0][k] for k in range(4)])
        A.append([v * P[2][k] - P[1][k] for k in range(4)])
    X = nullvec(A)
    if X[3] == 0.0:
        raise ValueError("optimal triangulation: the point is at infinity")
    return [X[0] / X[3], X[1] / X[3], X[2] / X[3]]


def optimal_triangulation(P1, P2, x1, x2) -> Tuple[Vector, Vector, Vector, float]:
    """The 3D point of least reprojection error for the cameras P1, P2 and
    the image points x1, x2. Returns (X, x1h, x2h, cost)."""
    F = fundamental_from_cameras(P1, P2)
    x1h, x2h, cost = optimal_correction(F, x1, x2)
    X = triangulate_dlt(P1, P2, x1h, x2h)                            # @line L10
    return X, x1h, x2h, cost


def reprojection_cost(P1, P2, X, x1, x2) -> float:
    """The sum of the squared image distances of the projections of X."""
    s = 0.0
    for P, x in ((P1, x1), (P2, x2)):
        q = matvec(P, list(X) + [1.0])
        s += (q[0] / q[2] - x[0]) ** 2 + (q[1] / q[2] - x[1]) ** 2
    return s
test_optimal_triangulation.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-triangulation/. The authors are listed in prov/FJGF9W.jsonl.
"""Tests of Hartley-Sturm optimal triangulation."""

import math
import random

import pytest

from cvgeom import add_noise, camera_matrix, random_scene, rot_y
from cvla import inv, matvec, mul, norm, sub, transpose
from optimal_triangulation import (cost_s, fundamental_from_cameras,
                                   optimal_correction, optimal_triangulation,
                                   reprojection_cost, triangulate_dlt)

I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
P1 = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]
P2 = [[1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]
P2B = camera_matrix(I3, rot_y(-0.3), [-1.0, 0.0, 0.2])
Y1 = [0.25, 0.5]
Y2N = [-0.2741747441668867, 0.48329905176727356]


def rel(a, b):
    return norm(sub(a, b)) / max(1.0, norm(b))


def epipolar(F, x1, x2):
    return sum((x2 + [1.0])[i] * F[i][j] * (x1 + [1.0])[j] for i in range(3) for j in range(3))


def noisy_cases(seed, count, sigma=2.0):
    rng = random.Random(seed)
    out = []
    for _ in range(count):
        sc = random_scene(rng, n=1, n_cams=2, max_angle=0.5)
        xa, xb = add_noise(rng, [sc["x"][0][0], sc["x"][1][0]], sigma)
        out.append((sc["P"][0], sc["P"][1], xa, xb, sc["X"][0]))
    return out


def test_worked_example_pure_translation():
    X, x1h, x2h, cost = optimal_triangulation(P1, P2, [0.25, 0.5], [0.0, 0.52])
    assert rel(x1h, [0.25, 0.51]) <= 1e-12 and rel(x2h, [0.0, 0.51]) <= 1e-12
    assert rel(X, [1.0, 2.04, 4.0]) <= 1e-12
    assert abs(cost - 2e-4) <= 1e-15


def test_worked_example_general():
    F = fundamental_from_cameras(P1, P2B)
    x1h, x2h, cost, info = optimal_correction(F, Y1, Y2N, details=True)
    assert abs(abs(info["f"]) - 0.464944) <= 1e-6
    assert abs(abs(info["f2"]) - 0.210505) <= 1e-6
    assert len(info["roots"]) == 2
    assert abs(info["roots"][0] - 0.0094559) <= 1e-6
    assert abs(info["roots"][1] - 11.419014) <= 1e-5
    assert abs(cost - 1.880302e-4) <= 1e-9
    assert rel(x1h, [0.247761, 0.509187]) <= 1e-6
    assert rel(x2h, [-0.273185, 0.473418]) <= 1e-6
    X = triangulate_dlt(P1, P2B, x1h, x2h)
    assert rel(X, [1.054300, 2.166745, 4.255303]) <= 1e-6
    Xl = triangulate_dlt(P1, P2B, Y1, Y2N)
    assert reprojection_cost(P1, P2B, Xl, Y1, Y2N) > cost
    a, b, c, d = info["abcd"]
    for t in info["roots"]:
        h = 1e-6 * max(1.0, abs(t))
        ds = (cost_s(t + h, a, b, c, d, info["f"], info["f2"])
              - cost_s(t - h, a, b, c, d, info["f"], info["f2"])) / (2 * h)
        assert abs(ds) <= 1e-6


def test_exact_data():
    rng = random.Random(1)
    for _ in range(6):
        sc = random_scene(rng, n=1, n_cams=2, max_angle=0.5)
        xa, xb = sc["x"][0][0], sc["x"][1][0]
        X, x1h, x2h, cost = optimal_triangulation(sc["P"][0], sc["P"][1], xa, xb)
        assert rel(X, sc["X"][0]) <= 1e-8
        assert norm(sub(x1h, xa)) <= 1e-8 * norm(xa)
        assert cost <= 1e-12 * norm(xa) ** 2


def test_corrected_points_satisfy_the_epipolar_constraint():
    for Pa, Pb, xa, xb, _ in noisy_cases(2, 6):
        F = fundamental_from_cameras(Pa, Pb)
        x1h, x2h, _ = optimal_correction(F, xa, xb)
        scale = norm(F) * (norm(x1h) + 1.0) * (norm(x2h) + 1.0)
        assert abs(epipolar(F, x1h, x2h)) <= 1e-12 * scale


def test_cost_is_reprojection_error_and_beats_linear():
    for Pa, Pb, xa, xb, Xt in noisy_cases(3, 6):
        X, _, _, cost = optimal_triangulation(Pa, Pb, xa, xb)
        assert abs(reprojection_cost(Pa, Pb, X, xa, xb) - cost) <= 1e-8 * max(1.0, cost)
        Xl = triangulate_dlt(Pa, Pb, xa, xb)
        assert cost <= reprojection_cost(Pa, Pb, Xl, xa, xb) + 1e-9
        assert cost <= reprojection_cost(Pa, Pb, Xt, xa, xb) + 1e-9


def test_global_minimum_over_the_pencil():
    for Pa, Pb, xa, xb, _ in noisy_cases(4, 4, sigma=5.0):
        F = fundamental_from_cameras(Pa, Pb)
        _, _, _, info = optimal_correction(F, xa, xb, details=True)
        a, b, c, d = info["abcd"]
        best = min(cost_s(math.tan(math.pi * (k + 0.5) / 4000 - math.pi / 2),
                          a, b, c, d, info["f"], info["f2"]) for k in range(4000))
        assert info["s"] <= best + 1e-12


def test_local_perturbations_do_not_help():
    rng = random.Random(5)
    for Pa, Pb, xa, xb, _ in noisy_cases(5, 3):
        X, _, _, cost = optimal_triangulation(Pa, Pb, xa, xb)
        for _ in range(30):
            Z = [x + rng.gauss(0, 1e-3) for x in X]
            assert reprojection_cost(Pa, Pb, Z, xa, xb) >= cost - 1e-9


def test_projective_invariance():
    rng = random.Random(6)
    H = [[rng.uniform(-1, 1) + (2.0 if i == j else 0.0) for j in range(4)] for i in range(4)]
    Hi = inv(H)
    for Pa, Pb, xa, xb, _ in noisy_cases(7, 3):
        X, x1h, x2h, cost = optimal_triangulation(Pa, Pb, xa, xb)
        X2, y1h, y2h, cost2 = optimal_triangulation(mul(Pa, Hi), mul(Pb, Hi), xa, xb)
        assert rel(y1h, x1h) <= 1e-8 and rel(y2h, x2h) <= 1e-8
        assert abs(cost2 - cost) <= 1e-8 * max(1.0, cost)
        Xh = matvec(H, X + [1.0])
        assert rel([v / Xh[3] for v in Xh[:3]], X2) <= 1e-7


def test_point_at_the_epipole_raises():
    C2 = [-v for v in matvec(transpose(rot_y(-0.3)), [-1.0, 0.0, 0.2])]
    e1 = [C2[0] / C2[2], C2[1] / C2[2]]
    F = fundamental_from_cameras(P1, P2B)
    with pytest.raises(ValueError):
        optimal_correction(F, e1, Y2N)

History

Hartley and Sturm (1997) studied the triangulation of a point from two views with known cameras. They showed that the linear and midpoint methods are not projective invariant, reduced the minimization of the reprojection error to the real roots of a polynomial of degree 6, and showed in experiments that the optimal method is more accurate than the others. Hartley and Zisserman present the method as Algorithm 12.1 of their book. Lindstrom (2010) gave a fast iterative method that reaches the same optimum in a few steps.

References

  1. Richard I. Hartley and Peter Sturm, Triangulation, Computer Vision and Image Understanding 68(2), 1997, 146-157, the polynomial method, its projective invariance and the comparison with linear and midpoint methods
  2. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Sections 12.3 to 12.5, Algorithm 12.1
  3. Peter Lindstrom, Triangulation Made Easy, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2010, 1554-1561, the fast iterative alternative to the polynomial method
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 11.2.4, Triangulation

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