Algorithm Search⌘K

Algorithmcore

Direct linear transformation for homography

Also called DLT, DLT algorithm, normalized DLT for homographies.

Stack two linear equations per point pair into a system Ah = 0 and take h as the right singular vector of A of least singular value.

Time
Θ(n) worst · average · best
Space
Θ(n) extra
Where
n = the number of point pairs
Properties
deterministicexactofflineiterative
Origin
Y. I. Abdel Aziz, H. M. Karara, Richard Hartley, 1971

The direct linear transformation (DLT) for homographies estimates the 3×33 \times 3 matrix HH with xi′∼Hxi\mathbf{x}'_i \sim H\mathbf{x}_i from n≥4n \ge 4 point pairs. Each pair gives two equations that are linear in the nine entries of HH. The algorithm stacks them into a 2n×92n \times 9 matrix AA and returns the unit vector h\mathbf{h} that makes ∥Ah∥\|A\mathbf{h}\| smallest, which is a right singular vector of AA. This page gives the normalized form (Hartley and Zisserman, Algorithm 4.2): it first moves and scales the points of each image with Hartley normalization, and without that step the result on pixel data is poor. The problem it solves, with its other costs and methods, is on the page homography estimation; the same linear idea for a 3×43 \times 4 camera matrix is DLT resectioning.

In plain words

The rule x′∼Hx\mathbf{x}' \sim H\mathbf{x} says that HxH\mathbf{x} points in the same direction as x′\mathbf{x}'. Two vectors point in the same direction when their cross product is zero, and that gives equations in which the unknown entries of HH appear only to the first power. Each pair of points gives two useful equations, so four pairs give eight equations for the nine entries, which fixes HH up to its overall size. With more pairs and noisy points no HH fits all equations, so the algorithm takes the HH that leaves the smallest total leftover. Pixel coordinates are large numbers, and the equations mix them with 1, which makes the leftover depend on the units. Moving the points to the origin and shrinking them first fixes this.

The problem

