Algorithm Search⌘K

Algorithmcore

Stereo rectification

Also called epipolar rectification, Loop-Zhang rectification.

Warp both images of a stereo pair by homographies so that epipolar lines become matching horizontal scanlines.

Time
Θ(W H) worst · average · best
Space
Θ(W H) extra
Where
H = the height of the output images in pixels; W = the width of the output images in pixels
Properties
deterministicexactofflineiterative
Origin
Richard Hartley, Charles Loop, Zhengyou Zhang, Andrea Fusiello, Emanuele Trucco, Alessandro Verri, 1999

Stereo rectification turns the two images of a stereo pair into a new pair in which every epipolar line is a horizontal pixel row, and the epipolar line of row vv in one image is row vv in the other. It does this by one homography per image, which is the same as turning each camera about its center until both look in one direction, perpendicular to the baseline, with one shared intrinsic matrix. After rectification the search for a match is a search along one row, and the shift along the row is the disparity, from which depth follows by Z=fb/dZ = f b / d. This page gives the method for calibrated cameras of Fusiello, Trucco and Verri (2000), which needs K1K_1, K2K_2 and the relative pose from stereo calibration. The methods of Hartley (1999) and of Loop and Zhang (1999) need only the fundamental matrix; they are under the variants below. The homographies cost Θ(1)\Theta(1) to compute, and the warp of the images costs Θ(WH)\Theta(WH) on the real RAM.

In plain words

Two cameras look at the same scene from two places. A point seen in the first photo can be anywhere on a certain line in the second photo, and in general this line is tilted. Matching is easier if that line is always a plain row of pixels, the same row as the point. Rectification makes this true. It turns both cameras in your mind, without moving them, so that both point the same way, the line between them is horizontal in their view, and they have the same lens. Then it redraws each photo as the turned camera would see it. Turning a camera about its center needs no knowledge of the scene, so each photo is redrawn by one fixed formula for all of its pixels.

The problem

Input. Two cameras Pi=Ki[Ri∣ti]P_i = K_i [R_i \mid t_i], i=1,2i = 1, 2, with centers Ci=−RiTtiC_i = -R_i^{\mathsf T} t_i, and their images. A world point XX maps to the frame of camera ii by RiX+tiR_i X + t_i; the frame has XX to the right, YY down and ZZ forward. Ki=[[fx,s,cx],[0,fy,cy],[0,0,1]]K_i = [[f_x, s, c_x], [0, f_y, c_y], [0, 0, 1]] in pixels. The pixel (u,v)(u, v) has its center at the point (u,v)(u, v), with uu the column and vv the row. Lens distortion is removed first: it acts on normalized coordinates, so the image is undistorted before, or in the same inverse map as, the rectification.

Output. Two homographies H1H_1, H2H_2 and new cameras Pi′=KnRn[I∣−Ci]P'_i = K_n R_n [I \mid -C_i] with one rotation RnR_n and one intrinsic matrix KnK_n, such that Hixi∼Pi′XH_i x_i \sim P'_i X for every point XX with xi∼PiXx_i \sim P_i X, and such that P2′P'_2 sits at the baseline b=∥C2−C1∥b = \lVert C_2 - C_1 \rVert along the +X+X axis of P1′P'_1. Then a point has the same row vv in both new images, and its disparity is d=u1−u2=fxb/Zd = u_1 - u_2 = f_x b / Z, with ZZ its depth in the new frame of camera 1. The fundamental matrix of the new pair is, up to scale,

F′=(00000−1010),x2TF′x1=v1−v2.F' = \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & -1 \\ 0 & 1 & 0 \end{pmatrix}, \qquad x_2^{\mathsf T} F' x_1 = v_1 - v_2 .

Here x2TFx1=0x_2^{\mathsf T} F x_1 = 0 is the convention with the point of the second image on the left, as in Hartley and Zisserman.

