Algorithm Search⌘K

Algorithmadvanced

EPnP

Also called efficient perspective-n-point.

Write each 3D point as a weighted sum of four control points and solve linearly for the control points in the camera frame, an O(n) solution of PnP.

Time
Θ(n) worst · average · best
Space
Θ(n) extra
Where
n = the number of point correspondences, at least 4
Properties
deterministicexactofflineiterative
Origin
Francesc Moreno Noguer, Vincent Lepetit, Pascal Fua, 2007

EPnP finds the pose of a calibrated camera from n≥4n \ge 4 known 3D points and their images, in time linear in nn. It solves the perspective-n-point problem without an iterative search over the pose. The method chooses four control points in the world and writes each 3D point as a weighted sum of them, with weights that add up to 1. A rigid motion keeps these weights, so the same sums hold in the camera frame. The 12 unknown camera coordinates of the control points then satisfy a homogeneous linear system with two rows per point. Its solution is a combination of a few eigenvectors of a 12×1212 \times 12 matrix, and the coefficients follow from the known distances between the control points. A rigid alignment of the world points with the recovered camera points gives the rotation and the translation. Because the work on the points is one pass to build a 12×1212 \times 12 matrix, EPnP is fast for large nn, and it is a common choice inside RANSAC and as the first estimate before bundle adjustment.

In plain words

You know where some points are in the room, and you see them in a photo. You want to know where the camera stood. Instead of finding the camera position directly, EPnP picks four helper points that frame the whole set, and describes every real point as a mix of the four helpers. That mix stays the same when you look from the camera. So it is enough to find where the four helpers are as seen from the camera: only twelve numbers. Each photo point gives two simple equations for them. Solve these, use the known distances between the helpers to fix the size, and then turn the result into a camera position and direction.

The problem

Input. World points X1,…,Xn\mathbf{X}_1, \ldots, \mathbf{X}_n, n≥4n \ge 4, not all in one plane, and their normalized images yi=(ui,vi)=K−1xi\mathbf{y}_i = (u_i, v_i) = K^{-1}\mathbf{x}_i.

Output. A rotation RR and a translation t\mathbf{t} such that Xc=RXi+t\mathbf{X}_c = R\mathbf{X}_i + \mathbf{t} projects to yi\mathbf{y}_i for every ii, exactly on exact data and in the least squares sense of the method on noisy data.

The algorithm

Line L1 takes the centroid c1\mathbf{c}_1 of the points and adds the three principal directions of the points, each scaled by the spread of the points along it, to get c2\mathbf{c}_2, c3\mathbf{c}_3, c4\mathbf{c}_4. Line L2 finds the weights αij\alpha_{ij} with Xi=∑jαijcj\mathbf{X}_i = \sum_j \alpha_{ij}\mathbf{c}_j and ∑jαij=1\sum_j \alpha_{ij} = 1. In the camera frame Xc,i=∑jαijcjc\mathbf{X}_{c,i} = \sum_j \alpha_{ij}\mathbf{c}^c_j, and the projection equations uiZ=Xu_i Z = X and viZ=Yv_i Z = Y become two linear equations in the 12 unknowns x=(c1c,…,c4c)\mathbf{x} = (\mathbf{c}^c_1, \ldots, \mathbf{c}^c_4).

  1. EPNP(X_1 .. X_n, y_1 .. y_n)
  2. 1c_1 <- centroid of the X_i; c_2, c_3, c_4 <- c_1 + scaled principal directions
  3. 2for each i: alpha_i <- weights with X_i = sum_j alpha_ij c_j and sum_j alpha_ij = 1
  4. 3M <- the 2n x 12 matrix with rows (alpha_ij, 0, -alpha_ij u_i) and (0, alpha_ij, -alpha_ij v_i), j = 1..4
  5. 4v_1 .. v_4 <- eigenvectors of M^T M for its 4 smallest eigenvalues
  6. 5rho_ab <- ||c_a - c_b||^2 for the 6 pairs of control points
  7. 6for N = 1, 2, 3: beta <- linearized solution of ||sum_k beta_k (v_k^[a] - v_k^[b])||^2 = rho_ab
  8. 7refine the four betas by Gauss-Newton on the same 6 equations
  9. 8c^c <- sum_k beta_k v_k; p_i <- sum_j alpha_ij c^c_j; negate all p_i if their mean depth is negative
  10. 9(R, t) <- rigid alignment of the X_i to the p_i
  11. 10e <- reprojection error of (R, t)
  12. 11return the (R, t) of least e

Here vk[a]\mathbf{v}_k^{[a]} is the 3-vector of control point aa in vk\mathbf{v}_k. For N=1N = 1 the camera control points are βv1\beta\mathbf{v}_1, and line L6 takes β=∑∥v1[a]−v1[b]∥ρab/∑∥v1[a]−v1[b]∥2\beta = \sum \|\mathbf{v}_1^{[a]} - \mathbf{v}_1^{[b]}\|\sqrt{\rho_{ab}} / \sum \|\mathbf{v}_1^{[a]} - \mathbf{v}_1^{[b]}\|^2 over the 6 pairs. For N=2N = 2 and N=3N = 3 the 6 distance equations are linear in the products βkβl\beta_k\beta_l; line L6 solves them by least squares and reads βk\beta_k from the squares, with the signs from the cross terms. Line L9 is the Kabsch algorithm.