Input. Point pairs (xi,xi′)(\mathbf{x}_i, \mathbf{x}'_i), i=1,…,ni = 1, \ldots, n, n≥4n \ge 4, given as 2D points, which the algorithm extends to (x,y,1)T(x, y, 1)^{\mathsf T}.

Output. A 3×33 \times 3 matrix HH with ∥H∥F=1\|H\|_F = 1 and with its entry of largest absolute value positive. It minimizes the algebraic error of the normalized points, ∥Ah∥\|A\mathbf{h}\| subject to ∥h∥=1\|\mathbf{h}\| = 1, and then is moved back to the original coordinates. If the pairs are exact images of the points under an invertible homography H0H_0, and four of the points have no three on a line, the output is H0H_0 scaled to this form.

The algorithm

  1. DLT-HOMOGRAPHY(x_1 .. x_n, x'_1 .. x'_n)
  2. 1T <- the similarity that moves the centroid of the x_i to 0 and makes their mean distance to it sqrt(2)
  3. 2T' <- the same similarity for the x'_i
  4. 3for i <- 1 to n
  5. 4y_i <- T x_i ; (u', v', w') <- T' x'_i
  6. 5append the row [ 0^T , -w' y_i^T , v' y_i^T ] to A
  7. 6append the row [ w' y_i^T , 0^T , -u' y_i^T ] to A
  8. 7h <- the right singular vector of A for its smallest singular value
  9. 8H~ <- the 3 x 3 matrix with rows h[1..3], h[4..6], h[7..9]
  10. 9H <- T'^-1 H~ T
  11. 10return H / ||H||_F, with the sign that makes its entry of largest absolute value positive

Lines L1 and L2 are Hartley normalization: each image gets its own similarity. The rows of L5 and L6 come from yi′×H~yi=0\mathbf{y}'_i \times \tilde H \mathbf{y}_i = \mathbf{0}. Write hjT\mathbf{h}^{j\mathsf T} for row jj of H~\tilde H; then H~yi=(h1Tyi,h2Tyi,h3Tyi)T\tilde H\mathbf{y}_i = (\mathbf{h}^{1\mathsf T}\mathbf{y}_i, \mathbf{h}^{2\mathsf T}\mathbf{y}_i, \mathbf{h}^{3\mathsf T}\mathbf{y}_i)^{\mathsf T}, and the first two entries of the cross product are v′ h3Tyi−w′ h2Tyiv'\,\mathbf{h}^{3\mathsf T}\mathbf{y}_i - w'\,\mathbf{h}^{2\mathsf T}\mathbf{y}_i and w′ h1Tyi−u′ h3Tyiw'\,\mathbf{h}^{1\mathsf T}\mathbf{y}_i - u'\,\mathbf{h}^{3\mathsf T}\mathbf{y}_i. The third entry is a combination of these two when w′≠0w' \ne 0, so it adds nothing and is left out. Line L7 is the minimizer of ∥Ah∥\|A\mathbf{h}\| over unit vectors, found by the singular value decomposition. Line L9 undoes the normalization: if y′∼H~y\mathbf{y}' \sim \tilde H\mathbf{y} with y=Tx\mathbf{y} = T\mathbf{x} and y′=T′x′\mathbf{y}' = T'\mathbf{x}', then x′∼T′−1H~Tx\mathbf{x}' \sim T'^{-1}\tilde H T\mathbf{x}. Line L10 picks one of the matrices λH\lambda H so that equal homographies give equal outputs.

Example

Map the unit square (0,0)(0, 0), (1,0)(1, 0), (1,1)(1, 1), (0,1)(0, 1) to the trapezoid (0,0)(0, 0), (4,0)(4, 0), (3,2)(3, 2), (1,2)(1, 2).

line value
L1 centroid (12,12)(\frac12, \frac12), mean distance 22\frac{\sqrt2}{2}, scale 2: T=(20−102−1001)T = \begin{pmatrix} 2 & 0 & -1 \\ 0 & 2 & -1 \\ 0 & 0 & 1 \end{pmatrix}, and the yi\mathbf{y}_i are (±1,±1)(\pm 1, \pm 1)
L2 centroid (2,1)(2, 1), mean distance 5+22≈1.8251\frac{\sqrt5 + \sqrt2}{2} \approx 1.8251, scale s=22/(5+2)≈0.7749s = 2\sqrt2/(\sqrt5 + \sqrt2) \approx 0.7749: T′=(s0−2s0s−s001)T' = \begin{pmatrix} s & 0 & -2s \\ 0 & s & -s \\ 0 & 0 & 1 \end{pmatrix}
L3 to L6 8 rows; for the third pair, y=(1,1,1)\mathbf{y} = (1, 1, 1) and T′(3,2,1)T=(s,s,1)T'(3, 2, 1)^{\mathsf T} = (s, s, 1), so the rows are [0,0,0,−1,−1,−1,s,s,s][0, 0, 0, -1, -1, -1, s, s, s] and [1,1,1,0,0,0,−s,−s,−s][1, 1, 1, 0, 0, 0, -s, -s, -s]
L7, L8 AA has rank 8, and its null vector gives H~∼(2s0001.5s0.5s00.51.5)≈(1.54970001.16230.387400.51.5)\tilde H \sim \begin{pmatrix} 2s & 0 & 0 \\ 0 & 1.5s & 0.5s \\ 0 & 0.5 & 1.5 \end{pmatrix} \approx \begin{pmatrix} 1.5497 & 0 & 0 \\ 0 & 1.1623 & 0.3874 \\ 0 & 0.5 & 1.5 \end{pmatrix}
L9 T′−1H~T∼(420040011)T'^{-1}\tilde H T \sim \begin{pmatrix} 4 & 2 & 0 \\ 0 & 4 & 0 \\ 0 & 1 & 1 \end{pmatrix}
L10 ∥H∥F=38\|H\|_F = \sqrt{38}; the output is that matrix divided by 38≈6.1644\sqrt{38} \approx 6.1644, with largest entry 4/38≈0.64894/\sqrt{38} \approx 0.6489

A check of one pair: H(1,1,1)T=(6,4,2)T∼(3,2,1)TH(1, 1, 1)^{\mathsf T} = (6, 4, 2)^{\mathsf T} \sim (3, 2, 1)^{\mathsf T}. For the third pair, the rows of the plain DLT without normalization would be [0,0,0,−1,−1,−1,2,2,2][0, 0, 0, -1, -1, -1, 2, 2, 2] and [1,1,1,0,0,0,−3,−3,−3][1, 1, 1, 0, 0, 0, -3, -3, -3], and both are orthogonal to h=(4,2,0,0,4,0,0,1,1)\mathbf{h} = (4, 2, 0, 0, 4, 0, 0, 1, 1).

Correctness

Each pair of rows is equivalent to yi′×H~yi=0\mathbf{y}'_i \times \tilde H\mathbf{y}_i = \mathbf{0}, which is yi′∼H~yi\mathbf{y}'_i \sim \tilde H\mathbf{y}_i when H~yi≠0\tilde H\mathbf{y}_i \ne \mathbf{0}. On exact data, four pairs with no three of the points on a line make AA of rank exactly 8. Then the null space of AA is spanned by the true normalized matrix, so line L7 returns it up to sign, and line L9 gives back the true HH up to scale. For noisy data, the right singular vector of the smallest singular value minimizes ∥Ah∥\|A\mathbf{h}\| over unit vectors, by the SVD. The full proof is below.

Proof: The normalized DLT minimizes the algebraic error and recovers H exactly from exact datafull

We use the notation of the page. The input is n≥4n \ge 4 pairs of 2D points, written as xi=(xi,yi,1)T\mathbf{x}_i = (x_i, y_i, 1)^{\mathsf T} and xi′=(xi′,yi′,1)T\mathbf{x}'_i = (x'_i, y'_i, 1)^{\mathsf T}. A set of points of P2\mathbb{P}^2 is in general position when no three of them lie on one line, which for three points means that their vectors are linearly independent. For a 3×33 \times 3 matrix GG we write g∈R9\mathbf{g} \in \mathbb{R}^9 for its rows put one after the other, so ∥g∥=∥G∥F\|\mathbf{g}\| = \|G\|_F. The canonical form of a nonzero matrix GG is G/∥G∥FG / \|G\|_F times the sign of its entry of largest absolute value (on a tie, the first such entry in row order).

Claim. (a) The vector h\mathbf{h} of line L7 minimizes ∥Ah∥\|A\mathbf{h}\| over all unit vectors. (b) If there is an invertible H0H_0 with xi′∼H0xi\mathbf{x}'_i \sim H_0\mathbf{x}_i for all ii, and four of the xi\mathbf{x}_i are in general position, then DLT-HOMOGRAPHY returns the canonical form of H0H_0.

Lemma 1 (the two rows). Let y′=(u′,v′,w′)T\mathbf{y}' = (u', v', w')^{\mathsf T} with w′≠0w' \ne 0, let y∈R3\mathbf{y} \in \mathbb{R}^3, and let GG be a 3×33 \times 3 matrix. The rows of lines L5 and L6, applied to g\mathbf{g}, are 0 if and only if y′×Gy=0\mathbf{y}' \times G\mathbf{y} = \mathbf{0}, that is, if and only if GyG\mathbf{y} is a multiple of y′\mathbf{y}' (possibly the zero multiple).

Proof. Let z=Gy\mathbf{z} = G\mathbf{y}, so zj=gjTyz_j = \mathbf{g}^{j\mathsf T}\mathbf{y} with gjT\mathbf{g}^{j\mathsf T} the row jj of GG. The row of L5 applied to g\mathbf{g} is −w′z2+v′z3-w' z_2 + v' z_3, and the row of L6 is w′z1−u′z3w' z_1 - u' z_3. These are the first two entries of y′×z\mathbf{y}' \times \mathbf{z}, whose third entry is u′z2−v′z1u' z_2 - v' z_1. If the first two are 0, then z1=u′z3/w′z_1 = u' z_3 / w' and z2=v′z3/w′z_2 = v' z_3 / w', so the third is (u′v′z3−v′u′z3)/w′=0(u' v' z_3 - v' u' z_3)/w' = 0 and z=(z3/w′) y′\mathbf{z} = (z_3 / w')\,\mathbf{y}'. The converse is clear. □\square

The points yi′=T′xi′\mathbf{y}'_i = T'\mathbf{x}'_i have last entry 1, because the last row of the similarity T′T' is (0,0,1)(0, 0, 1). So Lemma 1 applies to every pair, and the null space of AA is exactly the set of g\mathbf{g} with yi′×Gyi=0\mathbf{y}'_i \times G\mathbf{y}_i = \mathbf{0} for all ii.

Lemma 2 (minimum of the algebraic error). Let AA be an m×9m \times 9 real matrix and let σmin⁡≥0\sigma_{\min} \ge 0 be its smallest singular value, counted as 0 when m<9m < 9. Then min⁡∥h∥=1∥Ah∥=σmin⁡\min_{\|\mathbf{h}\| = 1} \|A\mathbf{h}\| = \sigma_{\min}, and a right singular vector for σmin⁡\sigma_{\min} attains it.

Proof. Let ATA=Vdiag⁡(σ12,…,σ92)VTA^{\mathsf T}A = V \operatorname{diag}(\sigma_1^2, \ldots, \sigma_9^2) V^{\mathsf T} with VV orthogonal, where σ1≥⋯≥σ9=σmin⁡\sigma_1 \ge \cdots \ge \sigma_9 = \sigma_{\min} are the singular values (with zeros added when m<9m < 9). For a unit vector h\mathbf{h} put c=VTh\mathbf{c} = V^{\mathsf T}\mathbf{h}, also a unit vector. Then ∥Ah∥2=hTATAh=∑jσj2cj2≥σ92∑jcj2=σ92\|A\mathbf{h}\|^2 = \mathbf{h}^{\mathsf T}A^{\mathsf T}A\mathbf{h} = \sum_j \sigma_j^2 c_j^2 \ge \sigma_9^2 \sum_j c_j^2 = \sigma_9^2. The last column of VV, the right singular vector for σ9\sigma_9, gives c=e9\mathbf{c} = \mathbf{e}_9 and equality. □\square

Part (a) of the claim is Lemma 2 applied to line L7.

Lemma 3 (four points fix the matrix). Let H0H_0 be invertible, and let y1,…,y4\mathbf{y}_1, \ldots, \mathbf{y}_4 be in general position, with yi′∼H0yi\mathbf{y}'_i \sim H_0\mathbf{y}_i. If a matrix GG satisfies yi′×Gyi=0\mathbf{y}'_i \times G\mathbf{y}_i = \mathbf{0} for i=1,…,4i = 1, \ldots, 4, then G=νH0G = \nu H_0 for some real ν\nu.

Proof. Write H0yi=κiyi′H_0\mathbf{y}_i = \kappa_i\mathbf{y}'_i with κi≠0\kappa_i \ne 0 (it is not 0, since H0H_0 is invertible and yi≠0\mathbf{y}_i \ne \mathbf{0}), and Gyi=μiyi′G\mathbf{y}_i = \mu_i\mathbf{y}'_i, which holds by the cross product condition. Let M=H0−1GM = H_0^{-1}G. Then Myi=(μi/κi) yi=νiyiM\mathbf{y}_i = (\mu_i / \kappa_i)\,\mathbf{y}_i = \nu_i\mathbf{y}_i. The vectors y1,y2,y3\mathbf{y}_1, \mathbf{y}_2, \mathbf{y}_3 are a basis of R3\mathbb{R}^3, so y4=ay1+by2+cy3\mathbf{y}_4 = a\mathbf{y}_1 + b\mathbf{y}_2 + c\mathbf{y}_3. None of a,b,ca, b, c is 0: if a=0a = 0, then y2,y3,y4\mathbf{y}_2, \mathbf{y}_3, \mathbf{y}_4 would be dependent, so three of the points would be on a line. Apply MM to both sides:

ν4ay1+ν4by2+ν4cy3=ν1ay1+ν2by2+ν3cy3.\nu_4 a\mathbf{y}_1 + \nu_4 b\mathbf{y}_2 + \nu_4 c\mathbf{y}_3 = \nu_1 a\mathbf{y}_1 + \nu_2 b\mathbf{y}_2 + \nu_3 c\mathbf{y}_3 .

By the independence of y1,y2,y3\mathbf{y}_1, \mathbf{y}_2, \mathbf{y}_3 and since a,b,c≠0a, b, c \ne 0, ν1=ν2=ν3=ν4=:ν\nu_1 = \nu_2 = \nu_3 = \nu_4 =: \nu. So MM acts as νI\nu I on a basis, M=νIM = \nu I, and G=νH0G = \nu H_0. □\square

Lemma 4 (normalization). Let H~0=T′H0T−1\tilde H_0 = T' H_0 T^{-1}. Then yi′∼H~0yi\mathbf{y}'_i \sim \tilde H_0\mathbf{y}_i for all ii, H~0\tilde H_0 is invertible, and four of the yi\mathbf{y}_i are in general position. For every nonzero λ\lambda, T′−1(λH~0)T=λH0T'^{-1}(\lambda\tilde H_0)T = \lambda H_0.

Proof. H~0yi=T′H0T−1Txi=T′H0xi∼T′xi′=yi′\tilde H_0\mathbf{y}_i = T' H_0 T^{-1} T\mathbf{x}_i = T' H_0\mathbf{x}_i \sim T'\mathbf{x}'_i = \mathbf{y}'_i. It is a product of invertible matrices. The map x↦Tx\mathbf{x} \mapsto T\mathbf{x} is an invertible linear map of R3\mathbb{R}^3, so it keeps linear independence, and the four points stay in general position. The last identity is direct. □\square

Proof of part (b). By Lemma 4 and Lemma 1, h~0\tilde{\mathbf{h}}_0 lies in the null space of AA, so σmin⁡=0\sigma_{\min} = 0. By Lemma 3, applied to H~0\tilde H_0 and the four points in general position, and by Lemma 1, every null vector of AA is a multiple of h~0\tilde{\mathbf{h}}_0. So the null space is the line spanned by h~0\tilde{\mathbf{h}}_0, AA has rank 8, and its other singular values are positive. By Lemma 2, line L7 returns a unit vector h\mathbf{h} with Ah=0A\mathbf{h} = \mathbf{0}, so h=±h~0/∥h~0∥\mathbf{h} = \pm\tilde{\mathbf{h}}_0 / \|\tilde{\mathbf{h}}_0\| and H~=λH~0\tilde H = \lambda\tilde H_0 with λ≠0\lambda \ne 0. By Lemma 4, line L9 gives H=λH0H = \lambda H_0. Line L10 divides by ∥H∥F=∣λ∣ ∥H0∥F\|H\|_F = |\lambda|\,\|H_0\|_F and fixes the sign by a rule that depends only on the matrix up to a positive factor, so the result is the same for every λ≠0\lambda \ne 0: it is the canonical form of H0H_0. ■\blacksquare

Remark (covariance under similarities). Let SS and S′S' be similarities of the two images. The normalized points of SxiS\mathbf{x}_i are QyiQ\mathbf{y}_i for a matrix Q=(R00T1)Q = \begin{pmatrix} R & \mathbf{0} \\ \mathbf{0}^{\mathsf T} & 1 \end{pmatrix} with RR a 2×22 \times 2 orthogonal matrix, because a similarity moves the centroid with the points and multiplies all distances by the same factor; likewise Q′Q' for the second image. For orthogonal Q′Q', Q′a×Q′b=det⁡(Q′) Q′(a×b)Q'\mathbf{a} \times Q'\mathbf{b} = \det(Q')\,Q'(\mathbf{a} \times \mathbf{b}), and the first two entries of Q′cQ'\mathbf{c} are R′R' times the first two entries of c\mathbf{c}. So the algebraic error of G′=Q′GQTG' = Q' G Q^{\mathsf T} on the new points equals the algebraic error of GG on the old ones, and G↦Q′GQTG \mapsto Q' G Q^{\mathsf T} keeps the Frobenius norm. The minimizer moves with the data, and the output for the moved points is the canonical form of S′HS−1S' H S^{-1} whenever the minimizer is unique. The plain DLT, without normalization, has no such property, because a translation of the pixel frame changes AA by more than an orthogonal change of variables.

Complexity

Counting arithmetic operations, lines L1 and L2 cost Θ(n)\Theta(n), the loop costs Θ(n)\Theta(n), and AA has 2n2n rows and a fixed number of 9 columns. The SVD of a 2n×92n \times 9 matrix costs Θ(n)\Theta(n): for example, a QR decomposition reduces it to a 9×99 \times 9 triangle in Θ(n)\Theta(n) operations, and the SVD of that triangle takes a fixed amount of work. So the time is Θ(n)\Theta(n). The matrix AA needs Θ(n)\Theta(n) extra space; a version that only keeps ATAA^{\mathsf T}A needs Θ(1)\Theta(1), at the price of squaring the condition number.

In floating point the accuracy depends on the condition of AA. Without normalization the entries of a row range from about 1 to the product of two pixel coordinates, around 10510^5 or 10610^6, and the gap between the smallest and the second smallest singular value is tiny compared with the largest one. Normalization makes all entries about 1. The page on Hartley normalization gives a measured example.

Properties

  • Exact on exact data. If xi′∼H0xi\mathbf{x}'_i \sim H_0\mathbf{x}_i for an invertible H0H_0 and four of the points are in general position, the output is H0H_0 in canonical form, for any number n≥4n \ge 4 of pairs.
  • Covariant under similarities. If the points of the first image are moved by a similarity SS and those of the second by S′S', the output becomes the canonical form of S′HS−1S' H S^{-1}. The plain DLT, without lines L1 and L2, does not have this property: its result depends on where the origin of the pixel frame is and on the unit.
  • Linear and non-iterative. No starting point and no iterations; the cost is one SVD.
  • Algebraic, not geometric. On noisy data the output minimizes the algebraic error of the normalized points, not a distance in pixels. See algebraic and geometric error.
  • Swap gives the inverse. On exact data, exchanging the two images returns the canonical form of H0−1H_0^{-1}.

Variants and improvements

  • Plain DLT. Lines L1 and L2 with T=T′=IT = T' = I. It is HZ's basic algorithm and is fine only for small, centered coordinates.
  • Fix h33=1h_{33} = 1. Solve an ordinary 2n×82n \times 8 least squares problem for the other eight entries. It fails when the true h33h_{33} is 0 or near 0, which happens when the origin of image 1 maps to a point at or near infinity.
  • Normal equations. Take the eigenvector of ATAA^{\mathsf T}A for its smallest eigenvalue. It needs only a 9×99 \times 9 matrix, but squares the condition number.
  • Four points in closed form. For exactly four pairs, map both quadruples to the canonical frame (1,0,0)(1, 0, 0), (0,1,0)(0, 1, 0), (0,0,1)(0, 0, 1), (1,1,1)(1, 1, 1) and compose; this is fast in a minimal solver inside RANSAC.
  • Lines and mixed data. A matched pair of lines satisfies li∼HTli′\mathbf{l}_i \sim H^{\mathsf T}\mathbf{l}'_i, so li×HTli′=0\mathbf{l}_i \times H^{\mathsf T}\mathbf{l}'_i = \mathbf{0} gives two more rows that are linear in h\mathbf{h}, and lines and points can share one matrix AA.
  • Refinement. Use the output as the starting point of a geometric fit, the Gold Standard method of homography estimation or a Sampson fit, with Levenberg-Marquardt.

When to use it

Use the normalized DLT whenever a homography must be found from point matches: as the minimal solver inside RANSAC, as the estimate on the inliers, and as the start of a nonlinear refinement. On its own it is accurate enough for many tasks, such as stitching previews or document rectification. When the best accuracy matters, for example in calibration or measurement, refine it with a geometric cost. If the matches contain outliers, do not run it on all of them: one gross outlier can move the result far.

Pitfalls

  • No normalization. On pixel coordinates the plain DLT can be wrong by many pixels, even with little noise.
  • One normalization for both images. Each image needs its own TT, computed from its own points.
  • Degenerate points. Three of four points on a line, or all points near one line, make the two smallest singular values of AA both near 0. Check that the second smallest singular value is not close to the smallest one.
  • Direction. The result maps image 1 to image 2. For the other direction use H−1H^{-1}, not HTH^{\mathsf T}.
  • Comparing results. HH and −H-H are the same homography. Compare canonical forms, or compare the maps on test points.
  • Outliers. The algebraic least squares fit has no robustness. Use it inside RANSAC or another robust method.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

cvla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

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

from __future__ import annotations

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

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

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


# ---------------------------------------------------------------- basics

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """The cross product a x b of two 3-vectors."""
    return [a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0]]


def skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


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

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
dlt_homography.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dlt-homography/. The authors are listed in prov/12XVFY.jsonl.
"""Normalized direct linear transformation (DLT) for a 2D homography.

Given n >= 4 point pairs x1[i] <-> x2[i] (pixels, 2 entries each), find the
3 x 3 matrix H with x2[i] ~ H x1[i]. This is the normalized DLT of Hartley
and Zisserman (Algorithm 4.2). The result has Frobenius norm 1, and its
entry of largest absolute value is positive.

Cost: O(n) to build the 2n x 9 matrix A and O(n) for its SVD (the number of
columns is fixed at 9), so O(n) in total.
"""

from __future__ import annotations

import math
from typing import List, Sequence

from cvla import inv, matvec, mul, norm, nullvec, scale, svd

Matrix = List[List[float]]


def normalizing_similarity(pts: Sequence[Sequence[float]]) -> Matrix:
    """The 3 x 3 similarity T that moves the centroid of the points to the
    origin and scales them so that their mean distance to it is sqrt(2).

    Precondition: the points are not all equal. Cost O(n)."""
    n = len(pts)
    cx = sum(float(p[0]) for p in pts) / n
    cy = sum(float(p[1]) for p in pts) / n
    d = sum(math.hypot(float(p[0]) - cx, float(p[1]) - cy) for p in pts) / n
    if d == 0.0:
        raise ValueError("all points coincide")
    s = math.sqrt(2.0) / d
    return [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]]