The algorithm

  1. RECTIFY(K1, R1, t1, K2, R2, t2)
  2. 1C1 ← -R1ᵀ t1; C2 ← -R2ᵀ t2 ▷ the camera centers, in the world frame
  3. 2b ← ‖C2 - C1‖; if b = 0 then fail ▷ no baseline
  4. 3r1 ← (C2 - C1) / b ▷ the new X axis, along the baseline
  5. 4y ← z1 × r1, with z1 the third row of R1; if y = 0 then fail
  6. 5r2 ← y / ‖y‖; r3 ← r1 × r2 ▷ the new Y and Z axes
  7. 6Rn ← the matrix with rows r1, r2, r3; Kn ← a common K with zero skew
  8. 7H1 ← Kn Rn R1ᵀ K1⁻¹; H2 ← Kn Rn R2ᵀ K2⁻¹
  9. 8return H1, H2, Kn, Rn, b
  1. WARP(I, H, W, H') ▷ output of W columns and H' rows
  2. 1G ← H⁻¹
  3. 2for each output pixel (u, v) do
  4. 3(x, y, w) ← G (u, v, 1)
  5. 4J[v][u] ← I sampled at (x / w, y / w) by bilinear interpolation, or a fill value outside I
  6. 5return J

Lines L1 and L2 find the centers and the baseline. Line L3 makes the baseline the new XX axis, so the second camera is to the right of the first. Line L4 takes the old optical axis z1z_1 of camera 1 (the third row of R1R_1, written in the world frame) and makes the new YY axis perpendicular to both z1z_1 and the baseline. If the cameras already point along +Z+Z and the baseline is along +X+X, then z1×r1=eZ×eX=eYz_1 \times r_1 = e_Z \times e_X = e_Y, so YY stays down. Line L5 completes a right-handed frame: r3r_3 is the part of z1z_1 that is perpendicular to the baseline, so the new cameras look roughly where camera 1 looked. Line L6 chooses KnK_n; Fusiello, Trucco and Verri take the mean of K1K_1 and K2K_2 with the skew set to zero, and so does the code. Line L7 is the map "undo KiK_i, undo RiR_i, apply RnR_n, apply KnK_n", a rotation of camera ii about its center. The warp of lines L9 to L13 uses the inverse map, so every output pixel gets exactly one value, and it samples with bilinear interpolation, as in image warping.

Example

Take K=[[500,0,320],[0,500,240],[0,0,1]]K = [[500, 0, 320], [0, 500, 240], [0, 0, 1]] for both cameras. Camera 1 is at the origin and turned by 0.050.05 rad about its YY axis, R1=Ry(0.05)R_1 = R_y(0.05). Camera 2 is at C2=(0.1,0.01,0)C_2 = (0.1, 0.01, 0) m with R2=Ry(−0.05)R_2 = R_y(-0.05), so the two cameras turn toward each other, and camera 2 is 1 cm lower than camera 1. Then b=0.12+0.012=0.100499b = \sqrt{0.1^2 + 0.01^2} = 0.100499 m, and lines L3 to L6 give

Rn≈(0.9950370.0995040−0.0995030.995025−0.004979−0.0004950.0049550.999988),Kn=K.R_n \approx \begin{pmatrix} 0.995037 & 0.099504 & 0 \\ -0.099503 & 0.995025 & -0.004979 \\ -0.000495 & 0.004955 & 0.999988 \end{pmatrix}, \qquad K_n = K .

The first row is the baseline direction. The new image axes are turned by arctan⁡(0.01/0.1)≈5.71°\arctan(0.01/0.1) \approx 5.71° against the old ones, because the baseline is not level. Line L7 gives

H1≈(1.025460.102675−58.0517−0.0758750.99740324.60629.897⋅10−59.909⋅10−60.964715),H2≈(0.9614910.10267512.1348−0.1233560.99740334.8154−1.0095⋅10−49.909⋅10−61.02864).H_1 \approx \begin{pmatrix} 1.02546 & 0.102675 & -58.0517 \\ -0.075875 & 0.997403 & 24.6062 \\ 9.897 \cdot 10^{-5} & 9.909 \cdot 10^{-6} & 0.964715 \end{pmatrix}, \quad H_2 \approx \begin{pmatrix} 0.961491 & 0.102675 & 12.1348 \\ -0.123356 & 0.997403 & 34.8154 \\ -1.0095 \cdot 10^{-4} & 9.909 \cdot 10^{-6} & 1.02864 \end{pmatrix}.

Two world points, before and after:

point XX (m) x1x_1 x2x_2 H1x1H_1 x_1 H2x2H_2 x_2 dd fb/Zf b / Z
(0.2,0.1,2.0)(0.2, 0.1, 2.0) (395.398,265.157)(395.398, 265.157) (319.979,262.472)(319.979, 262.472) (372.230,257.408)(372.230, 257.408) (347.110,257.408)(347.110, 257.408) 25.12025.120 25.12025.120
(−0.3,−0.2,4.0)(-0.3, -0.2, 4.0) (307.568,215.062)(307.568, 215.062) (244.602,213.585)(244.602, 213.585) (280.190,216.361)(280.190, 216.361) (267.624,216.361)(267.624, 216.361) 12.56512.565 12.56512.565

Before the warp the rows differ by about 2.7 and 1.5 pixels. After it they are equal, and the disparity matches fb/Zf b / Z with Z=2.00037Z = 2.00037 and 3.999113.99911, the depths in the new frame. With C2=(0.1,0,0)C_2 = (0.1, 0, 0), R1=R2=IR_1 = R_2 = I and the same KK, both homographies are the identity: the pair is already rectified, and a point at depth 2.52.5 m has d=500⋅0.1/2.5=20d = 500 \cdot 0.1 / 2.5 = 20 pixels.

Correctness

The full proof is in proofs/correctness.md. It shows that RnR_n is a rotation with Rn(C2−C1)=(b,0,0)R_n (C_2 - C_1) = (b, 0, 0), that Hixi∼Pi′XH_i x_i \sim P'_i X for every point seen by camera ii, and that the two new cameras then give the same row and the disparity fxb/Zf_x b / Z for each point with Z≠0Z \ne 0. The key fact is that KneX=fxeXK_n e_X = f_x e_X for an upper triangular KnK_n, so a shift of the camera center along XX changes only the first image coordinate. The proof also shows that line L4 fails exactly when the baseline is parallel to the optical axis of camera 1, and it derives F′F'.

Proof: Correctness of calibrated stereo rectificationfull

We prove that the homographies of lines L1 to L8 rectify the pair: a point seen by both cameras has the same row in both new images, and its disparity is fxb/Zf_x b / Z. We use the conventions of the page: Xi=RiX+tiX_i = R_i X + t_i, Pi=Ki[Ri∣ti]P_i = K_i [R_i \mid t_i], Ci=−RiTtiC_i = -R_i^{\mathsf T} t_i, and ∼\sim means equal up to a nonzero scale.

Lemma 1. RnR_n is a rotation and Rn(C2−C1)=(b,0,0)TR_n (C_2 - C_1) = (b, 0, 0)^{\mathsf T}

Line L2 fails if b=0b = 0, so b>0b > 0 after it, and r1=(C2−C1)/br_1 = (C_2 - C_1)/b is a unit vector. Line L4 fails if y=z1×r1=0y = z_1 \times r_1 = 0. Otherwise yy is perpendicular to r1r_1, and r2=y/∥y∥r_2 = y / \lVert y \rVert is a unit vector perpendicular to r1r_1. Then r3=r1×r2r_3 = r_1 \times r_2 is a unit vector perpendicular to both, and (r1,r2,r3)(r_1, r_2, r_3) is a right-handed orthonormal basis. The matrix RnR_n with these rows satisfies RnRnT=IR_n R_n^{\mathsf T} = I and det⁡Rn=r1⋅(r2×r3)=r1⋅r1=1\det R_n = r_1 \cdot (r_2 \times r_3) = r_1 \cdot r_1 = 1, so it is a rotation. Its rows are orthonormal and C2−C1=br1C_2 - C_1 = b r_1, so Rn(C2−C1)=(b r1⋅r1,b r2⋅r1,b r3⋅r1)=(b,0,0)R_n (C_2 - C_1) = (b\, r_1 \cdot r_1, b\, r_2 \cdot r_1, b\, r_3 \cdot r_1) = (b, 0, 0). □\square

The test of line L4 fails exactly when z1z_1 is parallel to r1r_1, that is, when the baseline lies along the optical axis of camera 1. In this case the epipole is the principal point and no rotation can move it to infinity, so the failure is not a defect of the method.

Lemma 2. Hixi∼Pi′XH_i x_i \sim P'_i X for every point XX with xi∼PiXx_i \sim P_i X

Let XX be a point and xi∼PiX=Ki(RiX+ti)x_i \sim P_i X = K_i (R_i X + t_i). Since ti=−RiCit_i = -R_i C_i, this is xi∼KiRi(X−Ci)x_i \sim K_i R_i (X - C_i). The matrix KiK_i is invertible because fxfy≠0f_x f_y \ne 0, so

Hixi=KnRnRiTKi−1xi∼KnRnRiTRi(X−Ci)=KnRn(X−Ci)=Pi′X,H_i x_i = K_n R_n R_i^{\mathsf T} K_i^{-1} x_i \sim K_n R_n R_i^{\mathsf T} R_i (X - C_i) = K_n R_n (X - C_i) = P'_i X ,

with Pi′=KnRn[I∣−Ci]P'_i = K_n R_n [I \mid -C_i]. The scale factor is the same nonzero number on both sides, so the two homogeneous vectors give the same pixel. □\square

Lemma 2 does not use the depth of XX. That is why one homography per image serves every point of the scene: a change of rotation about a fixed center maps rays to rays.

Lemma 3. An upper triangular KnK_n maps eXe_X to a multiple of itself

Write Kn=[[fx,s,cx],[0,fy,cy],[0,0,1]]K_n = [[f_x, s, c_x], [0, f_y, c_y], [0, 0, 1]] and eX=(1,0,0)Te_X = (1, 0, 0)^{\mathsf T}. Then KneXK_n e_X is the first column, (fx,0,0)T=fxeX(f_x, 0, 0)^{\mathsf T} = f_x e_X. □\square

Theorem. Equal rows and d=fxb/Zd = f_x b / Z

Let XX be a point and Y=Rn(X−C1)=(Yx,Yy,Z)Y = R_n (X - C_1) = (Y_x, Y_y, Z) its coordinates in the new frame of camera 1, with Z≠0Z \ne 0. By Lemma 2 and Lemma 1,

H1x1∼KnY,H2x2∼KnRn(X−C1−(C2−C1))=Kn(Y−beX)=KnY−bfxeX,H_1 x_1 \sim K_n Y, \qquad H_2 x_2 \sim K_n R_n (X - C_1 - (C_2 - C_1)) = K_n (Y - b e_X) = K_n Y - b f_x e_X ,

where the last step is Lemma 3. The vector bfxeXb f_x e_X has zero second and third entries. So KnYK_n Y and Kn(Y−beX)K_n (Y - b e_X) have the same third entry ZZ and the same second entry fyYy+cyZf_y Y_y + c_y Z, and their first entries differ by bfxb f_x. Divide both by ZZ: the rows are v1=v2=fyYy/Z+cyv_1 = v_2 = f_y Y_y / Z + c_y, and the columns satisfy u1−u2=fxb/Zu_1 - u_2 = f_x b / Z. For a point in front of the new camera 1, Z>0Z > 0 and d>0d > 0. □\square

The proof uses only one KnK_n for both images. If camera 2 used cx′c'_x instead of cxc_x, its first entry would change by (cx′−cx)Z(c'_x - c_x) Z, and dd would change by the constant cx−cx′c_x - c'_x. A different fyf_y or cyc_y would break the equality of rows.