Example

Take the six world points (0,0,0)(0, 0, 0), (1,0,0)(1, 0, 0), (0,1,0)(0, 1, 0), (0,0,1)(0, 0, 1), (1,1,0.5)(1, 1, 0.5), (0.3,0.7,1.2)(0.3, 0.7, 1.2) and the true pose R=Ry(0.3)Rx(0.2)R = R_y(0.3)R_x(0.2), t=(0.2,−0.1,4)\mathbf{t} = (0.2, -0.1, 4). The normalized images are (0.05,−0.025)(0.05, -0.025), (0.3119,−0.027)(0.3119, -0.027), (0.0617,0.21)(0.0617, 0.21), (0.0992,−0.0605)(0.0992, -0.0605), (0.3115,0.179)(0.3115, 0.179) and (0.1694,0.0673)(0.1694, 0.0673).

line value
L1 c1=(0.3833,0.45,0.45)\mathbf{c}_1 = (0.3833, 0.45, 0.45), c2=(0.1991,0.5398,0.9183)\mathbf{c}_2 = (0.1991, 0.5398, 0.9183), c3=(0.6734,0.8382,0.4897)\mathbf{c}_3 = (0.6734, 0.8382, 0.4897), c4=(0.6719,0.2182,0.6080)\mathbf{c}_4 = (0.6719, 0.2182, 0.6080)
L2 weights of the first point: (3.4534,−0.6908,−1.2848,−0.4778)(3.4534, -0.6908, -1.2848, -0.4778)
L4 the four smallest eigenvalues: about 10−1610^{-16}, 0.03590.0359, 0.07010.0701, 0.23610.2361
L5 ρ=(0.2613,0.2364,0.1620,0.4977,0.4233,0.3984)\rho = (0.2613, 0.2364, 0.1620, 0.4977, 0.4233, 0.3984)
L6, N=1N = 1 β1=9.2725\beta_1 = 9.2725
L7 no change: the distance equations already hold
L9, L10 RR and t\mathbf{t} equal the true pose to about 10−1510^{-15}; error 3.5×10−163.5 \times 10^{-16}

Only one eigenvalue is near 0, so the case N=1N = 1 already gives the pose. Now move the image points by up to 0.0020.002: point ii gets (0.002 (−1)i,−0.001 i/3)(0.002\,(-1)^i, -0.001\,i/3), for i=0,…,5i = 0, \ldots, 5. All three cases then end at the same betas after Gauss-Newton, the root mean square reprojection error is 0.00170.0017, the rotation is off by 0.01320.0132 rad, and t=(0.1997,−0.0953,3.9948)\mathbf{t} = (0.1997, -0.0953, 3.9948).

Correctness

On exact data the true camera control points Rcj+tR\mathbf{c}_j + \mathbf{t} satisfy Mx=0M\mathbf{x} = \mathbf{0}, because the weights sum to 1 and so hold in every frame. If the null space of MM has dimension 1, the eigenvector of the eigenvalue 0 is a multiple of the true control points. Rigid motions keep distances, so the formula of the case N=1N = 1 gives exactly the right scale, the sign follows from the positive depths, and the alignment gives the true pose with error 0. Any candidate with error 0 and positive depths has control points in the same null space, which forces it to be the true pose, so line L11 returns it. The full proof is in the proof file of this page. For n=4n = 4 and n=5n = 5 the null space has dimension at least 4 and 2; the cases N=2N = 2 and N=3N = 3 handle such cases in practice but carry no guarantee.

Proof: On exact data with a one-dimensional null space of M, EPnP returns the true posefull

We use the notation of the page. The world points X1,…,Xn\mathbf{X}_1, \ldots, \mathbf{X}_n, n≥4n \ge 4, are not coplanar. The true pose (R,t)(R, \mathbf{t}) puts every point in front of the camera, Zi=(RXi+t)3>0Z_i = (R\mathbf{X}_i + \mathbf{t})_3 > 0, and the data are exact: yi=(ui,vi)\mathbf{y}_i = (u_i, v_i) with ui=(RXi+t)1/Ziu_i = (R\mathbf{X}_i + \mathbf{t})_1/Z_i and vi=(RXi+t)2/Ziv_i = (R\mathbf{X}_i + \mathbf{t})_2/Z_i. The arithmetic is exact (real RAM). We write x∈R12\mathbf{x} \in \mathbb{R}^{12} for a stack of four 3-vectors x1,…,x4\mathbf{x}_1, \ldots, \mathbf{x}_4, and x∗\mathbf{x}^\ast for the true camera control points, xj∗=Rcj+t\mathbf{x}^\ast_j = R\mathbf{c}_j + \mathbf{t}.