def dlt_rows(y1: Sequence[float], y2: Sequence[float]) -> Matrix:
    """The two rows of A for one pair of homogeneous points y1, y2 = (u, v, w).

    They are rows 1 and 2 of [y2]_x (y1 kron I) and say y2 x (H y1) = 0."""
    u, v, w = y2
    zero = [0.0, 0.0, 0.0]
    r1 = zero + [-w * c for c in y1] + [v * c for c in y1]  # @line L5
    r2 = [w * c for c in y1] + zero + [-u * c for c in y1]  # @line L6
    return [r1, r2]


def canonical(H: Sequence[Sequence[float]]) -> Matrix:
    """H scaled to Frobenius norm 1, with its entry of largest absolute
    value positive (the first such entry, in row order, on a tie)."""
    f = norm(H)
    if f == 0.0:
        raise ValueError("zero matrix")
    big = max((x for row in H for x in row), key=abs)
    return scale(H, (1.0 if big > 0 else -1.0) / f)


def dlt_homography(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]],
                   normalize: bool = True) -> Matrix:
    """Estimate H with x2[i] ~ H x1[i] from n >= 4 pairs of 2D points.

    With normalize=False the points are used as they are: this is the plain
    DLT, which is badly conditioned on pixel data. Raises ValueError for
    fewer than 4 pairs or for coincident points. The result is exact (up to
    rounding) when the pairs are exact and no 3 of 4 points are collinear.
    Cost O(n)."""
    n = len(x1)
    if n != len(x2) or n < 4:
        raise ValueError("need at least 4 point pairs")
    if normalize:
        T1 = normalizing_similarity(x1)  # @line L1
        T2 = normalizing_similarity(x2)  # @line L2
    else:
        T1 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
        T2 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    a: Matrix = []
    for p, q in zip(x1, x2):  # @line L3
        y1 = matvec(T1, [float(p[0]), float(p[1]), 1.0])  # @line L4
        y2 = matvec(T2, [float(q[0]), float(q[1]), 1.0])  # @line L4
        a.extend(dlt_rows(y1, y2))
    h = nullvec(a)  # @line L7
    Hn = [h[0:3], h[3:6], h[6:9]]  # @line L8
    H = mul(mul(inv(T2), Hn), T1)  # @line L9
    return canonical(H)  # @line L10


