Algorithm Search⌘K

Algorithmintro

Midpoint triangulation

Also called ray midpoint triangulation.

Take the midpoint of the shortest segment between the two back-projected rays; simple and fast, but not affine or projective invariant.

Time
Θ(1) worst · average · best
Space
Θ(1) extra
Where
N = the number of rays in the N-view variant
Properties
deterministicexactofflineiterative
Origin
Richard Hartley, Peter Sturm, 1997

Midpoint triangulation finds a 3D point from two calibrated views. Each image point defines a ray in space, from the camera center through the point on the image plane. With exact data the two rays meet at the point. With noisy data they usually miss each other, and the method takes the shortest segment between them and returns its middle. The two ends of the segment follow from a 2×22 \times 2 linear system, so the cost is a fixed small number of operations. The method needs a Euclidean frame: it uses lengths and right angles, so it works with calibrated cameras in a metric reconstruction, not in a projective one. It is the simplest triangulation method, and it extends at once to many rays and to generalized cameras.

In plain words

A photo of a point tells you a line in space on which the point lies: the line from the camera through the dot in the photo. Two photos give two lines. If the dots were perfect, the lines would cross at the point. Real dots are a little off, so the lines pass near each other without touching. Find the two places where they come closest, one on each line, and take the spot halfway between them. That spot is the answer. It is easy to compute and easy to picture, but it measures errors in space and not in the photos, so it is not the most accurate choice.

The problem

Input. Two rays C1+λ1d1\mathbf{C}_1 + \lambda_1\mathbf{d}_1 and C2+λ2d2\mathbf{C}_2 + \lambda_2\mathbf{d}_2 in a Euclidean frame. For a camera with Xc=RXw+t\mathbf{X}_c = R\mathbf{X}_w + \mathbf{t} and a normalized image point y=K−1x=(u,v,1)\mathbf{y} = K^{-1}\mathbf{x} = (u, v, 1), the ray has the center C=−RTt\mathbf{C} = -R^{\mathsf T}\mathbf{t} and the direction d=RTy\mathbf{d} = R^{\mathsf T}\mathbf{y}.

Output. The point M\mathbf{M} that minimizes the sum of the squared distances to the two lines, and the parameters λ1\lambda_1, λ2\lambda_2 of the closest points. With d=RTy\mathbf{d} = R^{\mathsf T}\mathbf{y}, the parameter λi\lambda_i is the depth of the closest point in camera ii.

The algorithm

The closest points Q1=C1+λ1d1\mathbf{Q}_1 = \mathbf{C}_1 + \lambda_1\mathbf{d}_1 and Q2=C2+λ2d2\mathbf{Q}_2 = \mathbf{C}_2 + \lambda_2\mathbf{d}_2 are the ones for which Q1−Q2\mathbf{Q}_1 - \mathbf{Q}_2 is perpendicular to both directions. These two conditions are a 2×22 \times 2 linear system in λ1\lambda_1, λ2\lambda_2.

  1. MIDPOINT-TRIANGULATION(C_1, d_1, C_2, d_2)
  2. 1w <- C_1 - C_2
  3. 2a <- d_1.d_1; b <- d_1.d_2; c <- d_2.d_2; d <- d_1.w; e <- d_2.w
  4. 3D <- a c - b^2; if D <= eps a c then report parallel rays
  5. 4l_1 <- (b e - c d) / D; l_2 <- (a e - b d) / D
  6. 5Q_1 <- C_1 + l_1 d_1; Q_2 <- C_2 + l_2 d_2
  7. 6return (Q_1 + Q_2) / 2, l_1, l_2

The N-view variant returns the point with the least sum of squared distances to NN lines. With unit directions ui\mathbf{u}_i it solves the 3×33 \times 3 system ∑i(I−uiuiT) X=∑i(I−uiuiT) Ci\sum_i (I - \mathbf{u}_i\mathbf{u}_i^{\mathsf T})\,\mathbf{X} = \sum_i (I - \mathbf{u}_i\mathbf{u}_i^{\mathsf T})\,\mathbf{C}_i. For two rays this is the same point. The code on this page has both forms.

Example

