Algorithm Search⌘K

Algorithmadvanced

Tsai's calibration method

Also called Tsai two-stage calibration, radial alignment constraint calibration.

Calibrate in two stages, first the rotation, T_x, T_y and the x scale factor by the radial alignment constraint, which radial distortion does not affect, then f, T_z and the distortion.

Time
O(T n) worst · averageO(n) best
Space
O(n) extra
Where
T = the number of Levenberg-Marquardt iterations; n = the number of world to image point pairs
Properties
deterministicnot exactofflineiterative
Origin
Roger Y. Tsai, 1987

Tsai's method calibrates a camera from one image of known 3D points, with a model that includes radial lens distortion. Its key idea is the radial alignment constraint: radial distortion moves a point only along the line from the principal point, so the direction of each image point from the principal point does not depend on the distortion, the focal length or the depth TzT_z. The first stage uses this to get the rotation, TxT_x, TyT_y and the scale factor sxs_x of the x axis from a linear system. The second stage gets ff and TzT_z from another linear system, then fits ff, TzT_z and the distortion coefficient κ1\kappa_1 by nonlinear least squares. Among the close pages, camera calibration states the problem; DLT resectioning also uses a 3D target, but has no distortion and does not need the principal point; camera matrix decomposition splits a 3×43 \times 4 matrix; and Zhang's method uses several views of a plane.

In plain words

A lens bends straight lines, but it bends them in a simple way: each point moves straight toward or away from the center of the image. So the direction of a point from the center stays correct, even if its distance is wrong. Tsai's method uses only those directions first. From them it finds how the camera is turned and how it is shifted sideways and up or down, with simple equations. The distances from the center, which the lens has changed, are used only after that, to find the focal length, how far away the camera is, and how strong the lens bending is. Splitting the work this way means that the hard nonlinear part has only three unknowns.

The problem

Input. World points Xi∈R3X_i \in \mathbb{R}^3, i=1,…,ni = 1, \dots, n, with n≥7n \ge 7 and not all on one plane; their pixels (ui,vi)(u_i, v_i); and the principal point (cx,cy)(c_x, c_y), which is known (Tsai takes the center of the image).

Camera model. With (xc,yc,zc)=RX+T(x_c, y_c, z_c) = R X + T and T=(Tx,Ty,Tz)T = (T_x, T_y, T_z), in units of pixels along the y axis:

Xu=fxczc,Yu=fyczc,Xu=Xd(1+κ1rd2),Yu=Yd(1+κ1rd2),rd2=Xd2+Yd2,X_u = f \frac{x_c}{z_c}, \quad Y_u = f \frac{y_c}{z_c}, \quad X_u = X_d (1 + \kappa_1 r_d^2), \quad Y_u = Y_d (1 + \kappa_1 r_d^2), \quad r_d^2 = X_d^2 + Y_d^2,
u=cx+sxXd,v=cy+Yd.u = c_x + s_x X_d, \qquad v = c_y + Y_d.

So the focal lengths are ff along y and sxfs_x f along x, and the skew is 0. As in Tsai's paper, the distortion maps the distorted point (Xd,Yd)(X_d, Y_d) to the undistorted one. This is the opposite direction from the Brown-Conrady model used by OpenCV, so a κ1\kappa_1 from this model is not a k1k_1 of OpenCV.

Output. RR, TT, ff, sxs_x and κ1\kappa_1.

The algorithm

Write xi′=ui−cx=sxXd,ix'_i = u_i - c_x = s_x X_{d,i} and yi′=vi−cy=Yd,iy'_i = v_i - c_y = Y_{d,i}. The distortion factor 1+κ1rd21 + \kappa_1 r_d^2 is the same for XdX_d and YdY_d, so Xd/Yd=xc/ycX_d / Y_d = x_c / y_c; this is the radial alignment constraint. With r1,r2,r3r_1, r_2, r_3 the rows of RR, it reads xi′(r2⋅Xi+Ty)=sx yi′(r1⋅Xi+Tx)x'_i (r_2 \cdot X_i + T_y) = s_x\, y'_i (r_1 \cdot X_i + T_x). Dividing by TyT_y gives one linear equation per point in seven unknowns:

(yi′XiTyi′−xi′XiT)a=xi′,a=(sxr1Ty,sxTxTy,r2Ty).\begin{pmatrix} y'_i X_i^{\mathsf T} & y'_i & -x'_i X_i^{\mathsf T} \end{pmatrix} a = x'_i, \qquad a = \Big(\frac{s_x r_1}{T_y}, \frac{s_x T_x}{T_y}, \frac{r_2}{T_y}\Big).