Claim. Assume that the null space of MM has dimension 1. Then the candidate of case N=1N = 1 is the true pose, the output has reprojection error 0, and the output is the true pose.

Lemma 1 (control points and weights). The four control points of line L1 are affinely independent, so each point has unique weights with Xi=∑jαijcj\mathbf{X}_i = \sum_j \alpha_{ij}\mathbf{c}_j and ∑jαij=1\sum_j \alpha_{ij} = 1.

Proof. The centered points are not coplanar, so their scatter matrix ∑i(Xi−c1)(Xi−c1)T\sum_i (\mathbf{X}_i - \mathbf{c}_1)(\mathbf{X}_i - \mathbf{c}_1)^{\mathsf T} is positive definite and its three eigenvalues λk\lambda_k are positive. The vectors ck+1−c1=λk/n ek\mathbf{c}_{k+1} - \mathbf{c}_1 = \sqrt{\lambda_k/n}\,\mathbf{e}_k, with orthonormal eigenvectors ek\mathbf{e}_k, are therefore linearly independent. So the 3×33 \times 3 matrix BB with these columns is invertible, and line L2 finds the unique (αi2,αi3,αi4)=B−1(Xi−c1)(\alpha_{i2}, \alpha_{i3}, \alpha_{i4}) = B^{-1}(\mathbf{X}_i - \mathbf{c}_1), with αi1=1−αi2−αi3−αi4\alpha_{i1} = 1 - \alpha_{i2} - \alpha_{i3} - \alpha_{i4}. □\square

Lemma 2 (the weights hold in every frame). For any rotation R′R' and translation t′\mathbf{t}', R′Xi+t′=∑jαij(R′cj+t′)R'\mathbf{X}_i + \mathbf{t}' = \sum_j \alpha_{ij}(R'\mathbf{c}_j + \mathbf{t}').

Proof. ∑jαij(R′cj+t′)=R′∑jαijcj+(∑jαij)t′=R′Xi+t′\sum_j \alpha_{ij}(R'\mathbf{c}_j + \mathbf{t}') = R'\sum_j\alpha_{ij}\mathbf{c}_j + (\sum_j\alpha_{ij})\mathbf{t}' = R'\mathbf{X}_i + \mathbf{t}'. □\square

Lemma 3 (the meaning of Mx=0M\mathbf{x} = \mathbf{0}). For x∈R12\mathbf{x} \in \mathbb{R}^{12} put pi=∑jαijxj\mathbf{p}_i = \sum_j \alpha_{ij}\mathbf{x}_j. Then Mx=0M\mathbf{x} = \mathbf{0} if and only if pi,1=uipi,3p_{i,1} = u_i p_{i,3} and pi,2=vipi,3p_{i,2} = v_i p_{i,3} for every ii. In particular, if a pose (R′,t′)(R', \mathbf{t}') projects every Xi\mathbf{X}_i exactly onto yi\mathbf{y}_i with positive depth, then x′=(R′cj+t′)j\mathbf{x}' = (R'\mathbf{c}_j + \mathbf{t}')_j satisfies Mx′=0M\mathbf{x}' = \mathbf{0}.

Proof. The two rows of point ii in line L3 applied to x\mathbf{x} give ∑jαij(xj,1−uixj,3)=pi,1−uipi,3\sum_j \alpha_{ij}(x_{j,1} - u_i x_{j,3}) = p_{i,1} - u_ip_{i,3} and pi,2−vipi,3p_{i,2} - v_ip_{i,3}. For the second statement, Lemma 2 gives pi=R′Xi+t′\mathbf{p}_i = R'\mathbf{X}_i + \mathbf{t}', whose projection is yi\mathbf{y}_i. □\square

Proof of the claim. By Lemma 3, Mx∗=0M\mathbf{x}^\ast = \mathbf{0}, and x∗≠0\mathbf{x}^\ast \ne \mathbf{0}. By the assumption, the null space of MM, which is also the null space of MTMM^{\mathsf T}M, is span⁡(x∗)\operatorname{span}(\mathbf{x}^\ast). MTMM^{\mathsf T}M is positive semidefinite, so its eigenvalue 0 is the smallest one and is simple, and line L4 gives v1=s x∗/∥x∗∥\mathbf{v}_1 = s\,\mathbf{x}^\ast/\|\mathbf{x}^\ast\| with s=±1s = \pm 1.

Case N=1N = 1, line L6. For a pair p=(a,b)p = (a, b) of control points, dvp=v1[a]−v1[b]=s(Rca−Rcb)/∥x∗∥\mathbf{dv}_p = \mathbf{v}_1^{[a]} - \mathbf{v}_1^{[b]} = s(R\mathbf{c}_a - R\mathbf{c}_b)/\|\mathbf{x}^\ast\|. A rotation keeps lengths, so ∥dvp∥=ρp/∥x∗∥\|\mathbf{dv}_p\| = \sqrt{\rho_p}/\|\mathbf{x}^\ast\|, where ρp=∥ca−cb∥2\rho_p = \|\mathbf{c}_a - \mathbf{c}_b\|^2. The formula of line L6 then gives