Take two cameras with R=IR = I, the first at (0,0,0)(0, 0, 0) and the second at (1,0,0)(1, 0, 0), so t2=(−1,0,0)\mathbf{t}_2 = (-1, 0, 0). The point (1,2,4)(1, 2, 4) has the normalized images (0.25,0.5)(0.25, 0.5) and (0,0.5)(0, 0.5). Move the second image point to (0,0.52)(0, 0.52), so that the rays no longer meet.

line exact data noisy data
L1 w=(−1,0,0)\mathbf{w} = (-1, 0, 0) w=(−1,0,0)\mathbf{w} = (-1, 0, 0)
L2 a=1.3125a = 1.3125, b=1.25b = 1.25, c=1.25c = 1.25, d=−0.25d = -0.25, e=0e = 0 a=1.3125a = 1.3125, b=1.26b = 1.26, c=1.2704c = 1.2704, d=−0.25d = -0.25, e=0e = 0
L3 D=0.078125D = 0.078125 D=0.0798D = 0.0798
L4 λ1=4\lambda_1 = 4, λ2=4\lambda_2 = 4 λ1=3.9799\lambda_1 = 3.9799, λ2=3.9474\lambda_2 = 3.9474
L5 Q1=Q2=(1,2,4)\mathbf{Q}_1 = \mathbf{Q}_2 = (1, 2, 4) Q1=(0.9950,1.9900,3.9799)\mathbf{Q}_1 = (0.9950, 1.9900, 3.9799), Q2=(1,2.0526,3.9474)\mathbf{Q}_2 = (1, 2.0526, 3.9474)
L6 (1,2,4)(1, 2, 4) (0.9975,2.0213,3.9637)(0.9975, 2.0213, 3.9637)

On the noisy data the gap between the rays is 0.07080.0708. The output projects to (0.2517,0.5100)(0.2517, 0.5100) in the first view and (−0.0006,0.5100)(-0.0006, 0.5100) in the second. On the same data linear triangulation gives (0.9999,2.0393,3.9983)(0.9999, 2.0393, 3.9983), a different point.

Correctness

The squared distance ∥w+λ1d1−λ2d2∥2\|\mathbf{w} + \lambda_1\mathbf{d}_1 - \lambda_2\mathbf{d}_2\|^2 between two points of the lines is a quadratic function of (λ1,λ2)(\lambda_1, \lambda_2) whose Hessian has determinant 4D4D. By the Cauchy-Schwarz inequality D>0D > 0 unless the directions are parallel, so the function has one minimizer, where its gradient is zero. The gradient condition says that Q1−Q2\mathbf{Q}_1 - \mathbf{Q}_2 is perpendicular to d1\mathbf{d}_1 and d2\mathbf{d}_2, and Cramer's rule gives line L4. If a point has distances r1r_1, r2r_2 to the lines, the triangle inequality gives r1+r2≥∥Q1−Q2∥r_1 + r_2 \ge \|\mathbf{Q}_1 - \mathbf{Q}_2\|, so r12+r22≥∥Q1−Q2∥2/2r_1^2 + r_2^2 \ge \|\mathbf{Q}_1 - \mathbf{Q}_2\|^2/2, with equality only at the midpoint. When the rays meet, the gap is zero and the output is the meeting point. The full proof is in the proof file of this page.

Proof: The midpoint of the common perpendicular is the unique point closest to two skew rays, and it is the true point on exact datafull

We use the notation of the page. The two rays are the lines L1={C1+λ1d1}L_1 = \{\mathbf{C}_1 + \lambda_1\mathbf{d}_1\} and L2={C2+λ2d2}L_2 = \{\mathbf{C}_2 + \lambda_2\mathbf{d}_2\} in R3\mathbb{R}^3, with d1,d2≠0\mathbf{d}_1, \mathbf{d}_2 \ne \mathbf{0}. Put w=C1−C2\mathbf{w} = \mathbf{C}_1 - \mathbf{C}_2, a=d1⋅d1a = \mathbf{d}_1\cdot\mathbf{d}_1, b=d1⋅d2b = \mathbf{d}_1\cdot\mathbf{d}_2, c=d2⋅d2c = \mathbf{d}_2\cdot\mathbf{d}_2, d=d1⋅wd = \mathbf{d}_1\cdot\mathbf{w}, e=d2⋅we = \mathbf{d}_2\cdot\mathbf{w} and D=ac−b2D = ac - b^2. The arithmetic is exact (real RAM).