Corollary. The fundamental matrix of the new pair

The new cameras are Kn[I∣0]K_n [I \mid 0] and Kn[I∣t]K_n [I \mid t] in the new frame of camera 1, with t=−beXt = -b e_X. The fundamental matrix of x2TFx1=0x_2^{\mathsf T} F x_1 = 0 is then F′=Kn−T[t]×Kn−1F' = K_n^{-\mathsf T} [t]_\times K_n^{-1}, as on the page of the fundamental matrix. For any invertible MM and vector aa, MT[Ma]×M=det⁡(M)[a]×M^{\mathsf T} [M a]_\times M = \det(M) [a]_\times. Put M=KnM = K_n and a=eXa = e_X. Lemma 3 gives [KneX]×=fx[eX]×[K_n e_X]_\times = f_x [e_X]_\times, so fxKnT[eX]×Kn=det⁡(Kn)[eX]×f_x K_n^{\mathsf T} [e_X]_\times K_n = \det(K_n) [e_X]_\times, which gives Kn−T[eX]×Kn−1=(fx/det⁡Kn)[eX]×K_n^{-\mathsf T} [e_X]_\times K_n^{-1} = (f_x / \det K_n) [e_X]_\times. Hence

F′=−bfxdet⁡Kn[eX]×=−bfy(00000−1010),F' = -\frac{b f_x}{\det K_n} [e_X]_\times = -\frac{b}{f_y} \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & -1 \\ 0 & 1 & 0 \end{pmatrix},