β1=∑p∥dvp∥ρp∑p∥dvp∥2=∑pρp/∥x∗∥∑pρp/∥x∗∥2=∥x∗∥.\beta_1 = \frac{\sum_p \|\mathbf{dv}_p\|\sqrt{\rho_p}}{\sum_p \|\mathbf{dv}_p\|^2} = \frac{\sum_p \rho_p/\|\mathbf{x}^\ast\|}{\sum_p \rho_p/\|\mathbf{x}^\ast\|^2} = \|\mathbf{x}^\ast\| .

The sums are positive because the control points are distinct (Lemma 1).

Line L7. At β=(β1,0,0,0)\boldsymbol\beta = (\beta_1, 0, 0, 0) every residual ∥∑kβkdvp,k∥2−ρp=β12∥dvp∥2−ρp\|\sum_k \beta_k\mathbf{dv}_{p,k}\|^2 - \rho_p = \beta_1^2\|\mathbf{dv}_p\|^2 - \rho_p is 0. A Gauss-Newton step solves JTJ δ=−JTrJ^{\mathsf T}J\,\boldsymbol\delta = -J^{\mathsf T}\mathbf{r} with r=0\mathbf{r} = \mathbf{0}, so it is δ=0\boldsymbol\delta = \mathbf{0}; if JTJJ^{\mathsf T}J is singular, the code stops. In both cases β\boldsymbol\beta does not change.

Line L8. The camera control points are β1v1=s x∗\beta_1\mathbf{v}_1 = s\,\mathbf{x}^\ast, so pi=s(RXi+t)\mathbf{p}_i = s(R\mathbf{X}_i + \mathbf{t}) by Lemma 2. All true depths are positive, so the sum of the depths has the sign of ss, and the sign test gives pi=RXi+t\mathbf{p}_i = R\mathbf{X}_i + \mathbf{t} exactly.

Line L9. The pairs (Xi,pi)(\mathbf{X}_i, \mathbf{p}_i) are related exactly by (R,t)(R, \mathbf{t}), and the Xi\mathbf{X}_i are not collinear. The rigid alignment (the Kabsch algorithm) has the unique minimizer (R,t)(R, \mathbf{t}) of ∑i∥R′Xi+t′−pi∥2\sum_i\|R'\mathbf{X}_i + \mathbf{t}' - \mathbf{p}_i\|^2 in that case, because the cost is 0 there and a rigid motion that fixes three non-collinear points is the identity. So the candidate of case N=1N = 1 is (R,t)(R, \mathbf{t}), and its error in line L10 is 0.

Line L11. Errors are nonnegative, so the chosen candidate (R′,t′)(R', \mathbf{t}') has error 0. The error is infinite when a depth is not positive, so (R′,t′)(R', \mathbf{t}') projects every point exactly with positive depth. By Lemma 3 its control points x′\mathbf{x}' satisfy Mx′=0M\mathbf{x}' = \mathbf{0}, so x′=k x∗\mathbf{x}' = k\,\mathbf{x}^\ast for some kk. Rigid motions keep the distance between c1\mathbf{c}_1 and c2\mathbf{c}_2, so ∣k∣=1|k| = 1; the depths of pi′=k(RXi+t)\mathbf{p}_i' = k(R\mathbf{X}_i + \mathbf{t}) are positive, so k=1k = 1. Then R′cj+t′=Rcj+tR'\mathbf{c}_j + \mathbf{t}' = R\mathbf{c}_j + \mathbf{t} for four affinely independent points, which forces R′=RR' = R and t′=t\mathbf{t}' = \mathbf{t}. □\square

Remark (the dimension of the null space). MM has 2n2n rows and 12 columns, so for n=4n = 4 its null space has dimension at least 4, and for n=5n = 5 at least 2. The assumption of the claim can then hold only for n≥6n \ge 6. For n≥6n \ge 6 points in general position it is the usual case, but we do not prove it here; this is a heuristic statement. The cases N=2N = 2 and N=3N = 3 serve the larger null spaces: they solve the distance equations, linearized in the products βkβl\beta_k\beta_l, and Gauss-Newton refines the result. They are not guaranteed to find the true pose. They usually do for n=5n = 5, and this version can fail for n=4n = 4, where the original method also uses the case N=4N = 4.

Remark (floating point). On exact data in floating point, the eigenvalue 0 becomes a value of the order of the rounding error, and the steps above hold up to a relative error that grows with the ratio of the largest eigenvalue of MTMM^{\mathsf T}M to the second smallest one.

Complexity

Lines L1 to L3 and the product MTMM^{\mathsf T}M take Θ(n)\Theta(n) time. Everything after that works on matrices of fixed size: the eigenvectors of a 12×1212 \times 12 matrix, least squares problems with 6 equations, and a few Gauss-Newton steps on 4 unknowns. Lines L8 to L10 take Θ(n)\Theta(n) time for each of the three cases. So the total is Θ(n)\Theta(n) time and Θ(n)\Theta(n) space for the weights and MM. Iterative methods such as Gauss-Newton on the full pose also cost Θ(n)\Theta(n) per step; the gain of EPnP is that it needs no starting pose.