Claim. Assume that d1\mathbf{d}_1 and d2\mathbf{d}_2 are not parallel. Then (a) D>0D > 0, so line L3 does not stop; (b) the values λ1\lambda_1, λ2\lambda_2 of line L4 give the unique pair of points Q1∈L1\mathbf{Q}_1 \in L_1, Q2∈L2\mathbf{Q}_2 \in L_2 at least distance, and Q1−Q2\mathbf{Q}_1 - \mathbf{Q}_2 is perpendicular to both directions; (c) the output M=(Q1+Q2)/2\mathbf{M} = (\mathbf{Q}_1 + \mathbf{Q}_2)/2 is the unique minimizer of g(X)=dist⁡(X,L1)2+dist⁡(X,L2)2g(\mathbf{X}) = \operatorname{dist}(\mathbf{X}, L_1)^2 + \operatorname{dist}(\mathbf{X}, L_2)^2; (d) if the two lines meet at a point X\mathbf{X}, the output is X\mathbf{X}; (e) if the rays come from calibrated cameras, di=RiT(ui,vi,1)T\mathbf{d}_i = R_i^{\mathsf T}(u_i, v_i, 1)^{\mathsf T} and Ci=−RiTti\mathbf{C}_i = -R_i^{\mathsf T}\mathbf{t}_i, then λi\lambda_i is the depth of Qi\mathbf{Q}_i in camera ii.

Proof of part (a). By the Cauchy-Schwarz inequality b2≤acb^2 \le ac, with equality only if d1\mathbf{d}_1 and d2\mathbf{d}_2 are parallel. So D>0D > 0. □\square

Proof of part (b). The squared distance between the points with parameters λ1\lambda_1 and λ2\lambda_2 is

f(λ1,λ2)=∥w+λ1d1−λ2d2∥2.f(\lambda_1, \lambda_2) = \|\mathbf{w} + \lambda_1\mathbf{d}_1 - \lambda_2\mathbf{d}_2\|^2 .

This is a quadratic function with Hessian 2(a−b−bc)2\begin{pmatrix} a & -b \\ -b & c\end{pmatrix}, whose determinant is 4D>04D > 0 and whose first entry is 2a>02a > 0. So the Hessian is positive definite, ff is strictly convex, and its unique minimizer is the unique zero of its gradient. Half the gradient is

(d1⋅g,  −d2⋅g),g=w+λ1d1−λ2d2=Q1−Q2.\left(\mathbf{d}_1\cdot\mathbf{g},\; -\mathbf{d}_2\cdot\mathbf{g}\right), \qquad \mathbf{g} = \mathbf{w} + \lambda_1\mathbf{d}_1 - \lambda_2\mathbf{d}_2 = \mathbf{Q}_1 - \mathbf{Q}_2 .

So at the minimizer g\mathbf{g} is perpendicular to d1\mathbf{d}_1 and d2\mathbf{d}_2. Written out, the two conditions are aλ1−bλ2=−da\lambda_1 - b\lambda_2 = -d and bλ1−cλ2=−eb\lambda_1 - c\lambda_2 = -e. Cramer's rule, with the determinant −D-D of this system, gives

λ1=(−d)(−c)−(−b)(−e)−D=be−cdD,λ2=a(−e)−b(−d)−D=ae−bdD,\lambda_1 = \frac{(-d)(-c) - (-b)(-e)}{-D} = \frac{be - cd}{D}, \qquad \lambda_2 = \frac{a(-e) - b(-d)}{-D} = \frac{ae - bd}{D},

which are the values of line L4. □\square

Proof of part (c). Put δ=∥Q1−Q2∥\delta = \|\mathbf{Q}_1 - \mathbf{Q}_2\|, the least distance between the lines. Take any X\mathbf{X}, and let P1\mathbf{P}_1, P2\mathbf{P}_2 be its nearest points on L1L_1, L2L_2, at distances r1r_1, r2r_2. By the triangle inequality and part (b),

r1+r2≥∥P1−P2∥≥δ.r_1 + r_2 \ge \|\mathbf{P}_1 - \mathbf{P}_2\| \ge \delta .