and x2TF′x1=−(b/fy)(v1−v2)x_2^{\mathsf T} F' x_1 = -(b / f_y)(v_1 - v_2), which is zero exactly when the rows are equal. □\square

The warp

Lines L9 to L13 compute J(x′)=I(H−1x′)J(x') = I(H^{-1} x') for each output pixel x′x'. By Lemma 2, the pixel x′x' of the new image and the pixel H−1x′H^{-1} x' of the old image see the same ray, so JJ is the image that the new camera would record, up to the error of the interpolation and the pixels whose source is outside II, which get the fill value. Every output pixel is visited once, so the result has no holes. □\square

Complexity

  • Lines L1 to L8 work on 3×33 \times 3 matrices: a fixed number of arithmetic operations and one square root per norm, so Θ(1)\Theta(1) on the real RAM, independent of the image.
  • The warp computes one 3×33 \times 3 product, one division and one bilinear sample of four pixels per output pixel, so it costs Θ(WH)\Theta(WH) for an output of W×HW \times H pixels, in the best and the worst case. The output image takes Θ(WH)\Theta(WH) space.

A real system often combines undistortion and rectification in one lookup table of source positions, built once per camera pair. Then each new frame costs one table read and one interpolation per pixel.

Properties

  • Rotation only. Each HiH_i is KnRKi−1K_n R K_i^{-1} with a rotation R=RnRiTR = R_n R_i^{\mathsf T}. So it is exact for every scene, at every depth, and needs no knowledge of the scene.
  • Not unique. Any rotation of both new cameras about the baseline, and any common change of ff, cxc_x (the same for both) and cyc_y, keeps the rows matched. The choice of r2r_2 from z1z_1 is one choice; others reduce the distortion.
  • Disparity offset. If the two new cameras use different cxc_x, all disparities shift by cx1−cx2c_{x1} - c_{x2}, so d=fb/Z+(cx1−cx2)d = f b / Z + (c_{x1} - c_{x2}). The Middlebury data sets give this offset as a separate number.
  • Direction of the baseline. If camera 2 is to the left of camera 1, line L3 points the new XX axis to the left, and the new images are the old ones turned by about 180°180°. The disparities are still positive, but most programs then swap the two images instead.

Variants and improvements

  • Uncalibrated rectification (Hartley 1999). Find a homography H2H_2 that maps the epipole e2e_2 to the point at infinity (1,0,0)(1, 0, 0) and is close to a rigid motion near the image center. Then choose H1H_1 among the homographies that match the epipolar lines, by the linear least squares problem that makes the matched points as close as possible in uu. It needs only the fundamental matrix and point matches, and the result is defined up to a projective change of the scene.
  • Loop and Zhang (1999). Split each homography into a projective part, a similarity and a shear. Choose the projective part to make the images as close to affine as possible, and the shear to keep the right angles and the aspect ratio of the image.
  • Polar rectification (Pollefeys, Koch and Van Gool 1999). When the epipole is inside an image, as for a camera that moves forward, no homography maps it to infinity without tearing the image. Polar rectification resamples the image along the epipolar lines around the epipole instead.
  • OpenCV's stereoRectify. It splits the relative rotation into two halves, one for each camera, and then turns both to the baseline. It also has a free scaling parameter that trades the valid pixels against the black border.