Properties

  • Exact on exact data when the null space of MM is one-dimensional, which is the usual case for n≥6n \ge 6 points in general position.
  • Linear in nn. The number of points enters only in building MTMM^{\mathsf T}M, the weights and the final error.
  • No starting pose. The method is closed form up to a fixed number of Gauss-Newton steps on four unknowns.
  • Not a maximum likelihood estimate. On noisy data it minimizes an algebraic error, not the reprojection error. A short refinement of the pose on the reprojection error improves it.
  • Depends on the control points. The result on noisy data changes a little with the choice of the control points, for example with the signs of the principal directions.

Variants and improvements

  • Planar points. If the points lie in a plane, three control points in that plane are enough, and MM has 9 columns. The page code only covers the general case and rejects planar input.
  • The case N=4N = 4. For four points the null space is at least four-dimensional, and the journal paper solves this case with a relinearization step. The code here leaves it out, so it can fail for n=4n = 4.
  • Outlier rejection. Ferraz, Binefa and Moreno-Noguer (2014) build on the same control point system and reject outliers inside the linear solve, instead of with an outer RANSAC loop.
  • Refinement. Running Gauss-Newton or Levenberg-Marquardt on the reprojection error from the EPnP pose gives the maximum likelihood pose under Gaussian noise in most cases.

When to use it

Use EPnP when there are many correspondences, say 6 or more, and the camera is calibrated: for example to find the pose of a new image in incremental structure from motion, or to refit the pose on all inliers after a RANSAC loop. For the minimal case of three points inside RANSAC, a P3P solver is the usual choice. When the camera is not calibrated, use DLT resectioning instead.

Pitfalls

  • Pixels instead of normalized points. The rows of MM assume K=IK = I. Apply K−1K^{-1} to the pixels first, or put the focal lengths and the principal point into MM.
  • Nearly planar points. When the smallest principal spread is tiny, the weights become large and the system is badly conditioned. Use the planar variant.
  • Few points. With 4 or 5 points the null space is large and the linearized cases can miss the true pose. Check the reprojection error, or use a minimal solver.
  • Wrong sign. The eigenvectors have no fixed sign. Without the depth test in line L8, half the results would place the points behind the camera.
  • Outliers. One wrong match can spoil the linear solve. Run EPnP inside RANSAC, or reject outliers before it.

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()
epnp.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/epnp/. The authors are listed in prov/ATAF9X.jsonl.
"""EPnP: pose of a calibrated camera from n >= 4 point correspondences.

Convention: Xc = R Xw + t, Z forward. The image points are normalized,
y = K^-1 x, so the camera is [R | t] with K = I.

Each world point is written as a weighted sum of four control points,
Xw_i = sum_j alpha_ij c_j with sum_j alpha_ij = 1. The same weights hold in
the camera frame, so the 12 camera coordinates of the control points solve a
homogeneous linear system M x = 0 with 2n rows. The solution is a
combination of the eigenvectors of M^T M with the smallest eigenvalues; the
coefficients beta follow from the distances between the control points.
This file follows Lepetit, Moreno-Noguer and Fua (2009): the cases N = 1, 2
and 3, each refined by Gauss-Newton on four betas, and the pose of least
reprojection error.

This version needs non-coplanar points. Planar points raise ValueError.
Cost: Theta(n) for M^T M and the alphas, plus Theta(1) work on 12 x 12 and
6 x 10 matrices.
"""

from __future__ import annotations

import math
from typing import List, Sequence, Tuple

from cvla import det, inv, matvec, mul, solve, svd, sym_eig, transpose

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

PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]


def control_points(Xw: Sequence[Sequence[float]], planar_tol: float = 1e-10) -> Matrix:
    """The centroid and the centroid plus the three principal directions,
    each scaled by sqrt(eigenvalue / n). Raises ValueError for coplanar or
    collinear points."""
    n = len(Xw)
    c0 = [sum(p[k] for p in Xw) / n for k in range(3)]
    A = [[p[k] - c0[k] for k in range(3)] for p in Xw]
    w, V = sym_eig(mul(transpose(A), A))
    if w[0] <= planar_tol * w[2]:
        raise ValueError("EPnP: the points are coplanar; this version needs 3D points")
    cps = [c0]
    for j in (2, 1, 0):
        s = math.sqrt(w[j] / n)
        cps.append([c0[k] + s * V[k][j] for k in range(3)])
    return cps


def barycentric(Xw: Sequence[Sequence[float]], cps: Matrix) -> Matrix:
    """The weights alpha_i (4 per point) with X_i = sum_j alpha_ij c_j and
    sum_j alpha_ij = 1."""
    B = [[cps[j][k] - cps[0][k] for j in (1, 2, 3)] for k in range(3)]
    Binv = inv(B)
    out = []
    for p in Xw:
        a = matvec(Binv, [p[k] - cps[0][k] for k in range(3)])
        out.append([1.0 - a[0] - a[1] - a[2]] + a)
    return out