Then g(X)=r12+r22≥(r1+r2)2/2≥δ2/2g(\mathbf{X}) = r_1^2 + r_2^2 \ge (r_1 + r_2)^2/2 \ge \delta^2/2. The midpoint M\mathbf{M} reaches this bound: the vector M−Q1=(Q2−Q1)/2\mathbf{M} - \mathbf{Q}_1 = (\mathbf{Q}_2 - \mathbf{Q}_1)/2 is perpendicular to d1\mathbf{d}_1, so the nearest point of L1L_1 to M\mathbf{M} is Q1\mathbf{Q}_1 and r1=δ/2r_1 = \delta/2; in the same way r2=δ/2r_2 = \delta/2, and g(M)=δ2/2g(\mathbf{M}) = \delta^2/2. For uniqueness, let g(X)=δ2/2g(\mathbf{X}) = \delta^2/2. Then all the inequalities are equalities: r1=r2r_1 = r_2, r1+r2=δr_1 + r_2 = \delta, and ∥P1−P2∥=δ\|\mathbf{P}_1 - \mathbf{P}_2\| = \delta. By part (b) the pair at distance δ\delta is unique, so P1=Q1\mathbf{P}_1 = \mathbf{Q}_1 and P2=Q2\mathbf{P}_2 = \mathbf{Q}_2. Equality in the triangle inequality puts X\mathbf{X} on the segment from Q1\mathbf{Q}_1 to Q2\mathbf{Q}_2, and r1=r2r_1 = r_2 makes it the midpoint. If δ=0\delta = 0 the bound gives X∈L1∩L2\mathbf{X} \in L_1 \cap L_2, which is the single point Q1=Q2=M\mathbf{Q}_1 = \mathbf{Q}_2 = \mathbf{M}. □\square

Proof of part (d). If X=C1+μ1d1=C2+μ2d2\mathbf{X} = \mathbf{C}_1 + \mu_1\mathbf{d}_1 = \mathbf{C}_2 + \mu_2\mathbf{d}_2, then f(μ1,μ2)=0f(\mu_1, \mu_2) = 0, which is the least possible value. By the uniqueness in part (b), (λ1,λ2)=(μ1,μ2)(\lambda_1, \lambda_2) = (\mu_1, \mu_2), so Q1=Q2=X\mathbf{Q}_1 = \mathbf{Q}_2 = \mathbf{X} and the output is X\mathbf{X}. Two lines that are not parallel meet in at most one point, so this is the only point on both rays. □\square

Proof of part (e). The point Qi=Ci+λidi\mathbf{Q}_i = \mathbf{C}_i + \lambda_i\mathbf{d}_i has the camera coordinates

RiQi+ti=(RiCi+ti)+λiRidi=0+λi(ui,vi,1)T,R_i\mathbf{Q}_i + \mathbf{t}_i = (R_i\mathbf{C}_i + \mathbf{t}_i) + \lambda_i R_i\mathbf{d}_i = \mathbf{0} + \lambda_i(u_i, v_i, 1)^{\mathsf T},

because RiRiT=IR_iR_i^{\mathsf T} = I. Its third coordinate, the depth, is λi\lambda_i. □\square

Remark (similarity invariance). Let T(X)=sQX+TT(\mathbf{X}) = sQ\mathbf{X} + \mathbf{T} with QQ a rotation and s>0s > 0. The new rays have the centers T(Ci)T(\mathbf{C}_i) and the directions QdiQ\mathbf{d}_i. Then aa, bb, cc do not change, w\mathbf{w} becomes sQwsQ\mathbf{w}, and dd, ee are multiplied by ss. So λ1\lambda_1, λ2\lambda_2 are multiplied by ss, the new Qi\mathbf{Q}_i is T(Qi)T(\mathbf{Q}_i), and the new output is T(M)T(\mathbf{M}). A general affine map does not keep right angles, so the common perpendicular of the new lines is in general not the image of the old one. For example, the shear (x,y,z)↦(x,y+2z,z)(x, y, z) \mapsto (x, y + 2z, z) moves the output of the noisy example of the page away from the image of the old output. On exact data part (d) holds in every frame, so the output is invariant under all affine maps there.

Remark (scale of the directions). Multiplying di\mathbf{d}_i by a nonzero number kk divides λi\lambda_i by kk and leaves the points Qi\mathbf{Q}_i unchanged, so the output does not depend on the length or sign of the directions.