def apply(H: Sequence[Sequence[float]], p: Sequence[float]) -> List[float]:
    """The image (u, v) of the 2D point p under H. Raises ZeroDivisionError
    if p maps to a point at infinity."""
    x = matvec(H, [p[0], p[1], 1.0])
    return [x[0] / x[2], x[1] / x[2]]


def transfer_errors(H: Sequence[Sequence[float]], x1: Sequence[Sequence[float]],
                    x2: Sequence[Sequence[float]]) -> List[float]:
    """The distance in the second image between x2[i] and H x1[i]."""
    out = []
    for p, q in zip(x1, x2):
        u, v = apply(H, p)
        out.append(math.hypot(u - q[0], v - q[1]))
    return out


def dlt_singular_values(x1: Sequence[Sequence[float]], x2: Sequence[Sequence[float]]) -> List[float]:
    """The 9 singular values (descending) of the normalized DLT matrix,
    padded with zero rows when n = 4. A second singular value near zero
    shows a degenerate configuration."""
    T1, T2 = normalizing_similarity(x1), normalizing_similarity(x2)
    a: Matrix = []
    for p, q in zip(x1, x2):
        a.extend(dlt_rows(matvec(T1, [p[0], p[1], 1.0]), matvec(T2, [q[0], q[1], 1.0])))
    a += [[0.0] * 9 for _ in range(max(0, 9 - len(a)))]
    return svd(a)[1]