def build_M(alphas: Matrix, y: Sequence[Sequence[float]]) -> Matrix:
    """The 2n x 12 matrix M with M x = 0 for the camera control points x."""
    M = []
    for a, (u, v) in zip(alphas, y):
        r1, r2 = [], []
        for j in range(4):
            r1 += [a[j], 0.0, -a[j] * u]
            r2 += [0.0, a[j], -a[j] * v]
        M.append(r1)
        M.append(r2)
    return M


def _diffs(vs: Sequence[Vector]) -> List[List[Vector]]:
    """dv[p][k]: the 3-vector v_k[a] - v_k[b] for the control point pair p."""
    return [[[vk[3 * a + i] - vk[3 * b + i] for i in range(3)] for vk in vs]
            for a, b in PAIRS]


def _dot3(p, q):
    return p[0] * q[0] + p[1] * q[1] + p[2] * q[2]


def _lstsq(A: Matrix, b: Vector) -> Vector:
    """Least squares solution of A x = b by the normal equations."""
    At = transpose(A)
    return solve(mul(At, A), matvec(At, b))


def betas_initial(dv, rho: Vector, N: int) -> Vector:
    """The linearized estimate of the betas for the case N (1, 2 or 3).
    The unused betas are 0."""
    if N == 1:
        num = sum(math.sqrt(_dot3(d[0], d[0])) * math.sqrt(r) for d, r in zip(dv, rho))
        den = sum(_dot3(d[0], d[0]) for d in dv)
        return [num / den, 0.0, 0.0, 0.0]
    # Unknowns b_kl = beta_k beta_l for k <= l < N, in the order 11, 12, 22, 13, 23, 33.
    idx = [(0, 0), (0, 1), (1, 1), (0, 2), (1, 2), (2, 2)][: N * (N + 1) // 2]
    L = [[(1.0 if k == l else 2.0) * _dot3(d[k], d[l]) for k, l in idx] for d in dv]
    b = _lstsq(L, rho)
    beta = [0.0] * 4
    beta[0] = math.sqrt(abs(b[0]))
    beta[1] = math.copysign(math.sqrt(abs(b[2])), b[1])
    if N == 3:
        beta[2] = math.copysign(math.sqrt(abs(b[5])), b[3])
    return beta


def gauss_newton(dv, rho: Vector, beta: Vector, iters: int = 10) -> Vector:
    """Refine the four betas on sum_p (||sum_k beta_k dv[p][k]||^2 - rho_p)^2."""
    beta = list(beta)
    G = [[[_dot3(d[k], d[l]) for l in range(4)] for k in range(4)] for d in dv]
    for _ in range(iters):
        J, r = [], []
        for Gp, rp in zip(G, rho):
            gb = matvec(Gp, beta)
            r.append(_dot3(beta[:3], gb[:3]) + beta[3] * gb[3] - rp)
            J.append([2.0 * x for x in gb])
        try:
            step = solve(mul(transpose(J), J), [-x for x in matvec(transpose(J), r)])
        except ValueError:
            break
        beta = [b + s for b, s in zip(beta, step)]
        if math.sqrt(sum(s * s for s in step)) <= 1e-15 * max(1.0, math.sqrt(sum(b * b for b in beta))):
            break
    return beta


def kabsch(Xw: Sequence[Sequence[float]], Pc: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector]:
    """The rotation R and translation t that minimize sum ||R X_i + t - P_i||^2."""
    n = len(Xw)
    cw = [sum(p[k] for p in Xw) / n for k in range(3)]
    cc = [sum(p[k] for p in Pc) / n for k in range(3)]
    H = [[sum((Pc[i][r] - cc[r]) * (Xw[i][s] - cw[s]) for i in range(n)) for s in range(3)]
         for r in range(3)]
    U, _, V = svd(H)
    Vt = transpose(V)
    if det(mul(U, Vt)) < 0:
        U = [[U[r][0], U[r][1], -U[r][2]] for r in range(3)]
    R = mul(U, Vt)
    t = [cc[k] - matvec(R, cw)[k] for k in range(3)]
    return R, t


def reprojection_error(R, t, Xw, y) -> float:
    """Root mean square image error in normalized units; inf if a point is
    not in front of the camera."""
    s = 0.0
    for p, (u, v) in zip(Xw, y):
        q = [a + b for a, b in zip(matvec(R, p), t)]
        if q[2] <= 0.0:
            return math.inf
        s += (q[0] / q[2] - u) ** 2 + (q[1] / q[2] - v) ** 2
    return math.sqrt(s / len(Xw))


def epnp(Xw: Sequence[Sequence[float]], y: Sequence[Sequence[float]],
         details: bool = False):
    """Pose (R, t) of a calibrated camera from n >= 4 non-coplanar world
    points Xw and their normalized images y. With details=True, also return
    a dict with the intermediate values."""
    n = len(Xw)
    if n < 4 or len(y) != n:
        raise ValueError("EPnP needs n >= 4 points and n image points")
    cps = control_points(Xw)                                         # @line L1
    alphas = barycentric(Xw, cps)                                    # @line L2
    M = build_M(alphas, y)                                           # @line L3
    w, V = sym_eig(mul(transpose(M), M))                             # @line L4
    vs = [[V[r][k] for r in range(12)] for k in range(4)]            # @line L4
    dv = _diffs(vs)                                                  # @line L5
    rho = [sum((cps[a][k] - cps[b][k]) ** 2 for k in range(3)) for a, b in PAIRS]  # @line L5
    best = None
    trials = []
    for N in (1, 2, 3):                                              # @line L6
        beta0 = betas_initial(dv, rho, N)                            # @line L6
        beta = gauss_newton(dv, rho, beta0)                          # @line L7
        x = [sum(beta[k] * vs[k][r] for k in range(4)) for r in range(12)]  # @line L8
        Pc = [[sum(a[j] * x[3 * j + i] for j in range(4)) for i in range(3)]
              for a in alphas]                                       # @line L8
        if sum(p[2] for p in Pc) < 0:                                # @line L8
            Pc = [[-c for c in p] for p in Pc]                       # @line L8
        R, t = kabsch(Xw, Pc)                                        # @line L9
        err = reprojection_error(R, t, Xw, y)                        # @line L10
        trials.append({"N": N, "beta0": beta0, "beta": beta, "error": err})
        if best is None or err < best[2]:                            # @line L11
            best = (R, t, err)                                       # @line L11
    if details:
        return best[0], best[1], {"control_points": cps, "alphas": alphas,
                                  "eigenvalues": w[:4], "rho": rho, "trials": trials}
    return best[0], best[1]                                          # @line L11


def epnp_pixels(Xw, x, K):
    """EPnP with pixel image points x and the intrinsic matrix K."""
    Ki = inv(K)
    y = [matvec(Ki, [p[0], p[1], 1.0]) for p in x]
    return epnp(Xw, [[q[0] / q[2], q[1] / q[2]] for q in y])
test_epnp.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/epnp/. The authors are listed in prov/ATAF9X.jsonl.
"""Tests of EPnP."""

import math
import random

import pytest

from cvgeom import add_noise, make_K, random_rotation, rot_x, rot_y
from cvla import matvec, mul, norm, sub, transpose
from epnp import (barycentric, build_M, control_points, epnp, epnp_pixels,
                  reprojection_error)

R0 = mul(rot_y(0.3), rot_x(0.2))
T0 = [0.2, -0.1, 4.0]
X0 = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0.5], [0.3, 0.7, 1.2]]