Remark (floating point). The test D≤ε acD \le \varepsilon\,ac in line L3 rejects pairs whose angle θ\theta has sin⁡2θ≤ε\sin^2\theta \le \varepsilon, because D=acsin⁡2θD = ac\sin^2\theta. For nearly parallel rays the formulas of line L4 lose accuracy in proportion to 1/sin⁡2θ1/\sin^2\theta; this is a property of the problem, whose answer moves far when the rays turn a little.

Complexity

Two rays need a fixed number of dot products and one division by DD: Θ(1)\Theta(1) time and space. The N-view variant forms a 3×33 \times 3 sum in Θ(N)\Theta(N) time and solves it in Θ(1)\Theta(1).

Properties

  • Exact on exact data. If the rays meet at one point, the output is that point.
  • Depths for free. The parameters λ1\lambda_1, λ2\lambda_2 are the depths of the closest points; a negative value shows a point behind the camera.
  • Similarity invariant. Rotating, moving or scaling the world frame moves the output in the same way.
  • Not affine or projective invariant. An affine change of the frame does not keep right angles, so the common perpendicular, and with it the output, changes. On exact data the output is the meeting point in every frame.
  • Error in space. The quantity it minimizes is a distance in 3D, not the reprojection error. A far point has a large gap for a small image error, and a near point a small one.

Variants and improvements

  • N rays. The least squares point of NN lines, as above, works for any number of views and for rays from a generalized camera.
  • Weighted midpoint. Lee and Civera (2019) move the output along the segment in proportion to the depths of the two ends, instead of taking the middle. This brings the result closer to the optimum in the images, at the same cost.
  • Cheirality check. Reject the point if λ1≤0\lambda_1 \le 0 or λ2≤0\lambda_2 \le 0. This test is part of choosing the right pose in essential matrix decomposition.
  • Refinement. A few Gauss-Newton steps on the reprojection error, starting from the midpoint, give the maximum likelihood estimate in most cases.

When to use it

Use it when the cameras are calibrated and the frame is metric, and a quick first estimate is enough: for the cheirality test of relative pose, for new points in incremental structure from motion that bundle adjustment will refine, and for systems of many rays. In a projective reconstruction use linear triangulation instead. For the best two-view estimate under Gaussian image noise use optimal triangulation.

Pitfalls

  • Pixels as directions. The direction must be RTK−1x~R^{\mathsf T}K^{-1}\tilde{\mathbf{x}}. Using pixel coordinates without K−1K^{-1} gives wrong rays.
  • Parallel rays. For a far point or a small baseline, DD is close to 0 and the depths are poorly fixed. Reject such points, or keep only the direction.
  • Points behind a camera. The lines extend in both directions, so the output can lie behind a camera. Check the signs of λ1\lambda_1 and λ2\lambda_2.
  • Projective frames. In a frame that is only projective, distances and right angles have no meaning, and the output depends on the arbitrary choice of frame.

Implementations

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

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

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

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

from __future__ import annotations

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

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

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


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


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


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


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


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

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


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


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


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


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


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


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


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


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


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

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

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

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


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


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


if __name__ == "__main__":
    self_test()
cvla.py 494 lines
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

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

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

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

from __future__ import annotations

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

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

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


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

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


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


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


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


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


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


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


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


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


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


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


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


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


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

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

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


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


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


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


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

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


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


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


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

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


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


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

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


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


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


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

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


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


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

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


if __name__ == "__main__":
    self_test()
midpoint_triangulation.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/midpoint-triangulation/. The authors are listed in prov/NVV9NG.jsonl.
"""Midpoint triangulation of a point from two rays.

A ray is a center C and a direction d (any length). The method finds the
points C1 + l1 d1 and C2 + l2 d2 that are closest to each other and returns
the midpoint of the segment between them. With calibrated cameras,
Xc = R Xw + t, the ray of the normalized image point y = (u, v) has
C = -R^T t and d = R^T (u, v, 1); then l is the depth of the point on the
ray in that camera.

The N-view variant returns the point with the least sum of squared
distances to N rays. For two rays it is the same point.

Cost: Theta(1) for two rays, Theta(N) for N rays.
"""

from __future__ import annotations

from typing import List, Sequence, Tuple

from cvla import dot, matvec, norm, solve, transpose

Vector = List[float]