def inverse(H: Sequence[Sequence[float]]) -> Matrix:
    """The inverse homography, in canonical form."""
    return canonical(inv(H))
test_dlt_homography.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dlt-homography/. The authors are listed in prov/12XVFY.jsonl.
"""Tests of the normalized DLT for homographies."""

import math
import random
from fractions import Fraction

import pytest

from cvla import inv, matvec, mul, norm, sub
from dlt_homography import (apply, canonical, dlt_homography, dlt_rows,
                            dlt_singular_values, inverse, normalizing_similarity,
                            transfer_errors)


def exact_four_point(src, dst):
    """Independent oracle: solve the 8 x 8 linear system with h33 = 1 in
    exact rational arithmetic (Gauss-Jordan elimination)."""
    a = []
    for (x, y), (u, v) in zip(src, dst):
        x, y, u, v = Fraction(x), Fraction(y), Fraction(u), Fraction(v)
        a.append([x, y, 1, 0, 0, 0, -u * x, -u * y, u])
        a.append([0, 0, 0, x, y, 1, -v * x, -v * y, v])
    a = [[Fraction(c) for c in row] for row in a]
    for c in range(8):
        p = next(r for r in range(c, 8) if a[r][c] != 0)
        a[c], a[p] = a[p], a[c]
        for r in range(8):
            if r != c and a[r][c] != 0:
                f = a[r][c] / a[c][c]
                a[r] = [x - f * y for x, y in zip(a[r], a[c])]
    h = [a[i][8] / a[i][i] for i in range(8)] + [Fraction(1)]
    return [h[0:3], h[3:6], h[6:9]]