def rotation_angle(Ra, Rb):
    return 2.0 * math.asin(min(1.0, norm(sub(Ra, Rb)) / (2.0 * math.sqrt(2.0))))


def project_all(R, t, P):
    out = []
    for p in P:
        q = [a + b for a, b in zip(matvec(R, p), t)]
        out.append([q[0] / q[2], q[1] / q[2]])
    return out


def random_problem(rng, n):
    R = random_rotation(rng)
    t = [rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(4, 8)]
    P = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(n)]
    return R, t, P, project_all(R, t, P)


def test_worked_example():
    y = project_all(R0, T0, X0)
    R, t, info = epnp(X0, y, details=True)
    assert norm(sub(R, R0)) <= 1e-10
    assert norm(sub(t, T0)) <= 1e-10 * norm(T0)
    assert abs(info["eigenvalues"][0]) <= 1e-12
    assert abs(info["eigenvalues"][1] - 0.035921) <= 1e-6
    assert abs(info["trials"][0]["beta0"][0] - 9.27247) <= 1e-5
    rho = [0.2613, 0.2364, 0.1620, 0.4977, 0.4233, 0.3984]
    assert all(abs(a - b) <= 1e-4 for a, b in zip(info["rho"], rho))


def test_worked_example_noisy():
    y = project_all(R0, T0, X0)
    yn = [[p[0] + 0.002 * (-1) ** i, p[1] - 0.001 * i / 3] for i, p in enumerate(y)]
    R, t = epnp(X0, yn)
    assert abs(rotation_angle(R, R0) - 0.013227) <= 1e-5
    assert norm(sub(t, [0.199704, -0.095312, 3.994757])) <= 1e-5
    assert abs(reprojection_error(R, t, X0, yn) - 0.0017014) <= 1e-6


def test_control_points_and_weights():
    rng = random.Random(1)
    P = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(10)]
    cps = control_points(P)
    assert norm(sub(cps[0], [sum(p[k] for p in P) / 10 for k in range(3)])) <= 1e-12
    for p, a in zip(P, barycentric(P, cps)):
        assert abs(sum(a) - 1.0) <= 1e-12
        rec = [sum(a[j] * cps[j][k] for j in range(4)) for k in range(3)]
        assert norm(sub(rec, p)) <= 1e-12