def camera_ray(R: Sequence[Sequence[float]], t: Sequence[float],
               y: Sequence[float]) -> Tuple[Vector, Vector]:
    """The ray (C, d) of the normalized image point y in the camera (R, t)."""
    Rt = transpose(R)
    C = [-c for c in matvec(Rt, t)]
    d = matvec(Rt, [float(y[0]), float(y[1]), 1.0])
    return C, d


def midpoint(C1: Sequence[float], d1: Sequence[float], C2: Sequence[float],
             d2: Sequence[float], eps: float = 1e-12) -> Tuple[Vector, float, float]:
    """The midpoint of the common perpendicular of two rays, and the ray
    parameters l1, l2 of its two ends. Raises ValueError if the rays are
    parallel (sin^2 of their angle below eps)."""
    w = [p - q for p, q in zip(C1, C2)]                              # @line L1
    a, b, c = dot(d1, d1), dot(d1, d2), dot(d2, d2)                  # @line L2
    d, e = dot(d1, w), dot(d2, w)                                    # @line L2
    D = a * c - b * b                                                # @line L3
    if D <= eps * a * c:                                             # @line L3
        raise ValueError("midpoint triangulation: the rays are parallel")
    l1 = (b * e - c * d) / D                                         # @line L4
    l2 = (a * e - b * d) / D                                         # @line L4
    Q1 = [p + l1 * q for p, q in zip(C1, d1)]                        # @line L5
    Q2 = [p + l2 * q for p, q in zip(C2, d2)]                        # @line L5
    return [(p + q) / 2.0 for p, q in zip(Q1, Q2)], l1, l2           # @line L6


def midpoint_triangulation(R1, t1, y1, R2, t2, y2) -> Vector:
    """The midpoint of the rays of y1 in (R1, t1) and y2 in (R2, t2)."""
    C1, d1 = camera_ray(R1, t1, y1)
    C2, d2 = camera_ray(R2, t2, y2)
    return midpoint(C1, d1, C2, d2)[0]


def nearest_point_to_rays(Cs: Sequence[Sequence[float]],
                          ds: Sequence[Sequence[float]]) -> Vector:
    """The point with the least sum of squared distances to the lines
    (C_i, d_i): X = (sum (I - u u^T))^-1 sum (I - u u^T) C_i with u the
    unit direction. Raises ValueError if all lines are parallel."""
    S = [[0.0] * 3 for _ in range(3)]
    r = [0.0] * 3
    for C, d in zip(Cs, ds):
        n = norm(d)
        u = [x / n for x in d]
        for i in range(3):
            for j in range(3):
                m = (1.0 if i == j else 0.0) - u[i] * u[j]
                S[i][j] += m
                r[i] += m * C[j]
    return solve(S, r)
test_midpoint_triangulation.py 191 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/midpoint-triangulation/. The authors are listed in prov/NVV9NG.jsonl.
"""Tests of midpoint triangulation."""

import math
import random

import pytest

from cvgeom import add_noise, make_K, random_rotation, random_scene, rot_y
from cvla import cross, dot, inv, matvec, norm, sub
from midpoint_triangulation import (camera_ray, midpoint,
                                    midpoint_triangulation,
                                    nearest_point_to_rays)

I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]


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


def line_dist2(X, C, d):
    v = sub(X, C)
    c = cross(v, d)
    return dot(c, c) / dot(d, d)


def random_rays(rng):
    C1 = [rng.uniform(-1, 1) for _ in range(3)]
    C2 = [rng.uniform(-1, 1) for _ in range(3)]
    d1 = [rng.gauss(0, 1) for _ in range(3)]
    d2 = [rng.gauss(0, 1) for _ in range(3)]
    return C1, d1, C2, d2


def test_worked_example_exact():
    X = midpoint_triangulation(I3, [0, 0, 0], [0.25, 0.5], I3, [-1, 0, 0], [0.0, 0.5])
    assert rel(X, [1.0, 2.0, 4.0]) <= 1e-12
    C1, d1 = camera_ray(I3, [0, 0, 0], [0.25, 0.5])
    C2, d2 = camera_ray(I3, [-1, 0, 0], [0.0, 0.5])
    assert C2 == [1.0, 0.0, 0.0]
    _, l1, l2 = midpoint(C1, d1, C2, d2)
    assert abs(l1 - 4.0) <= 1e-12 and abs(l2 - 4.0) <= 1e-12