def random_homography(rng):
    """A homography of pixel images that keeps [0, 640] x [0, 480] in front
    (third coordinate > 0)."""
    return [[1.0 + rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3), rng.uniform(-50, 50)],
            [rng.uniform(-0.3, 0.3), 1.0 + rng.uniform(-0.3, 0.3), rng.uniform(-50, 50)],
            [rng.uniform(-4e-4, 4e-4), rng.uniform(-4e-4, 4e-4), 1.0]]


def random_points(rng, n):
    return [[rng.uniform(0, 640), rng.uniform(0, 480)] for _ in range(n)]


def rel_dist(a, b):
    return norm(sub(canonical(a), canonical(b)))


def test_square_to_trapezoid():
    src = [(0, 0), (1, 0), (1, 1), (0, 1)]
    dst = [(0, 0), (4, 0), (3, 2), (1, 2)]
    H = dlt_homography(src, dst)
    want = [[4.0, 2.0, 0.0], [0.0, 4.0, 0.0], [0.0, 1.0, 1.0]]
    assert rel_dist(H, want) <= 1e-12
    assert exact_four_point(src, dst) == [[4, 2, 0], [0, 4, 0], [0, 1, 1]]
    u, v = apply(H, (0.5, 0.5))
    assert abs(u - 2.0) <= 1e-12 and abs(v - 4.0 / 3.0) <= 1e-12


def test_rows_vanish_on_the_true_homography():
    rng = random.Random(1)
    for _ in range(50):
        H = random_homography(rng)
        h = [c for row in H for c in row]
        p = random_points(rng, 1)[0]
        y1 = [p[0], p[1], 1.0]
        y2 = matvec(H, y1)
        for row in dlt_rows(y1, y2):
            assert abs(sum(a * b for a, b in zip(row, h))) <= 1e-9 * norm(row) * norm(h)


def test_four_points_against_exact_oracle():
    rng = random.Random(2)
    done = 0
    while done < 40:
        src = [(rng.randint(0, 640), rng.randint(0, 480)) for _ in range(4)]
        dst = [(rng.randint(0, 640), rng.randint(0, 480)) for _ in range(4)]
        if any(Fraction(0) == ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))
               for pts in (src, dst) for i, a in enumerate(pts) for j, b in enumerate(pts)
               for k, c in enumerate(pts) if i < j < k):
            continue
        Hx = exact_four_point(src, dst)
        Hf = [[float(c) for c in row] for row in Hx]
        H = dlt_homography(src, dst)
        assert rel_dist(H, Hf) <= 1e-8
        done += 1