When to use it

Use rectification before any dense stereo matching on two images: block matching, semi-global matching and the other methods in this group assume rectified input and search along rows. Use the calibrated method when K1K_1, K2K_2 and the pose are known, which gives depths in meters. Use the uncalibrated methods when only matches between the images are available. Skip rectification when there are more than two views; plane sweep stereo and PatchMatch stereo handle general camera positions without it.

Pitfalls

  • Forward motion. If the baseline is close to the optical axis, line L4 divides by a small ∥y∥\lVert y \rVert, and the homographies send parts of the image to infinity. Test the angle between z1z_1 and the baseline, and use polar rectification when the epipole is inside or near the image.
  • Forward mapping. Pushing each source pixel through HiH_i leaves holes and overlaps in the output. Line L9 inverts HiH_i and pulls one value per output pixel.
  • Distortion left in. A radial distortion of one pixel at the border bends the epipolar lines by about one pixel, and a matcher that searches one row then finds wrong matches. Undistort first.
  • Different KK rows. If KnK_n differs between the two images in fyf_y or cyc_y, the rows no longer match. Line L6 uses one KnK_n for both; only cxc_x may differ, and then the disparities shift by a constant.
  • Lost pixels. The new images can be larger or smaller than the old ones. Choose the output size and cxc_x, cyc_y so that the useful part of both images is inside, or many pixels of the far side of the image fall out.
  • Transposed FF. Some libraries write x1TFx2=0x_1^{\mathsf T} F x_2 = 0. Their rectified FF is the transpose of F′F' above, with the opposite sign.

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()
stereo_rectification.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stereo-rectification/. The authors are listed in prov/K5RE9X.jsonl.
"""Rectification of a calibrated stereo pair (the method of Fusiello, Trucco
and Verri, 2000).

Conventions: a world point X maps to the frame of camera i by
X_i = R_i X + t_i, the camera matrix is P_i = K_i [R_i | t_i] and the center
is C_i = -R_i^T t_i. The camera frame has X to the right, Y down and Z
forward. Pixel (u, v) has its center at the point (u, v); in code an image
is a list of rows, so the value at (u, v) is img[v][u].

The two new cameras keep their centers and share one rotation Rn and one
intrinsic matrix Kn. The new X axis points from C1 to C2, so the second
camera sits at the baseline b along +X of the first, the disparity is
d = u1 - u2 = f b / Z > 0 and the rows of the two new images match.
"""

from __future__ import annotations

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

from cvgeom import from_h, make_K
from cvla import cross, inv, matvec, mul, norm, transpose

Matrix = List[List[float]]

_EPS = 1e-12


def rectify_calibrated(K1: Sequence[Sequence[float]], R1: Sequence[Sequence[float]],
                       t1: Sequence[float], K2: Sequence[Sequence[float]],
                       R2: Sequence[Sequence[float]], t2: Sequence[float],
                       Kn: Optional[Sequence[Sequence[float]]] = None) -> Dict[str, object]:
    """Rectifying homographies H1, H2 for the cameras (K1, R1, t1) and
    (K2, R2, t2). A pixel x_i of image i maps to H_i x_i in the new image i.

    Kn is the common intrinsic matrix of the new cameras. By default it is
    the mean of K1 and K2 with zero skew. Raises ValueError if the two
    centers coincide or if the baseline is parallel to the optical axis of
    camera 1 (the new Y axis is then not defined).

    Returns a dict with H1, H2, Kn, Rn, the baseline b, the centers C1, C2
    and the new camera matrices P1, P2."""
    C1 = [-v for v in matvec(transpose(R1), t1)]  # @line L1
    C2 = [-v for v in matvec(transpose(R2), t2)]  # @line L1
    base = [a - c for a, c in zip(C2, C1)]
    b = norm(base)  # @line L2
    if b == 0.0:  # @line L2
        raise ValueError("the two camera centers coincide")
    r1 = [v / b for v in base]  # @line L3
    z1 = list(R1[2])  # @line L4
    y = cross(z1, r1)  # @line L4
    ny = norm(y)
    if ny <= _EPS:  # @line L4
        raise ValueError("the baseline is parallel to the optical axis")
    r2 = [v / ny for v in y]  # @line L5
    r3 = cross(r1, r2)  # @line L5
    Rn = [r1, r2, r3]  # @line L6
    if Kn is None:  # @line L6
        Kn = make_K((K1[0][0] + K2[0][0]) / 2.0, (K1[1][1] + K2[1][1]) / 2.0,
                    (K1[0][2] + K2[0][2]) / 2.0, (K1[1][2] + K2[1][2]) / 2.0)
    Kn = [list(map(float, row)) for row in Kn]
    KR = mul(Kn, Rn)
    H1 = mul(mul(KR, transpose(R1)), inv(K1))  # @line L7
    H2 = mul(mul(KR, transpose(R2)), inv(K2))  # @line L7
    P1 = [row + [-sum(row[k] * C1[k] for k in range(3))] for row in KR]
    P2 = [row + [-sum(row[k] * C2[k] for k in range(3))] for row in KR]
    return {"H1": H1, "H2": H2, "Kn": Kn, "Rn": Rn, "b": b,  # @line L8
            "C1": C1, "C2": C2, "P1": P1, "P2": P2}