def test_worked_example_noisy():
    C1, d1 = camera_ray(I3, [0, 0, 0], [0.25, 0.5])
    C2, d2 = camera_ray(I3, [-1, 0, 0], [0.0, 0.52])
    X, l1, l2 = midpoint(C1, d1, C2, d2)
    assert rel(X, [0.997494, 2.021303, 3.963659]) <= 1e-6
    assert abs(l1 - 3.979950) <= 1e-6 and abs(l2 - 3.947368) <= 1e-6
    Q1 = [p + l1 * q for p, q in zip(C1, d1)]
    Q2 = [p + l2 * q for p, q in zip(C2, d2)]
    assert abs(norm(sub(Q1, Q2)) - 0.070799) <= 1e-6


def test_gap_is_perpendicular_to_both_rays():
    rng = random.Random(1)
    for _ in range(50):
        C1, d1, C2, d2 = random_rays(rng)
        _, l1, l2 = midpoint(C1, d1, C2, d2)
        g = sub([p + l1 * q for p, q in zip(C1, d1)],
                [p + l2 * q for p, q in zip(C2, d2)])
        scale = max(1.0, norm(g)) * norm(d1) * norm(d2)
        assert abs(dot(g, d1)) <= 1e-10 * scale
        assert abs(dot(g, d2)) <= 1e-10 * scale


def test_exact_recovery_and_depths():
    rng = random.Random(2)
    for _ in range(5):
        sc = random_scene(rng, n=10, n_cams=2, max_angle=0.4)
        Kinv = inv(sc["K"][0])
        (R1, R2), (t1, t2) = sc["R"], sc["t"]
        for j, X in enumerate(sc["X"]):
            y1 = matvec(Kinv, sc["x"][0][j] + [1.0])[:2]
            y2 = matvec(Kinv, sc["x"][1][j] + [1.0])[:2]
            C1, d1 = camera_ray(R1, t1, y1)
            C2, d2 = camera_ray(R2, t2, y2)
            Y, l1, l2 = midpoint(C1, d1, C2, d2)
            assert rel(Y, X) <= 1e-8
            z1 = matvec(R1, X)[2] + t1[2]
            z2 = matvec(R2, X)[2] + t2[2]
            assert abs(l1 - z1) <= 1e-8 * z1 and abs(l2 - z2) <= 1e-8 * z2


def test_direction_length_does_not_matter():
    rng = random.Random(3)
    for _ in range(20):
        C1, d1, C2, d2 = random_rays(rng)
        X = midpoint(C1, d1, C2, d2)[0]
        s1, s2 = rng.uniform(0.1, 10), rng.uniform(-10, -0.1)
        Y = midpoint(C1, [s1 * v for v in d1], C2, [s2 * v for v in d2])[0]
        assert rel(Y, X) <= 1e-10


def test_similarity_invariance():
    rng = random.Random(4)
    for _ in range(20):
        C1, d1, C2, d2 = random_rays(rng)
        X = midpoint(C1, d1, C2, d2)[0]
        Q = random_rotation(rng)
        s = rng.uniform(0.2, 5.0)
        T = [rng.uniform(-3, 3) for _ in range(3)]

        def point(p):
            return [s * a + b for a, b in zip(matvec(Q, p), T)]

        Y = midpoint(point(C1), matvec(Q, d1), point(C2), matvec(Q, d2))[0]
        assert rel(Y, point(X)) <= 1e-9


def test_not_affine_invariant():
    C1, d1 = camera_ray(I3, [0, 0, 0], [0.25, 0.5])
    C2, d2 = camera_ray(I3, [-1, 0, 0], [0.0, 0.52])
    X = midpoint(C1, d1, C2, d2)[0]
    A = [[1.0, 0.0, 0.0], [0.0, 1.0, 2.0], [0.0, 0.0, 1.0]]
    Y = midpoint(matvec(A, C1), matvec(A, d1), matvec(A, C2), matvec(A, d2))[0]
    assert norm(sub(Y, matvec(A, X))) > 1e-3
    # On exact data the rays meet, and every affine map keeps the meeting point.
    C2e, d2e = camera_ray(I3, [-1, 0, 0], [0.0, 0.5])
    X = midpoint(C1, d1, C2e, d2e)[0]
    Y = midpoint(matvec(A, C1), matvec(A, d1), matvec(A, C2e), matvec(A, d2e))[0]
    assert rel(Y, matvec(A, X)) <= 1e-12