Neither ff, nor TzT_z, nor κ1\kappa_1 appears.

  1. TSAI-CALIBRATE(X_1..X_n, (u_i, v_i), c_x, c_y)
  2. 1x'_i <- u_i - c_x ; y'_i <- v_i - c_y
  3. 2a <- least squares solution of the n equations (y'_i X_i, y'_i, -x'_i X_i) . a = x'_i
  4. 3|T_y| <- 1 / |(a_5, a_6, a_7)| ; s_x <- |T_y| |(a_1, a_2, a_3)|
  5. 4T_y <- |T_y| ; r_1 <- T_y (a_1, a_2, a_3) / s_x ; r_2 <- T_y (a_5, a_6, a_7) ; T_x <- T_y a_4 / s_x
  6. 5if, at the point farthest from the center, x_c or y_c has the other sign than x' or y' then negate T_y, T_x, r_1, r_2
  7. 6r_3 <- r_1 × r_2 ; R <- nearest rotation to the matrix with rows r_1, r_2, r_3
  8. 7(f, T_z) <- least squares on f y_i - y'_i T_z = y'_i w_i, with y_i = r_2 . X_i + T_y and w_i = r_3 . X_i
  9. 8(f, T_z, kappa_1) <- Levenberg-Marquardt on the y residuals, from (f, T_z, 0)
  10. 9return R, (T_x, T_y, T_z), f, s_x, kappa_1

Lines L3 and L4 use ∥r2∥=∥r1∥=1\|r_2\| = \|r_1\| = 1: the last three entries of aa are r2/Tyr_2 / T_y, so their norm is 1/∣Ty∣1 / |T_y|, and the first three are sxr1/Tys_x r_1 / T_y, so their norm is sx/∣Ty∣s_x / |T_y|. Line L5 fixes the sign of TyT_y: with f>0f > 0, sx>0s_x > 0 and 1+κ1rd2>01 + \kappa_1 r_d^2 > 0, a point and its image lie on the same side of the center, so xcx_c has the sign of x′x' and ycy_c the sign of y′y'. A point far from the center makes this test robust to noise. Line L7 ignores the distortion and uses only the y coordinate, so that sxs_x does not enter; from Yd(wi+Tz)=fyiY_d (w_i + T_z) = f y_i it is linear in (f,Tz)(f, T_z). Line L8 minimizes ∑i(Yd,i(1+κ1rd,i2)−fyi/(wi+Tz))2\sum_i (Y_{d,i} (1 + \kappa_1 r_{d,i}^2) - f y_i / (w_i + T_z))^2, which has only three unknowns.

Example

The reference tests use f=800f = 800, sx=1.02s_x = 1.02, κ1=8⋅10−7\kappa_1 = 8 \cdot 10^{-7}, principal point (320,240)(320, 240), the rotation R0=Rx(0.3)Ry(−0.2)Rz(0.1)R_0 = R_x(0.3) R_y(-0.2) R_z(0.1), T=(0.2,0.6,5)T = (0.2, 0.6, 5), and 40 random points in the cube [−1,1]3[-1, 1]^3. The farthest image point is 258.9258.9 pixels from the center, where the distortion moves it by κ1rd3≈13.9\kappa_1 r_d^3 \approx 13.9 pixels.

step result
L2 to L6 Tx=0.2T_x = 0.2, Ty=0.6T_y = 0.6, sx=1.02s_x = 1.02 to 15 digits, and ∥R−R0∥F=4⋅10−16\|R - R_0\|_F = 4 \cdot 10^{-16}, although the pixels are distorted
L7 f=788.55f = 788.55 and Tz=5.0845T_z = 5.0845: the distortion biases the linear stage by 1.4%
L8 the cost falls from 111.6 to 9.8⋅10−269.8 \cdot 10^{-26} in 8 accepted steps
L9 f=800f = 800, Tz=5T_z = 5, κ1=8⋅10−7\kappa_1 = 8 \cdot 10^{-7}, to at least 13 digits

With pixel noise of σ=0.1\sigma = 0.1 on 60 points, over 5 random scenes, the relative error of ff was between 0.02% and 0.15%, and that of κ1\kappa_1 between 0.13% and 0.9%.

Correctness

With exact data, the radial alignment constraint holds for the true parameters whatever ff, TzT_z and κ1\kappa_1 are, so the true aa solves the system of line L2. If the n×7n \times 7 matrix has full rank, which needs points not on one plane and Ty≠0T_y \ne 0, the least squares solution is that aa, and lines L3 and L4 recover ∣Ty∣|T_y|, sxs_x, r1r_1, r2r_2 and TxT_x up to the common sign of TyT_y. Line L5 picks the right sign, and line L6 gives RR exactly. Without distortion, line L7 gives ff and TzT_z exactly. Line L8 accepts only steps that lower the cost. The full proof is in the proof file below.

Proof: Stage one of Tsai's method is exact under radial distortion, and the linear stage is exact without itfull

We use the notation and the camera model of the page. The true parameters are RR with rows r1,r2,r3r_1, r_2, r_3, T=(Tx,Ty,Tz)T = (T_x, T_y, T_z), f>0f > 0, sx>0s_x > 0 and κ1\kappa_1, and the data are exact. We assume that every point is in front of the camera (zc>0z_c > 0) and that 1+κ1rd2>01 + \kappa_1 r_d^2 > 0 at every image point, so that distortion does not flip a point through the center.

Claim. (a) If Ty≠0T_y \ne 0 and the n×7n \times 7 matrix AA of line L2 has rank 7, lines L2 to L6 return the true RR, TxT_x, TyT_y and sxs_x, for every value of ff, TzT_z and κ1\kappa_1. (b) If moreover κ1=0\kappa_1 = 0 and the n×2n \times 2 matrix of line L7 has rank 2, line L7 returns the true ff and TzT_z. (c) Line L8 never increases its cost.

Lemma 1 (radial alignment). For every point, xi′ yc,i=sx yi′ xc,ix'_i\, y_{c,i} = s_x\, y'_i\, x_{c,i}, where xc,i=r1⋅Xi+Txx_{c,i} = r_1 \cdot X_i + T_x and yc,i=r2⋅Xi+Tyy_{c,i} = r_2 \cdot X_i + T_y.

Proof. Let g=1+κ1rd2>0g = 1 + \kappa_1 r_d^2 > 0. The model gives Xd=fxc/(gzc)X_d = f x_c / (g z_c) and Yd=fyc/(gzc)Y_d = f y_c / (g z_c), so Xdyc=YdxcX_d y_c = Y_d x_c. With x′=sxXdx' = s_x X_d and y′=Ydy' = Y_d, this is x′yc=sxy′xcx' y_c = s_x y' x_c. □\square

The lemma does not involve ff, TzT_z or κ1\kappa_1. Dividing it by TyT_y and moving the terms gives

xi′=yi′sxr1Ty⋅Xi+yi′sxTxTy−xi′r2Ty⋅Xi,x'_i = y'_i \frac{s_x r_1}{T_y} \cdot X_i + y'_i \frac{s_x T_x}{T_y} - x'_i \frac{r_2}{T_y} \cdot X_i,

which is row ii of line L2 applied to a∗=(sxr1/Ty,  sxTx/Ty,  r2/Ty)a^\ast = (s_x r_1 / T_y, \; s_x T_x / T_y, \; r_2 / T_y). So Aa∗=x′A a^\ast = x'.

Proof of (a). Since Aa∗=x′A a^\ast = x' and AA has rank 7, a∗a^\ast is the unique least squares solution, and line L2 returns it. Since ∥r2∥=1\|r_2\| = 1, ∥(a5,a6,a7)∥=1/∣Ty∣\|(a_5, a_6, a_7)\| = 1 / |T_y|, and since ∥r1∥=1\|r_1\| = 1, ∥(a1,a2,a3)∥=sx/∣Ty∣\|(a_1, a_2, a_3)\| = s_x / |T_y|. So line L3 returns the true ∣Ty∣|T_y| and sxs_x. Let ϵ=sign⁡(Ty)\epsilon = \operatorname{sign}(T_y). Line L4 sets Ty←∣Ty∣=ϵTyT_y \leftarrow |T_y| = \epsilon T_y and

r1←∣Ty∣sxr1Tysx=ϵr1,r2←∣Ty∣r2Ty=ϵr2,Tx←∣Ty∣sxTxTysx=ϵTx.r_1 \leftarrow |T_y| \frac{s_x r_1}{T_y s_x} = \epsilon r_1, \qquad r_2 \leftarrow |T_y| \frac{r_2}{T_y} = \epsilon r_2, \qquad T_x \leftarrow |T_y| \frac{s_x T_x}{T_y s_x} = \epsilon T_x.

So after line L4, the four quantities are the true ones times the same ϵ\epsilon. For the point kk farthest from the center, line L5 computes ϵxc,k\epsilon x_{c,k} and ϵyc,k\epsilon y_{c,k} with the true xc,k,yc,kx_{c,k}, y_{c,k}. By the proof of Lemma 1, xk′=sxfxc,k/(gzc,k)x'_k = s_x f x_{c,k} / (g z_{c,k}) and yk′=fyc,k/(gzc,k)y'_k = f y_{c,k} / (g z_{c,k}) with sx,f,g,zc,k>0s_x, f, g, z_{c,k} > 0, so xk′x'_k has the sign of xc,kx_{c,k} and yk′y'_k that of yc,ky_{c,k}. The point kk has (xk′,yk′)≠0(x'_k, y'_k) \ne 0, because it is the farthest from the center and not all points are at the center (else AA would be 0). So at least one of xk′xc,kx'_k x_{c,k} and yk′yc,ky'_k y_{c,k} is positive. If ϵ=+1\epsilon = +1, both products in line L5 are ≥0\ge 0 and nothing changes. If ϵ=−1\epsilon = -1, both are ≤0\le 0 and at least one is negative, so line L5 negates all four quantities. In both cases the result is the true TyT_y, TxT_x, r1r_1 and r2r_2. Then r1×r2=r3r_1 \times r_2 = r_3, because the rows of a rotation form a right handed orthonormal basis, so line L6 starts from the true RR, and the nearest rotation to a rotation QQ is QQ itself. □\square

Proof of (b). With κ1=0\kappa_1 = 0, Yd,i=fyc,i/zc,iY_{d,i} = f y_{c,i} / z_{c,i} and zc,i=wi+Tzz_{c,i} = w_i + T_z with wi=r3⋅Xiw_i = r_3 \cdot X_i. So yi′(wi+Tz)=fyc,iy'_i (w_i + T_z) = f y_{c,i}, that is, fyc,i−yi′Tz=yi′wif y_{c,i} - y'_i T_z = y'_i w_i. By (a), the yc,iy_{c,i} and wiw_i of line L7 are the true ones, so the true (f,Tz)(f, T_z) solves the system exactly. With rank 2 it is the unique least squares solution, and line L7 returns it. □\square

Proof of (c). In line L8 a step is accepted only if the new cost is strictly lower than the current one; otherwise the damping grows and the step is tried again, and the loop ends when no step is accepted. So the accepted costs strictly decrease. □\square

Remark (with distortion). If κ1≠0\kappa_1 \ne 0, line L7 is biased, because it treats YdY_d as YuY_u. The cost of line L8 is 0 at the true (f,Tz,κ1)(f, T_z, \kappa_1), since Yd(1+κ1rd2)=Yu=fyc/zcY_d (1 + \kappa_1 r_d^2) = Y_u = f y_c / z_c there; so with exact data the true values are a global minimizer, and Levenberg-Marquardt reaches them from the linear start when that start is close enough. This last part is a heuristic, not a theorem: Levenberg-Marquardt only guarantees a local minimum.

Remark (rank). If all points lie on a plane m⋅X=d\mathbf{m} \cdot X = d, the first four columns c1,…,c4c_1, \dots, c_4 of AA are the entries of yi′(Xi,1)y'_i (X_i, 1), so m1c1+m2c2+m3c3−d c4=0m_1 c_1 + m_2 c_2 + m_3 c_3 - d\, c_4 = 0, and AA has rank at most 6; this is why the general form needs points that are not coplanar. If Ty=0T_y = 0, the division that defines a∗a^\ast is not possible, and the system has no solution of this form.

Complexity

Lines L1 and L4 to L6 are O(n)O(n) or O(1)O(1). Line L2 is a least squares problem with nn rows and 7 columns, which costs O(n)O(n) by an SVD or by the normal equations. Line L7 is O(n)O(n). Each Levenberg-Marquardt iteration in line L8 computes nn residuals and an n×3n \times 3 analytic Jacobian, then solves a 3×33 \times 3 system, so it costs O(n)O(n), and TT iterations cost O(Tn)O(T n). The extra space is O(n)O(n) for the two linear systems and the Jacobian. The best case, O(n)O(n), is when the refinement stops after a constant number of steps, or is skipped.

Properties

  • Distortion does not affect stage one. The rotation, TxT_x, TyT_y and sxs_x are exact on exact data for any κ1\kappa_1, as the tests check.
  • Small nonlinear part. Only three parameters go into the nonlinear fit, so it is fast and has a good start.
  • Needs the principal point. The constraint is about directions from the principal point, so an error in (cx,cy)(c_x, c_y) biases every parameter. Tsai uses the center of the image.
  • Not maximum likelihood. Stage one fixes the rotation and TxT_x, TyT_y before the distortion is known, and the final fit uses only the y residuals. So the result is not the minimizer of the full reprojection error.
  • One image. A single image of a 3D target is enough.

Variants and improvements

  • Coplanar points. For points on the plane Z=0Z = 0, Tsai's paper gives a version with 5 unknowns in stage one. It needs sxs_x to be known, since it cannot be separated from the other parameters for a plane.
  • Full refinement. Use the result as the start of a Levenberg-Marquardt fit of all parameters, including the principal point and more distortion terms, on the full reprojection error. Heikkila and Silven (1997) follow this scheme with a DLT start and radial and tangential distortion.
  • Several images. Use several images of the target, sharing the intrinsics, which helps to fix the principal point.
  • Other distortion models. The first stage holds for any purely radial distortion about the principal point, including the division model and higher order terms.

When to use it

Use Tsai's method when you have a precise 3D target, or a plane moved by a known amount, and a lens with clear radial distortion, and you want a start that needs no guess. Today, most users take Zhang's method with a flat pattern, which also estimates the principal point. Tsai's radial alignment constraint is still useful whenever a method must not depend on an unknown radial distortion, for example to get a pose from a camera with an unknown lens.

Pitfalls

  • TyT_y near zero. The equations of line L2 divide by TyT_y, so they fail when the origin of the world frame lies near the plane yc=0y_c = 0 of the camera. Move the world origin, for example to a corner of the target that is not near the middle row of the image.
  • Coplanar points in the general form. The n×7n \times 7 system is rank deficient for coplanar points; the code raises an error. Use the coplanar variant with known sxs_x.
  • Points near the center. Near the principal point, the direction of a point is poorly measured, and the sign test of line L5 can fail. Use points spread over the image, and the farthest point for the sign.
  • Wrong principal point. An offset of a few pixels in (cx,cy)(c_x, c_y) breaks the constraint and biases the rotation. Do not use this method on cropped images or on cameras whose principal point is far from the center.
  • Mixing distortion conventions. Tsai's κ1\kappa_1 maps distorted to undistorted points. Using it as the k1k_1 of a model that maps undistorted to distorted points gives the wrong correction.
  • A negative ff. If the linear stage gives f≤0f \le 0, the sign of TyT_y or the axis conventions are wrong; the code raises an error rather than return a mirrored camera.

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()
tsai_calibration_method.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tsai-calibration-method/. The authors are listed in prov/0E3W2B.jsonl.
"""Tsai's two-stage calibration (Tsai 1987), for non-coplanar points and a
known principal point.

Camera model, in pixels, with the conventions of the area (X_c = R X_w + t,
image Y down, Z forward):
    (x_c, y_c, z_c) = R X_w + (T_x, T_y, T_z)
    X_u = f x_c / z_c,  Y_u = f y_c / z_c            (undistorted, y pixel units)
    X_u = X_d (1 + kappa1 r_d^2),  Y_u = Y_d (1 + kappa1 r_d^2),  r_d^2 = X_d^2 + Y_d^2
    u = c_x + s_x X_d,  v = c_y + Y_d
So f is the focal length in pixels along y, s_x f is the focal length along
x, and the skew is zero. As in Tsai's paper, the distortion maps distorted
to undistorted coordinates.
"""

from __future__ import annotations

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

from cvla import cross, mul, polyroots_real, solve, svd, transpose

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


def tsai_project(R: Sequence[Sequence[float]], t: Sequence[float], f: float, sx: float,
                 kappa1: float, cx: float, cy: float,
                 pts: Sequence[Sequence[float]]) -> List[Vector]:
    """Pixels of world points under the model above. The distorted radius
    r_d is the real root of kappa1 r_d^3 + r_d - r_u = 0 closest to r_u.
    Raises ValueError if a point is not in front of the camera."""
    out = []
    for X in pts:
        xc = [sum(R[i][k] * X[k] for k in range(3)) + t[i] for i in range(3)]
        if xc[2] <= 0.0:
            raise ValueError("point behind the camera")
        xu, yu = f * xc[0] / xc[2], f * xc[1] / xc[2]
        ru = math.hypot(xu, yu)
        if ru == 0.0 or kappa1 == 0.0:
            ratio = 1.0
        else:
            roots = [r for r in polyroots_real([kappa1, 0.0, 1.0, -ru]) if r > 0.0]
            if not roots:
                raise ValueError("no distorted radius for this point")
            ratio = min(roots, key=lambda r: abs(r - ru)) / ru
        out.append([cx + sx * xu * ratio, cy + yu * ratio])
    return out


def _lstsq(A: Sequence[Sequence[float]], b: Sequence[float]) -> Vector:
    """Least squares solution of A x = b by the SVD. Raises ValueError if A
    is rank deficient (relative tolerance 1e-10)."""
    U, s, V = svd(A)
    if s[-1] <= 1e-10 * s[0]:
        raise ValueError("rank deficient system: the points are coplanar or too few")
    utb = [sum(U[i][k] * b[i] for i in range(len(b))) / s[k] for k in range(len(s))]
    return [sum(V[j][k] * utb[k] for k in range(len(s))) for j in range(len(V))]


def nearest_rotation(Q: Sequence[Sequence[float]]) -> Matrix:
    """The rotation closest to Q in the Frobenius norm (SVD, det = +1)."""
    U, _, V = svd(Q)
    R = mul(U, transpose(V))
    d = (R[0][0] * (R[1][1] * R[2][2] - R[1][2] * R[2][1])
         - R[0][1] * (R[1][0] * R[2][2] - R[1][2] * R[2][0])
         + R[0][2] * (R[1][0] * R[2][1] - R[1][1] * R[2][0]))
    if d < 0.0:
        U = [row[:2] + [-row[2]] for row in U]
        R = mul(U, transpose(V))
    return R


def stage_one(pts: Sequence[Sequence[float]], pix: Sequence[Sequence[float]],
              cx: float, cy: float) -> Tuple[Matrix, float, float, float]:
    """R, T_x, T_y and s_x from the radial alignment constraint. Radial
    distortion, f and T_z do not enter, so with exact data the result is
    exact. Needs n >= 7 points that are not coplanar, and T_y != 0."""
    if len(pts) < 7 or len(pts) != len(pix):
        raise ValueError("need at least 7 point pairs")
    xp = [p[0] - cx for p in pix]  # @line L1
    yp = [p[1] - cy for p in pix]  # @line L1
    A, b = [], []
    for X, x, y in zip(pts, xp, yp):
        A.append([y * X[0], y * X[1], y * X[2], y, -x * X[0], -x * X[1], -x * X[2]])
        b.append(x)
    a = _lstsq(A, b)  # @line L2
    ty = 1.0 / math.sqrt(a[4] ** 2 + a[5] ** 2 + a[6] ** 2)  # @line L3
    sx = ty * math.sqrt(a[0] ** 2 + a[1] ** 2 + a[2] ** 2)  # @line L3
    r1 = [ty * v / sx for v in a[0:3]]  # @line L4
    r2 = [ty * v for v in a[4:7]]  # @line L4
    tx = ty * a[3] / sx  # @line L4
    k = max(range(len(pts)), key=lambda i: xp[i] ** 2 + yp[i] ** 2)
    X = pts[k]
    xc = sum(r1[j] * X[j] for j in range(3)) + tx
    yc = sum(r2[j] * X[j] for j in range(3)) + ty
    if xc * xp[k] < 0.0 or yc * yp[k] < 0.0:  # @line L5
        ty, tx = -ty, -tx
        r1 = [-v for v in r1]
        r2 = [-v for v in r2]
    r3 = cross(r1, r2)  # @line L6
    R = nearest_rotation([r1, r2, r3])  # @line L6
    return R, tx, ty, sx


def stage_two_linear(R, ty, pts, pix, cy) -> Tuple[float, float]:
    """f and T_z from f y_i - Y_d T_z = Y_d w_i, with distortion ignored."""
    A, b = [], []
    for X, p in zip(pts, pix):
        yi = sum(R[1][j] * X[j] for j in range(3)) + ty
        wi = sum(R[2][j] * X[j] for j in range(3))
        yd = p[1] - cy
        A.append([yi, -yd])
        b.append(yd * wi)
    ata = [[sum(r[i] * r[j] for r in A) for j in range(2)] for i in range(2)]
    atb = [sum(r[i] * v for r, v in zip(A, b)) for i in range(2)]
    f, tz = solve(ata, atb)  # @line L7
    if f <= 0.0:
        raise ValueError("f <= 0: the data do not fit a camera with these conventions")
    return f, tz


def refine_f_tz_kappa(R, ty, sx, pts, pix, cx, cy, f0, tz0,
                      max_iter: int = 100) -> Tuple[float, float, float, List[float]]:
    """Levenberg-Marquardt on e_i = Y_d (1 + kappa1 r_d^2) - f y_i / (w_i + T_z),
    with an analytic Jacobian. kappa1 is scaled by the largest r_d^2 so that
    the three unknowns have like sizes. Returns f, T_z, kappa1 and the cost
    after each accepted step (the first entry is the start cost)."""
    data = []
    for X, p in zip(pts, pix):
        yi = sum(R[1][j] * X[j] for j in range(3)) + ty
        wi = sum(R[2][j] * X[j] for j in range(3))
        xd, yd = (p[0] - cx) / sx, p[1] - cy
        data.append((yi, wi, yd, xd * xd + yd * yd))
    L2 = max(d[3] for d in data) or 1.0

    def resid(q):
        f, tz, k = q
        return [yd * (1.0 + k * rd2 / L2) - f * yi / (wi + tz) for yi, wi, yd, rd2 in data]

    q = [f0, tz0, 0.0]
    e = resid(q)
    cost = sum(v * v for v in e)
    history = [cost]
    mu = 1e-3
    for _ in range(max_iter):
        f, tz, _ = q
        J = [[-yi / (wi + tz), f * yi / (wi + tz) ** 2, yd * rd2 / L2]
             for yi, wi, yd, rd2 in data]
        A = [[sum(r[i] * r[j] for r in J) for j in range(3)] for i in range(3)]
        g = [sum(r[i] * v for r, v in zip(J, e)) for i in range(3)]
        accepted = False
        while mu < 1e12:
            Ad = [[A[i][j] + (mu * A[i][i] if i == j else 0.0) for j in range(3)] for i in range(3)]
            try:
                d = solve(Ad, [-v for v in g])
            except ValueError:
                mu *= 10.0
                continue
            qn = [q[i] + d[i] for i in range(3)]
            if any(wi + qn[1] <= 0.0 for _, wi, _, _ in data):
                mu *= 10.0
                continue
            en = resid(qn)
            cn = sum(v * v for v in en)
            if cn < cost:
                accepted = True
                drop = cost - cn
                q, e, cost = qn, en, cn
                history.append(cost)
                mu = max(mu / 10.0, 1e-15)
                break
            mu *= 10.0
        if not accepted or drop <= 1e-14 * cost or cost <= 1e-26:
            break
    return q[0], q[1], q[2] / L2, history


def calibrate(pts: Sequence[Sequence[float]], pix: Sequence[Sequence[float]],
              cx: float, cy: float, refine: bool = True) -> Dict[str, object]:
    """Tsai's two-stage method. pts are world points (not coplanar), pix
    their pixels, (cx, cy) the known principal point."""
    R, tx, ty, sx = stage_one(pts, pix, cx, cy)
    f, tz = stage_two_linear(R, ty, pts, pix, cy)
    kappa1, history = 0.0, []
    if refine:
        f, tz, kappa1, history = refine_f_tz_kappa(R, ty, sx, pts, pix, cx, cy, f, tz)  # @line L8
    return {"R": R, "t": [tx, ty, tz], "f": f, "sx": sx, "kappa1": kappa1,  # @line L9
            "history": history}
test_tsai_calibration_method.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tsai-calibration-method/. The authors are listed in prov/0E3W2B.jsonl.
"""Tests of Tsai's two-stage calibration on synthetic non-coplanar points."""

import math
import random

from cvgeom import add_noise, camera_matrix, make_K, project, rot_x, rot_y, rot_z
from cvla import det, eye, mul, norm, sub, transpose
from tsai_calibration_method import (calibrate, stage_one, stage_two_linear,
                                     tsai_project)

F, SX, KAPPA, CX, CY = 800.0, 1.02, 8e-7, 320.0, 240.0
R0 = mul(mul(rot_x(0.3), rot_y(-0.2)), rot_z(0.1))


def scene(t, n=40, seed=1, kappa1=KAPPA):
    rng = random.Random(seed)
    pts = [[rng.uniform(-1.0, 1.0) for _ in range(3)] for _ in range(n)]
    return pts, tsai_project(R0, t, F, SX, kappa1, CX, CY, pts)


def is_rotation(R, tol):
    return norm(sub(mul(transpose(R), R), eye(3))) <= tol and abs(det(R) - 1.0) <= tol


def test_forward_model_inverts_the_distortion():
    t = [0.2, 0.6, 5.0]
    pts, pix = scene(t)
    for X, (u, v) in zip(pts, pix):
        xc = [sum(R0[i][k] * X[k] for k in range(3)) + t[i] for i in range(3)]
        xd, yd = (u - CX) / SX, v - CY
        g = 1.0 + KAPPA * (xd * xd + yd * yd)
        assert abs(xd * g - F * xc[0] / xc[2]) <= 1e-9
        assert abs(yd * g - F * xc[1] / xc[2]) <= 1e-9


def test_no_distortion_matches_pinhole_reference():
    t = [0.2, 0.6, 5.0]
    pts, pix = scene(t, kappa1=0.0)
    P = camera_matrix(make_K(SX * F, F, CX, CY), R0, t)
    for X, p in zip(pts, pix):
        assert norm(sub(project(P, X), p)) <= 1e-9


def test_stage_one_exact_despite_distortion():
    for t in ([0.2, 0.6, 5.0], [-0.4, -0.6, 6.0], [0.3, 0.05, 4.0]):
        pts, pix = scene(t)
        R, tx, ty, sx = stage_one(pts, pix, CX, CY)
        assert is_rotation(R, 1e-12)
        assert norm(sub(R, R0)) <= 1e-8
        assert abs(tx - t[0]) <= 1e-8 and abs(ty - t[1]) <= 1e-8
        assert abs(sx - SX) <= 1e-8


def test_linear_stage_is_exact_without_distortion():
    t = [0.2, 0.6, 5.0]
    pts, pix = scene(t, kappa1=0.0)
    R, _, ty, _ = stage_one(pts, pix, CX, CY)
    f, tz = stage_two_linear(R, ty, pts, pix, CY)
    assert abs(f - F) <= 1e-8 * F and abs(tz - t[2]) <= 1e-8 * t[2]


def test_full_method_exact():
    for t in ([0.2, 0.6, 5.0], [-0.4, -0.6, 6.0]):
        pts, pix = scene(t)
        res = calibrate(pts, pix, CX, CY)
        assert abs(res["f"] - F) <= 1e-6 * F
        assert abs(res["t"][2] - t[2]) <= 1e-6 * t[2]
        assert abs(res["kappa1"] - KAPPA) <= 1e-6 * KAPPA
        assert norm(sub(res["t"], t)) <= 1e-6 * norm(t)
        # The linear stage alone is biased by the distortion.
        R, _, ty, _ = stage_one(pts, pix, CX, CY)
        f_lin, _ = stage_two_linear(R, ty, pts, pix, CY)
        assert abs(f_lin - F) > 1e-3 * F


def test_lm_cost_never_increases():
    rng = random.Random(4)
    pts, pix = scene([0.2, 0.6, 5.0])
    hist = calibrate(pts, add_noise(rng, pix, 0.3), CX, CY)["history"]
    assert len(hist) >= 3
    assert all(b <= a for a, b in zip(hist, hist[1:]))


def test_noise_sigma_01_sixty_points():
    # sigma = 0.1 pixel on 60 points; the worst of 5 seeds must pass.
    errs_f, errs_k, errs_r = [], [], []
    for seed in range(5):
        rng = random.Random(100 + seed)
        pts, pix = scene([0.2, 0.6, 5.0], n=60, seed=seed)
        res = calibrate(pts, add_noise(rng, pix, 0.1), CX, CY)
        assert is_rotation(res["R"], 1e-12)
        errs_f.append(abs(res["f"] - F) / F)
        errs_k.append(abs(res["kappa1"] - KAPPA) / KAPPA)
        errs_r.append(norm(sub(res["R"], R0)))
    assert max(errs_f) <= 0.005
    assert max(errs_k) <= 0.05
    assert max(errs_r) <= 0.005


def test_coplanar_points_raise():
    rng = random.Random(6)
    pts = [[rng.uniform(-1, 1), rng.uniform(-1, 1), 0.0] for _ in range(30)]
    pix = tsai_project(R0, [0.2, 0.6, 5.0], F, SX, KAPPA, CX, CY, pts)
    try:
        stage_one(pts, pix, CX, CY)
    except ValueError:
        return
    raise AssertionError("expected ValueError")


def test_too_few_points_raise():
    pts, pix = scene([0.2, 0.6, 5.0], n=6)
    try:
        stage_one(pts, pix, CX, CY)
    except ValueError:
        return
    raise AssertionError("expected ValueError")


def test_angle_of_recovered_rotation():
    pts, pix = scene([0.2, 0.6, 5.0])
    R, _, _, _ = stage_one(pts, pix, CX, CY)
    c = (sum(R[i][i] for i in range(3)) - 1.0) / 2.0
    c0 = (sum(R0[i][i] for i in range(3)) - 1.0) / 2.0
    assert abs(math.acos(c) - math.acos(c0)) <= 1e-8

History

Roger Tsai presented the two stage method at the IEEE Conference on Computer Vision and Pattern Recognition in 1986, and the full paper appeared in the IEEE Journal on Robotics and Automation in 1987. It was aimed at 3D measurement with standard TV cameras and lenses, and it handled radial distortion with a linear start, which earlier methods either ignored or fitted by a nonlinear search from a guess. It was widely used in machine vision until plane based methods such as Zhang's (2000) became common.

References

  1. Roger Y. Tsai, A versatile camera calibration technique for high-accuracy 3D machine vision metrology using off-the-shelf TV cameras and lenses, IEEE Journal on Robotics and Automation 3(4), 1987, 323-344, the camera model with radial distortion, the radial alignment constraint, the two stage method for coplanar and for non-coplanar points, and the sign rule for T_y
  2. Janne Heikkila and Olli Silven, A four-step camera calibration procedure with implicit image correction, Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 1997, 1106-1112, the discussion of earlier methods, including the two stage method, and a full nonlinear fit as an alternative
  3. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 7.4, Radial distortion (the radial distortion model and its estimation together with the camera)

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