def apply_homography(H: Sequence[Sequence[float]], uv: Sequence[float]) -> List[float]:
    """The pixel H (u, v, 1), dehomogenized."""
    return from_h(matvec(H, [float(uv[0]), float(uv[1]), 1.0]))


def bilinear(img: Sequence[Sequence[float]], x: float, y: float, fill: float = 0.0) -> float:
    """The bilinear interpolation of img at the point (x, y), with pixel
    centers at integer points. A point outside [0, W - 1] x [0, H - 1]
    gives fill."""
    h, w = len(img), len(img[0])
    if not (0.0 <= x <= w - 1 and 0.0 <= y <= h - 1):
        return fill
    x0 = min(int(math.floor(x)), max(w - 2, 0))
    y0 = min(int(math.floor(y)), max(h - 2, 0))
    ax, ay = x - x0, y - y0
    x1, y1 = min(x0 + 1, w - 1), min(y0 + 1, h - 1)
    top = (1 - ax) * img[y0][x0] + ax * img[y0][x1]
    bot = (1 - ax) * img[y1][x0] + ax * img[y1][x1]
    return (1 - ay) * top + ay * bot


def warp_image(img: Sequence[Sequence[float]], H: Sequence[Sequence[float]],
               out_w: int, out_h: int, fill: float = 0.0) -> List[List[float]]:
    """The image J with J(x') = img(H^-1 x'), by inverse mapping and
    bilinear interpolation. J has out_w columns and out_h rows."""
    Hi = inv(H)  # @line L9
    out = []
    for v in range(out_h):  # @line L10
        row = []
        for u in range(out_w):  # @line L10
            p = matvec(Hi, [float(u), float(v), 1.0])  # @line L11
            if p[2] == 0.0:
                row.append(fill)
                continue
            row.append(bilinear(img, p[0] / p[2], p[1] / p[2], fill))  # @line L12
        out.append(row)
    return out  # @line L13


def rectified_fundamental(Kn: Sequence[Sequence[float]], b: float) -> Matrix:
    """F = Kn^-T [t]_x Kn^-1 of the rectified pair, with t = (-b, 0, 0),
    the translation from the frame of camera 1 to the frame of camera 2."""
    tx = [[0.0, 0.0, 0.0], [0.0, 0.0, b], [0.0, -b, 0.0]]
    Ki = inv(Kn)
    return mul(mul(transpose(Ki), tx), Ki)
test_stereo_rectification.py 207 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stereo-rectification/. The authors are listed in prov/K5RE9X.jsonl.

import math
import random

import pytest

from cvgeom import axis_angle_to_R, camera_matrix, make_K, project, rot_y
from cvla import det, matvec, mul, norm, transpose
from stereo_rectification import (
    apply_homography,
    bilinear,
    rectified_fundamental,
    rectify_calibrated,
    warp_image,
)


def pose(R, C):
    """(R, t) of a camera with rotation R and center C."""
    return R, [-v for v in matvec(R, C)]


def random_rig(rng):
    K1 = make_K(rng.uniform(400, 600), rng.uniform(400, 600), rng.uniform(150, 170), rng.uniform(110, 130))
    K2 = make_K(rng.uniform(400, 600), rng.uniform(400, 600), rng.uniform(150, 170), rng.uniform(110, 130))
    R1 = axis_angle_to_R([rng.gauss(0, 1) for _ in range(3)], rng.uniform(0, 0.2))
    R2 = axis_angle_to_R([rng.gauss(0, 1) for _ in range(3)], rng.uniform(0, 0.2))
    C1 = [rng.uniform(-1, 1) for _ in range(3)]
    C2 = [C1[0] + rng.uniform(0.05, 0.5), C1[1] + rng.uniform(-0.03, 0.03), C1[2] + rng.uniform(-0.03, 0.03)]
    R1, t1 = pose(R1, C1)
    R2, t2 = pose(R2, C2)
    return K1, R1, t1, K2, R2, t2


def points_in_front(rng, R, C, n):
    """n points 2 to 6 units in front of the camera (R, C)."""
    out = []
    Rt = transpose(R)
    for _ in range(n):
        z = rng.uniform(2.0, 6.0)
        xc = [rng.uniform(-0.3, 0.3) * z, rng.uniform(-0.3, 0.3) * z, z]
        out.append([a + c for a, c in zip(matvec(Rt, xc), C)])
    return out


def normalize_f(F):
    s = norm(F)
    G = [[x / s for x in row] for row in F]
    if G[2][1] < 0:
        G = [[-x for x in row] for row in G]
    return G