def test_two_rays_least_squares_point_is_the_midpoint():
    rng = random.Random(5)
    for _ in range(30):
        C1, d1, C2, d2 = random_rays(rng)
        X = midpoint(C1, d1, C2, d2)[0]
        Y = nearest_point_to_rays([C1, C2], [d1, d2])
        assert rel(Y, X) <= 1e-8


def test_midpoint_minimizes_sum_of_squared_distances():
    rng = random.Random(6)
    for _ in range(10):
        C1, d1, C2, d2 = random_rays(rng)
        X = midpoint(C1, d1, C2, d2)[0]
        f0 = line_dist2(X, C1, d1) + line_dist2(X, C2, d2)
        for _ in range(20):
            Z = [x + rng.gauss(0, 0.05) for x in X]
            assert line_dist2(Z, C1, d1) + line_dist2(Z, C2, d2) >= f0 - 1e-12


def test_n_views_exact_and_noisy():
    rng = random.Random(7)
    sc = random_scene(rng, n=8, n_cams=5, max_angle=0.5)
    Kinv = inv(sc["K"][0])
    for j, X in enumerate(sc["X"]):
        Cs, ds = [], []
        for i in range(5):
            y = matvec(Kinv, sc["x"][i][j] + [1.0])[:2]
            C, d = camera_ray(sc["R"][i], sc["t"][i], y)
            Cs.append(C)
            ds.append(d)
        assert rel(nearest_point_to_rays(Cs, ds), X) <= 1e-8


def test_noise_gives_a_small_error():
    rng = random.Random(8)
    # Two cameras 5 units from the origin, 0.6 rad apart: a good baseline.
    R2 = rot_y(-0.6)
    t2 = [-v for v in matvec(R2, [5.0 * math.sin(0.6), 0.0, -5.0 * math.cos(0.6)])]
    K = make_K(800, 800, 320, 240)
    sc = random_scene(rng, n=20, cams=[(K, I3, [0.0, 0.0, 5.0]), (K, R2, t2)])
    Kinv = inv(K)
    xs = [add_noise(rng, sc["x"][i], 0.5) for i in range(2)]
    for j, X in enumerate(sc["X"]):
        ys = [matvec(Kinv, xs[i][j] + [1.0])[:2] for i in range(2)]
        Y = midpoint_triangulation(sc["R"][0], sc["t"][0], ys[0],
                                   sc["R"][1], sc["t"][1], ys[1])
        assert norm(sub(Y, X)) <= 0.05


def test_parallel_rays_raise():
    with pytest.raises(ValueError):
        midpoint([0, 0, 0], [0, 0, 1], [1, 0, 0], [0, 0, 2])
    with pytest.raises(ValueError):
        nearest_point_to_rays([[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [0, 0, -3]])


def test_point_behind_a_camera_gives_negative_depth():
    C1, d1 = [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]
    C2, d2 = [1.0, 0.0, 0.0], [1.0, 0.0, 1.0]
    X, l1, l2 = midpoint(C1, d1, C2, d2)
    assert rel(X, [0.0, 0.0, -1.0]) <= 1e-12
    assert l1 < 0 and l2 < 0
    assert math.isclose(l1, -1.0)

History

The common perpendicular of two skew lines is a classical construction of solid geometry, and its midpoint is a natural way to intersect two rays that do not meet. Hartley and Sturm (1997) included the midpoint method in their study of triangulation, noted that it is not projective invariant, and found it less accurate than their optimal method in their tests. Lee and Civera (2019) returned to midpoint methods and proposed weighted forms that are closed form and accurate for small parallax.

References

  1. Richard I. Hartley and Peter Sturm, Triangulation, Computer Vision and Image Understanding 68(2), 1997, 146-157, the midpoint method and its comparison with the linear and optimal methods
  2. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 11.2.4, Triangulation
  3. Seong Hun Lee and Javier Civera, Triangulation: Why Optimize?, British Machine Vision Conference (BMVC), 2019, the weighted midpoint methods for two views

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