def test_exact_recovery_many_points():
    rng = random.Random(3)
    for n in (4, 5, 8, 20, 50):
        for _ in range(4):
            Ht = random_homography(rng)
            x1 = random_points(rng, n)
            x2 = [apply(Ht, p) for p in x1]
            H = dlt_homography(x1, x2)
            assert rel_dist(H, Ht) <= 1e-8
            assert max(transfer_errors(H, x1, x2)) <= 1e-7


def test_plain_dlt_agrees_on_exact_data():
    rng = random.Random(4)
    Ht = random_homography(rng)
    x1 = random_points(rng, 10)
    x2 = [apply(Ht, p) for p in x1]
    assert rel_dist(dlt_homography(x1, x2, normalize=False), Ht) <= 1e-6


def test_normalizing_similarity():
    rng = random.Random(5)
    pts = random_points(rng, 30)
    T = normalizing_similarity(pts)
    q = [matvec(T, [p[0], p[1], 1.0]) for p in pts]
    assert abs(sum(r[0] for r in q)) <= 1e-9 and abs(sum(r[1] for r in q)) <= 1e-9
    mean = sum(math.hypot(r[0], r[1]) for r in q) / len(q)
    assert abs(mean - math.sqrt(2.0)) <= 1e-12
    with pytest.raises(ValueError):
        normalizing_similarity([[3.0, 4.0]] * 5)


def test_covariance_under_similarities():
    """Normalized DLT commutes with similarity changes of both frames."""
    rng = random.Random(6)
    Ht = random_homography(rng)
    x1 = random_points(rng, 30)
    x2 = [[a + rng.gauss(0, 1.0) for a in apply(Ht, p)] for p in x1]
    H = dlt_homography(x1, x2)
    c, s = math.cos(0.7), math.sin(0.7)
    S1 = [[3 * c, -3 * s, 100.0], [3 * s, 3 * c, -40.0], [0.0, 0.0, 1.0]]
    S2 = [[0.5, 0.0, 7.0], [0.0, 0.5, 9.0], [0.0, 0.0, 1.0]]
    y1 = [apply(S1, p) for p in x1]
    y2 = [apply(S2, p) for p in x2]
    G = dlt_homography(y1, y2)
    assert rel_dist(G, mul(mul(S2, H), inv(S1))) <= 1e-9


def test_noise_gives_small_transfer_error():
    rng = random.Random(7)
    sigma = 0.5
    for _ in range(5):
        Ht = random_homography(rng)
        x1 = random_points(rng, 60)
        x2 = [[a + rng.gauss(0, sigma) for a in apply(Ht, p)] for p in x1]
        H = dlt_homography(x1, x2)
        clean = [apply(Ht, p) for p in x1]
        err = transfer_errors(H, x1, clean)
        assert math.sqrt(sum(e * e for e in err) / len(err)) <= sigma


def test_swap_gives_inverse():
    rng = random.Random(8)
    Ht = random_homography(rng)
    x1 = random_points(rng, 12)
    x2 = [apply(Ht, p) for p in x1]
    assert rel_dist(dlt_homography(x2, x1), inverse(dlt_homography(x1, x2))) <= 1e-8


def test_three_collinear_points_lose_rank():
    src = [(0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (0.0, 3.0)]
    dst = [(0.0, 0.0), (1.0, 0.5), (2.0, 1.0), (1.0, 4.0)]
    s = dlt_singular_values(src, dst)
    assert s[-1] <= 1e-12 * s[0]
    assert s[-2] <= 1e-12 * s[0]
    good = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
    s = dlt_singular_values(good, dst)
    assert s[-2] >= 1e-3 * s[0]


def test_bad_input():
    with pytest.raises(ValueError):
        dlt_homography([(0, 0), (1, 0), (0, 1)], [(0, 0), (1, 0), (0, 1)])
    with pytest.raises(ValueError):
        dlt_homography([(0, 0)] * 4, [(0, 0), (1, 0), (0, 1), (1, 1)])

History

The name direct linear transformation comes from photogrammetry, where Abdel-Aziz and Karara (1971) estimated the camera from linear equations in the entries of its matrix. In computer vision the same idea gives the homography from four or more point pairs. The method was long held to be inaccurate. Hartley (1997) showed, for the eight-point algorithm and for linear estimates in general, that the poor results came from the bad condition of the system on raw pixel coordinates, and that translating and scaling the points first makes the linear estimate nearly as good as iterative ones. Hartley and Zisserman (2000, second edition 2004) give the normalized DLT for homographies as their Algorithm 4.2.

References

  1. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 4.1, The Direct Linear Transformation (DLT) algorithm, and Section 4.4, Transformation invariance and normalization (the normalized DLT, Algorithm 4.2)
  2. Richard I. Hartley, In defense of the eight-point algorithm, IEEE Transactions on Pattern Analysis and Machine Intelligence 19(6), 1997, 580-593, the normalization of the points and why it improves the condition of the linear system
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 8.1, Pairwise alignment (the linear least squares estimate of a homography)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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