def test_rows_match_and_disparity_is_f_b_over_z():
    rng = random.Random(1)
    for _ in range(20):
        K1, R1, t1, K2, R2, t2 = random_rig(rng)
        r = rectify_calibrated(K1, R1, t1, K2, R2, t2)
        P1, P2 = camera_matrix(K1, R1, t1), camera_matrix(K2, R2, t2)
        Rn, Kn, b, C1 = r["Rn"], r["Kn"], r["b"], r["C1"]
        for X in points_in_front(rng, R1, C1, 15):
            x1 = apply_homography(r["H1"], project(P1, X))
            x2 = apply_homography(r["H2"], project(P2, X))
            Zn = matvec(Rn, [a - c for a, c in zip(X, C1)])[2]
            assert abs(x1[1] - x2[1]) <= 1e-8
            d = x1[0] - x2[0]
            assert d > 0
            assert abs(d - Kn[0][0] * b / Zn) <= 1e-8 * max(1.0, d)


def test_homography_equals_new_camera():
    rng = random.Random(2)
    K1, R1, t1, K2, R2, t2 = random_rig(rng)
    r = rectify_calibrated(K1, R1, t1, K2, R2, t2)
    P1, P2 = camera_matrix(K1, R1, t1), camera_matrix(K2, R2, t2)
    for X in points_in_front(rng, R1, r["C1"], 10):
        for H, P, Pn in ((r["H1"], P1, r["P1"]), (r["H2"], P2, r["P2"])):
            a = apply_homography(H, project(P, X))
            c = project(Pn, X)
            assert max(abs(p - q) for p, q in zip(a, c)) <= 1e-8


def test_new_rotation_is_a_rotation_with_x_along_the_baseline():
    rng = random.Random(3)
    for _ in range(10):
        K1, R1, t1, K2, R2, t2 = random_rig(rng)
        r = rectify_calibrated(K1, R1, t1, K2, R2, t2)
        Rn = r["Rn"]
        RtR = mul(transpose(Rn), Rn)
        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(Rn) - 1.0) <= 1e-12
        base = [a - c for a, c in zip(r["C2"], r["C1"])]
        assert matvec(Rn, base)[0] == pytest.approx(r["b"], rel=1e-12)
        assert abs(matvec(Rn, base)[1]) <= 1e-12 and abs(matvec(Rn, base)[2]) <= 1e-12
        # the new optical axis keeps a positive component along the old one
        assert sum(p * q for p, q in zip(Rn[2], R1[2])) > 0


def test_rectified_fundamental_matrix():
    rng = random.Random(4)
    K1, R1, t1, K2, R2, t2 = random_rig(rng)
    r = rectify_calibrated(K1, R1, t1, K2, R2, t2)
    F = normalize_f(rectified_fundamental(r["Kn"], r["b"]))
    s = 1.0 / math.sqrt(2.0)
    target = [[0.0, 0.0, 0.0], [0.0, 0.0, -s], [0.0, s, 0.0]]
    assert max(abs(F[i][j] - target[i][j]) for i in range(3) for j in range(3)) <= 1e-12
    P1, P2 = camera_matrix(K1, R1, t1), camera_matrix(K2, R2, t2)
    for X in points_in_front(rng, R1, r["C1"], 10):
        x1 = apply_homography(r["H1"], project(P1, X)) + [1.0]
        x2 = apply_homography(r["H2"], project(P2, X)) + [1.0]
        assert abs(sum(x2[i] * sum(F[i][j] * x1[j] for j in range(3)) for i in range(3))) <= 1e-9


def test_check_value_depth():
    K = make_K(500, 500, 320, 240)
    I = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    R1, t1 = pose(I, [0.0, 0.0, 0.0])
    R2, t2 = pose(I, [0.1, 0.0, 0.0])
    r = rectify_calibrated(K, R1, t1, K, R2, t2)
    for H in (r["H1"], r["H2"]):
        assert all(abs(H[i][j] - I[i][j]) <= 1e-12 for i in range(3) for j in range(3))
    X = [0.3, -0.2, 2.5]
    x1 = project(r["P1"], X)
    x2 = project(r["P2"], X)
    assert x1[0] - x2[0] == pytest.approx(20.0, abs=1e-12)
    assert 500 * 0.1 / (x1[0] - x2[0]) == pytest.approx(2.5, abs=1e-12)


def test_worked_example():
    K = make_K(500, 500, 320, 240)
    R1, t1 = pose(rot_y(0.05), [0.0, 0.0, 0.0])
    R2, t2 = pose(rot_y(-0.05), [0.1, 0.0, 0.0])
    r = rectify_calibrated(K, R1, t1, K, R2, t2)
    X = [0.2, 0.1, 2.0]
    x1 = project(camera_matrix(K, R1, t1), X)
    x2 = project(camera_matrix(K, R2, t2), X)
    y1 = apply_homography(r["H1"], x1)
    y2 = apply_homography(r["H2"], x2)
    assert abs(y1[1] - y2[1]) <= 1e-9
    assert y1[0] - y2[0] == pytest.approx(25.0, abs=1e-9)