def test_true_control_points_are_in_the_null_space():
    rng = random.Random(2)
    R, t, P, y = random_problem(rng, 8)
    cps = control_points(P)
    x = []
    for c in cps:
        x += [a + b for a, b in zip(matvec(R, c), t)]
    M = build_M(barycentric(P, cps), y)
    assert len(M) == 16 and len(M[0]) == 12
    assert norm(matvec(M, x)) <= 1e-12 * norm(x)


def test_random_exact_scenes():
    rng = random.Random(3)
    for _ in range(25):
        n = rng.choice([6, 9, 20])
        R, t, P, y = random_problem(rng, n)
        Re, te = epnp(P, y)
        assert rotation_angle(Re, R) <= 1e-6
        assert norm(sub(te, t)) <= 1e-6 * norm(t)


def test_five_points():
    rng = random.Random(4)
    for _ in range(10):
        R, t, P, y = random_problem(rng, 5)
        Re, te = epnp(P, y)
        assert rotation_angle(Re, R) <= 1e-6
        assert norm(sub(te, t)) <= 1e-6 * norm(t)


def test_noise():
    rng = random.Random(5)
    for _ in range(5):
        R, t, P, y = random_problem(rng, 40)
        yn = add_noise(rng, y, 1.0 / 800.0)
        Re, te = epnp(P, yn)
        assert rotation_angle(Re, R) <= 0.02
        assert norm(sub(te, t)) <= 0.05 * norm(t)
        assert reprojection_error(Re, te, P, yn) <= 3.0 / 800.0


def test_pixels():
    rng = random.Random(6)
    K = make_K(800, 780, 320, 240, 0.5)
    R, t, P, y = random_problem(rng, 10)
    x = [matvec(K, [u, v, 1.0])[:2] for u, v in y]
    Re, te = epnp_pixels(P, x, K)
    assert rotation_angle(Re, R) <= 1e-6
    assert norm(sub(te, t)) <= 1e-6 * norm(t)


def test_change_of_world_frame():
    rng = random.Random(7)
    R, t, P, y = random_problem(rng, 10)
    yn = add_noise(rng, y, 0.002)
    Ra, ta = epnp(P, yn)
    I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    T = [rng.uniform(-5, 5) for _ in range(3)]
    # A translation of the world moves the centroid only: the same pose.
    # A rotation can flip the signs of the principal directions, which
    # changes the control points, so on noisy data the pose moves a little.
    for Q, tol in ((I3, 1e-8), (random_rotation(rng), 0.01)):
        P2 = [[a + b for a, b in zip(matvec(Q, p), T)] for p in P]
        Rb, tb = epnp(P2, yn)
        # The same camera in the new frame: R' = R Q^T, t' = t - R Q^T T.
        Rexp = mul(Ra, transpose(Q))
        texp = [a - b for a, b in zip(ta, matvec(Rexp, T))]
        assert rotation_angle(Rb, Rexp) <= tol
        assert norm(sub(tb, texp)) <= tol * norm(texp)


def test_selected_pose_has_least_error():
    rng = random.Random(8)
    R, t, P, y = random_problem(rng, 12)
    yn = add_noise(rng, y, 0.003)
    Re, te, info = epnp(P, yn, details=True)
    err = reprojection_error(Re, te, P, yn)
    assert err == min(tr["error"] for tr in info["trials"])


def test_bad_input():
    with pytest.raises(ValueError):
        epnp([[0, 0, 0], [1, 0, 0], [0, 1, 0]], [[0, 0], [0.1, 0], [0, 0.1]])
    rng = random.Random(9)
    planar = [[rng.uniform(-1, 1), rng.uniform(-1, 1), 0.0] for _ in range(8)]
    y = project_all(R0, T0, planar)
    with pytest.raises(ValueError):
        epnp(planar, y)

History

Moreno-Noguer, Lepetit and Fua presented the control point formulation at ICCV 2007 as an accurate non-iterative O(n)O(n) solution of PnP. The journal version by Lepetit, Moreno-Noguer and Fua (2009) gave the method its name, described the cases N=1N = 1 to 44, the planar case and a Gauss-Newton refinement of the betas, and compared it with iterative and other non-iterative methods. Later work, such as that of Ferraz, Binefa and Moreno-Noguer (2014), kept the control point idea and added outlier rejection.

References

  1. Vincent Lepetit, Francesc Moreno-Noguer and Pascal Fua, EPnP: An Accurate O(n) Solution to the PnP Problem, International Journal of Computer Vision 81(2), 2009, 155-166, the control points, the cases N = 1 to 4, the Gauss-Newton refinement and the planar case
  2. Francesc Moreno-Noguer, Vincent Lepetit and Pascal Fua, Accurate Non-Iterative O(n) Solution to the PnP Problem, IEEE International Conference on Computer Vision (ICCV), 2007, the first version of the method
  3. Luis Ferraz, Xavier Binefa and Francesc Moreno-Noguer, Very Fast Solution to the PnP Problem with Algebraic Outlier Rejection, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2014, a later variant that builds on the control point formulation
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 11.2, Pose estimation

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