def test_degenerate_rigs():
    K = make_K(500, 500, 320, 240)
    I = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    R1, t1 = pose(I, [0.0, 0.0, 0.0])
    R2, t2 = pose(I, [0.0, 0.0, 0.0])
    with pytest.raises(ValueError):
        rectify_calibrated(K, R1, t1, K, R2, t2)
    R2, t2 = pose(I, [0.0, 0.0, 0.5])
    with pytest.raises(ValueError):
        rectify_calibrated(K, R1, t1, K, R2, t2)


def test_baseline_to_the_left_still_gives_positive_disparity():
    # camera 2 to the left of camera 1: the new X axis points left, and the
    # new frame is the old one turned by pi about the optical axis.
    K = make_K(500, 500, 320, 240)
    I = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    R1, t1 = pose(I, [0.0, 0.0, 0.0])
    R2, t2 = pose(I, [-0.1, 0.0, 0.0])
    r = rectify_calibrated(K, R1, t1, K, R2, t2)
    # Rn rotates by pi about the optical axis: the image turns upside down
    assert r["Rn"][2] == pytest.approx([0.0, 0.0, 1.0], abs=1e-12)
    assert r["Rn"][0] == pytest.approx([-1.0, 0.0, 0.0], abs=1e-12)
    X = [0.1, 0.2, 2.5]
    d = project(r["P1"], X)[0] - project(r["P2"], X)[0]
    assert d == pytest.approx(20.0, abs=1e-9)


def test_bilinear_and_warp():
    rng = random.Random(5)
    img = [[rng.randint(0, 255) for _ in range(9)] for _ in range(7)]
    I = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    out = warp_image(img, I, 9, 7)
    assert all(abs(out[v][u] - img[v][u]) <= 1e-12 for v in range(7) for u in range(9))
    T = [[1.0, 0.0, 2.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]]
    out = warp_image(img, T, 9, 7, fill=-1.0)
    for v in range(7):
        for u in range(9):
            if u >= 2 and v >= 1:
                assert abs(out[v][u] - img[v - 1][u - 2]) <= 1e-12
            else:
                assert out[v][u] == -1.0
    assert bilinear([[0, 10], [20, 30]], 0.5, 0.5) == pytest.approx(15.0)
    assert bilinear([[0, 10], [20, 30]], 1.0, 1.0) == pytest.approx(30.0)
    assert bilinear([[0, 10], [20, 30]], 1.5, 0.0, fill=7.0) == 7.0


def test_warp_rectifies_a_synthetic_dot():
    # a bright dot at a 3D point lands on the same row in both rectified images
    K = make_K(40, 40, 16, 12)
    R1, t1 = pose(rot_y(0.04), [0.0, 0.0, 0.0])
    R2, t2 = pose(rot_y(-0.04), [0.2, 0.02, 0.0])
    r = rectify_calibrated(K, R1, t1, K, R2, t2)
    X = [0.1, 0.05, 2.0]
    rows = []
    for (R, t), H in (((R1, t1), r["H1"]), ((R2, t2), r["H2"])):
        u, v = project(camera_matrix(K, R, t), X)
        img = [[math.exp(-((x - u) ** 2 + (y - v) ** 2) / 2.0) for x in range(32)] for y in range(24)]
        out = warp_image(img, H, 32, 24)
        best = max((out[y][x], y, x) for y in range(24) for x in range(32))
        rows.append(best[1])
        assert best[0] > 0.5
    assert rows[0] == rows[1]

History

Photogrammetry resampled image pairs to epipolar geometry long before computer vision did. In computer vision, Hartley (1999) and Loop and Zhang (1999) showed how to rectify from the fundamental matrix alone and how to choose the homographies to keep the images close to the originals. Fusiello, Trucco and Verri (2000) gave the calibrated method of this page, short enough to fit in 22 lines of MATLAB, and Pollefeys, Koch and Van Gool (1999) gave polar rectification for the case that a homography cannot handle. Hartley and Zisserman treat rectification in Section 11.12 of their book.

References

  1. Andrea Fusiello, Emanuele Trucco and Alessandro Verri, A compact algorithm for rectification of stereo pairs, Machine Vision and Applications 12(1), 2000, 16-22, the whole paper (the new rotation from the baseline and the old optical axis, the common intrinsic matrix, and the rectifying transformations)
  2. Richard I. Hartley, Theory and practice of projective rectification, International Journal of Computer Vision 35(2), 1999, 115-127, the whole paper (rectification from the fundamental matrix, the epipole mapped to infinity, and the matching homography)
  3. Charles Loop and Zhengyou Zhang, Computing rectifying homographies for stereo vision, IEEE Conference on Computer Vision and Pattern Recognition, 1999, volume 1, 125-131 (also Microsoft Research technical report MSR-TR-99-21), the whole paper (the split of each homography into a projective, a similarity and a shearing part)
  4. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 11.12, Image rectification; Section 9.3 for the fundamental matrix of a pure translation
  5. Marc Pollefeys, Reinhard Koch and Luc Van Gool, A simple and efficient rectification method for general motion, IEEE International Conference on Computer Vision, 1999, the whole paper (polar rectification, for an epipole inside the image)
  6. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 12, Depth estimation (the section on epipolar geometry and rectification)

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