Module contents
Lesson 14 of 33Core 120 min

Camera geometry: projection, calibration and epipolar geometry

Build pinhole camera geometry, lens calibration, homographies and epipolar constraints, then estimate two-view pose and triangulate points.

After this lesson you can

  • Project 3D points with pinhole and radial-tangential distortion models and invert pixels to rays.
  • Calibrate a camera from board images using Zhang's method and analyze reprojection error.
  • Derive the epipolar constraint and estimate F using the normalized eight-point algorithm.
  • Implement RANSAC and calculate iterations for a given outlier fraction.
  • Recover relative pose from E and triangulate, selecting points in front of both cameras.

Before you start

From pixels to rays

A camera transforms world positions into pixels, but one image does not say how far away a point is. All points on one ray have the same projection. Recovering depth requires another observation, an additional measurement or an assumption about the scene. Before reconstruction, specify which coordinates enter each operation.

InteractiveDistance and distortion change the image
  • Cube / distorted image
  • Rays / ideal image
1.5
3.0
-0.50
0.00
0.00
0.00
Approximate central scale f / Z0.500
Principal point0.00
The cube and rays appear in space, with projection at right or below. Change focal length, pose, principal point and distortion: grey marks the ideal image and blue the distorted image. Equations below describe the model.

The graphic uses an explicit model, not lens measurements: a cube of edge 1.2, equal focal lengths on both axes and first-order radial distortion. Moving the cube farther away reduces apparent size, as does reducing focal length. Examining a single point does not remove this ambiguity. Rays reach its vertices and distortion affects only the image drawing.

Pinhole projection and reference frames

The pose above maps world to camera, rather than giving camera pose in the world. If its world centre is C\vb{C}, then t=−RC\vb{t}=-\mat{R}\vb{C}. Homogeneous rigid motion and the transformation tree compose this change with the rest of the robot. To invert an ideal pixel, K−1p~\mat{K}\inv\tilde{\vb{p}} gives a camera-frame direction; in world coordinates the ray is C+λR⊤K−1p~\vb{C}+\lambda\mat{R}\T\mat{K}\inv\tilde{\vb{p}}, with λ>0\lambda>0. Depth remains undetermined.

A lens is not a pinhole

Lens distortion modifies normalized coordinates before multiplication by K\mat{K}. For r2=x2+y2r^2=x^2+y^2, the usual radial and tangential model is

xd=x(1+k1r2+k2r4+k3r6)+2p1xy+p2(r2+2x2),yd=y(1+k1r2+k2r4+k3r6)+p1(r2+2y2)+2p2xy.\begin{aligned} x_d&=x(1+k_1r^2+k_2r^4+k_3r^6)+2p_1xy+p_2(r^2+2x^2),\\ y_d&=y(1+k_1r^2+k_2r^4+k_3r^6)+p_1(r^2+2y^2)+2p_2xy. \end{aligned}

The radial term preserves direction from the normalized centre and changes radius; the tangential term need not. Lines not passing through the centre may curve. Inverting distortion requires solving a nonlinear equation, normally iteratively, and the model may cease to be injective outside its useful domain. A fisheye lens usually needs a specific angular model rather than extrapolating a radial polynomial to extreme angles. The OpenCV guide details the calibration model and coefficients.

Calibration with a plane

Camera calibration estimates intrinsics, distortion and each view’s pose from correspondences between known points and their pixels. In Zhang’s method, the board lies at Z=0Z=0. For each view without distortion, its plane and image are related by H∼K[r1 r2 t]\mat{H}\sim\mat{K}[\vb{r}_1\ \vb{r}_2\ \vb{t}]. If B=K−⊤K−1\mat{B}=\mat{K}^{-\T}\mat{K}\inv and hi\vb{h}_i is column ii of H\mat{H}, orthogonality and equal norms of the first two rotation columns give two linear constraints:

h1⊤Bh2=0,h1⊤Bh1−h2⊤Bh2=0.\vb{h}_1\T\mat{B}\vb{h}_2=0,\qquad \vb{h}_1\T\mat{B}\vb{h}_1-\vb{h}_2\T\mat{B}\vb{h}_2=0.

Several views with different orientations produce a homogeneous system for the six independent elements of B\mat{B}, up to scale. After recovering K\mat{K} and poses, estimate distortion and refine all parameters by minimizing pixel reprojection error. Levenberg-Marquardt optimization is one way to solve this nonlinear problem. If every view is nearly frontal, constraints can be ill-conditioned. Global RMS alone does not reveal a pattern of errors in image corners: inspect residuals by view and region too.

For the closed-form solution, stack each view’s two equations into a matrix acting on the six independent coefficients of B\mat{B}; its last right singular vector gives the homogeneous solution. With five general intrinsic degrees of freedom, three generic views provide six equations for those five degrees. Two views may suffice with an additional independent intrinsic assumption. Choose sign and scale so B\mat{B} is positive definite; its factorization B=LL⊤\mat{B}=\mat{L}\mat{L}\T recovers K=L−⊤\mat{K}=\mat{L}^{-\T} and allows normalization to K33=1K_{33}=1. With noise, a non-positive-definite linear solution signals degenerate data or failed estimation, not a valid camera matrix.

For each homography, the first two columns of K−1H\mat{K}\inv\mat{H} are proportional to r1\vb{r}_1 and r2\vb{r}_2, and the third to t\vb{t}. Fix a common scale, form r3=r1×r2\vb{r}_3=\vb{r}_1\times\vb{r}_2 and project the approximate matrix to SO(3)SO(3) before refinement. The board needs known dimensions for translation in metric units; pixel intrinsics do not require that scale. If resolution changes or the image is cropped, transform focal lengths and principal point consistently rather than reusing K\mat{K} unchanged.

Homography and DLT

A homography is an invertible planar projective transformation, p~′∼Hp~\tilde{\vb{p}}'\sim\mat{H}\tilde{\vb{p}}, with rank-three H\mat{H} defined up to scale. If the scene is planar, image correspondences on that plane obey a homography. Points at any depth also obey one under pure rotation: H=K2RK1−1\mat{H}=\mat{K}_2\mat{R}\mat{K}_1\inv.

DLT writes p~′×Hp~=0\tilde{\vb{p}}'\times\mat{H}\tilde{\vb{p}}=0. Each pair contributes two independent equations in the nine entries of H\mat{H}. At least four pairs in a nondegenerate configuration determine the solution up to scale. Stack equations into Ah=0\mat{A}\vb{h}=0 and take the right singular vector associated with the smallest singular value. Normalizing coordinates before fitting and undoing normalization afterwards improves conditioning. SVD finds that approximate null-space direction.

Four collinear correspondences do not determine a general planar homography. With noise, use more pairs distributed across the plane and check geometric error, not only the algebraic residual of Ah\mat{A}\vb{h}. A homography fitted to a wall need not describe an object in front: under translation its parallax depends on depth. Under pure rotation, conversely, all rays change by the same angular transformation and the homography no longer depends on depth.

Two cameras and epipolar geometry

For the second camera use X2=RX1+t\vb{X}_2=\mat{R}\vb{X}_1+\vb{t}. Normalized rays x1\vb{x}_1 and x2\vb{x}_2, together with baseline t\vb{t}, lie in a plane. Epipolar geometry expresses their coplanarity:

x2⊤[t]×R⏟Ex1=0,p~2⊤K2−⊤EK1−1⏟Fp~1=0.\vb{x}_2\T\underbrace{[\vb{t}]_\times\mat{R}}_{\mat{E}}\vb{x}_1=0, \qquad \tilde{\vb{p}}_2\T\underbrace{\mat{K}_2^{-\T}\mat{E}\mat{K}_1\inv}_{\mat{F}}\tilde{\vb{p}}_1=0.

The skew-symmetric matrix [t]×[\vb{t}]_\times satisfies [t]×a=t×a[\vb{t}]_\times\vb{a}=\vb{t}\times\vb{a}. The inner product above is zero because x2\vb{x}_2 lies in the plane generated by t\vb{t} and Rx1\mat{R}\vb{x}_1. In the second image, Fp~1\mat{F}\tilde{\vb{p}}_1 gives coefficients of the line containing the match; the epipole is the other camera centre’s projection and satisfies F⊤e2=0\mat{F}\T\vb{e}_2=0. With translation parallel to the image plane, the epipole can be at infinity and lines parallel. Coordinates must be undistorted before applying these equations.

InteractiveA family of epipolar lines
  • Point in first image
  • Line in second image
  • Epipole, if visible
0.50
0.40
1.0
0.80
Horizontal epipole−1.25
Coefficient a−0.32
Coefficient b1.40
Coefficient c−0.40
Drag the point in the first image and change translation. The second shows its epipolar line for identical cameras, no rotation and normalized coordinates. Move the point: lines pass through the same epipole. With zero axial translation they are parallel.

If t≠0\vb{t}\ne0, singular values of E\mat{E} are (∥t∥,∥t∥,0)(\norm{\vb{t}},\norm{\vb{t}},0): [t]×⊤[t]×=∥t∥2I−tt⊤[\vb{t}]_\times\T[\vb{t}]_\times=\norm{\vb{t}}^2\mat{I}-\vb{t}\vb{t}\T, whose eigenvalues are ∥t∥2,∥t∥2,0\norm{\vb{t}}^2,\norm{\vb{t}}^2,0. Multiplying by a rotation does not change singular values. Under pure rotation t=0\vb{t}=0, E=0\mat{E}=0 and the constraint identifies neither translation nor depth.

Eight points and pose

The normalized eight-point algorithm centres each coordinate set and scales it so mean distance to the origin is 2\sqrt{2}. Stack equations x2⊤Fx1=0\vb{x}_2\T\mat{F}\vb{x}_1=0, calculate the homogeneous solution by SVD and zero the smallest singular value of the resulting 3×33\times3 matrix. Then denormalize: F=T2⊤FnT1\mat{F}=\mat{T}_2\T\mat{F}_n\mat{T}_1. Initial algebraic estimation and rank enforcement do not directly minimize geometric error, so refinement is useful. Hartley explains why normalization changes conditioning.

With calibrated cameras, E=K2⊤FK1\mat{E}=\mat{K}_2\T\mat{F}\mat{K}_1. Project its SVD to singular values (a,a,0)(a,a,0), with aa the mean of the first two. Decomposition produces two rotations and two translation signs, four combinations. Translation scale is indeterminate in monocular vision. Triangulate for each combination and choose the one placing most points in front of both cameras, the cheirality test; noise or little parallax can make this decision unstable.

If E=Udiag⁡(a,a,0)V⊤\mat{E}=\mat{U}\diag(a,a,0)\mat{V}\T and signs of U\mat{U} and V\mat{V} are chosen to make rotations proper, take

W=[0−10100001],R∈{UWV⊤,  UW⊤V⊤},t∈{+u3,−u3}.\mat{W}=\begin{bmatrix}0&-1&0\\1&0&0\\0&0&1\end{bmatrix},\qquad \mat{R}\in\{\mat{U}\mat{W}\mat{V}\T,\;\mat{U}\mat{W}\T\mat{V}\T\},\qquad \vb{t}\in\{+\vb{u}_3,-\vb{u}_3\}.

The four pairs are algebraic candidates, not four physically valid scenes under ideal cheirality and generic configuration. When almost all points are very far away or motion is nearly pure rotation, deciding the sign can be difficult. A planar scene or critical correspondence configuration can also leave F\mat{F} underdetermined: normalization does not fix missing geometric information.

RANSAC and triangulation

RANSAC repeats minimal samples, fits a model and counts compatible correspondences. If each independent sample of size ss is entirely correct with probability wsw^s, the probability at least one of NN samples is correct is 1−(1−ws)N1-(1-w^s)^N. To reach probability pp, it suffices that

N≥log⁡(1−p)log⁡(1−ws).N\geq\frac{\log(1-p)}{\log(1-w^s)}.

This formula assumes independent samples and representative proportion ww; an outlier-free sample alone guarantees neither an accurate nor nondegenerate model. For w=0.6w=0.6, s=8s=8 and p=0.99p=0.99, round up. After choosing consensus, re-estimate with all its points and refine. Sampson distance, a first-order approximation to geometric error, is preferable to comparing unnormalized algebraic residuals; the threshold’s units must match the coordinates used.

The expression wsw^s is exact for independent draws with replacement from a population with correct fraction ww. If ss elements are drawn without replacement from nn pairs, mm of them correct, the exact probability is (ms)/(ns)\binom{m}{s}/\binom{n}{s} when m≥sm\ge s. It can be lower than wsw^s for small samples. In real data ww is unknown and an overly permissive consensus can overestimate it. RANSAC also does not replace the detectors and descriptors generating candidates: poor coverage or repetitive matches degrade estimation.

InteractiveA sample, a model and its consensus
  • Compatible observation
  • Observation outside threshold
  • Minimal sample
  • Prediction
1
6
0.08
Consensus for this sample4
Approximate iterations at 99%13
Generate 24 planar points with a fixed homography, small noise and an adjustable number of false correspondences. Each iteration selects four pairs and fits a homography; empty circles are its predictions. Iteration count uses the w⁴ approximation, while the four-point sample is without replacement within each iteration.

Triangulation seeks the 3D point compatible with two projections. In linear form each view contributes rows uP3,:−P1,:u\mat{P}_{3,:}-\mat{P}_{1,:} and vP3,:−P2,:v\mat{P}_{3,:}-\mat{P}_{2,:}; SVD of the stacked system gives the homogeneous point. With noise, rays do not intersect exactly and minimizing total reprojection error is useful.

For rectified cameras with focal length ff, baseline bb and disparity d=u1−u2d=u_1-u_2, Z=fb/dZ=fb/d. If disparity uncertainty is small, first-order propagation gives σZ≈fbσd/d2=Z2σd/(fb)\sigma_Z\approx fb\sigma_d/d^2=Z^2\sigma_d/(fb). This is a local approximation, not a reliable distribution when dd is near zero. Increasing distance or reducing baseline therefore destabilizes depth even with well-measured pixels.

InteractiveDepth becomes uncertain
  • Central rays
  • Pixel-perturbation region
0.20
1.0
5.0
Disparity (px)20.00
Local deviation of Z (m)0.250
Disparity σ / disparity0.050
The plan view shows two cameras and central rays. The region spans combinations of shifts in each observation up to σ/√2 pixels; it is not a confidence interval. Below is local deviation for focal length 500 pixels. Reduce baseline or move the point away: the noise-to-disparity ratio indicates when the local approximation becomes questionable.
[ ]Projection and iteration countBrowser
import numpy as np
import math

def proyecta(X, K, R, t, k1=0.0):
    Xc = np.asarray(X) @ R.T + t
    if np.any(Xc[:, 2] <= 0):
        raise ValueError("Se requieren puntos delante de la cámara")
    xy = Xc[:, :2] / Xc[:, 2, None]
    r2 = np.sum(xy * xy, axis=1, keepdims=True)
    dist = xy * (1 + k1 * r2)
    h = np.column_stack((dist, np.ones(len(dist)))) @ K.T
    return h[:, :2] / h[:, 2, None]

K = np.array([[500., 0., 320.], [0., 500., 240.], [0., 0., 1.]])
print("píxel ideal:", proyecta([[1., 0.5, 5.]], K, np.eye(3), np.zeros(3)))
print("iteraciones:", math.ceil(math.log(0.01) / math.log(1 - 0.6**8)))

To undo distortion, the next Newton implementation solves the forward radial and tangential equation at each point. It checks the residual and declares failure if the Jacobian is singular or it does not converge; a numerical solution does not guarantee global uniqueness. The example works in a small domain where inversion is well conditioned.

[ ]Distortion and local inversionBrowser
def distorsiona(xy, k1, k2, p1, p2, k3=0.):
    x, y = np.asarray(xy, dtype=float)
    r2 = x*x+y*y
    radial = 1+k1*r2+k2*r2**2+k3*r2**3
    return np.array([x*radial+2*p1*x*y+p2*(r2+2*x*x),
                     y*radial+p1*(r2+2*y*y)+2*p2*x*y])

def desdistorsiona(observado, coef, tol=1e-12, max_iter=30):
    objetivo = np.asarray(observado, dtype=float)
    x = objetivo.copy()
    h = 1e-6
    for _ in range(max_iter):
        r = distorsiona(x, *coef)-objetivo
        if np.linalg.norm(r) < tol:
            return x
        J = np.column_stack([(distorsiona(x+h*np.eye(2)[j],*coef)-distorsiona(x-h*np.eye(2)[j],*coef))/(2*h) for j in range(2)])
        x -= np.linalg.solve(J, r)
    raise ValueError('La inversión no convergió')

coef = (-0.15, 0.03, 0.002, -0.001, 0.)
ideal = np.array([0.4, -0.3])
dist = distorsiona(ideal, *coef)
print('distorsionado:', dist.round(6))
print('error tras invertir:', np.linalg.norm(desdistorsiona(dist, coef)-ideal))

Lab: two-view estimation

We work with points in rows. For fitting F\mat{F} each design-matrix row is (u′u,u′v,u′,v′u,v′v,v′,u,v,1)(u'u,u'v,u',v'u,v'v,v',u,v,1). In the minimal case the matrix is 8×98\times9: full SVD is needed to obtain its ninth right vector, which generates the null space. Homography fitting uses the same principle and normalization.

[ ]DLT and normalized eight pointsBrowser
def homogeneos(x):
    return np.column_stack([x, np.ones(len(x))])

def normaliza(x):
    x = np.asarray(x, dtype=float)
    centro = x.mean(axis=0)
    media = np.linalg.norm(x - centro, axis=1).mean()
    if media < 1e-12:
        raise ValueError("Puntos coincidentes")
    s = np.sqrt(2) / media
    T = np.array([[s, 0, -s * centro[0]], [0, s, -s * centro[1]], [0, 0, 1.]])
    return (homogeneos(x) @ T.T)[:, :2], T

def eight_point_normalized(x1, x2):
    if len(x1) < 8 or len(x1) != len(x2):
        raise ValueError("Se necesitan al menos ocho pares")
    a, T1 = normaliza(x1)
    b, T2 = normaliza(x2)
    u, v = a.T
    up, vp = b.T
    A = np.column_stack([up*u, up*v, up, vp*u, vp*v, vp, u, v, np.ones(len(u))])
    if np.linalg.matrix_rank(A) < 8:
        raise ValueError("Configuración degenerada")
    F = np.linalg.svd(A, full_matrices=True)[2][-1].reshape(3, 3)
    U, s, Vt = np.linalg.svd(F)
    s[-1] = 0
    F = T2.T @ (U @ np.diag(s) @ Vt) @ T1
    return F / np.linalg.norm(F)

def homografia_dlt(x1, x2):
    if len(x1) < 4 or len(x1) != len(x2):
        raise ValueError("Se necesitan al menos cuatro pares")
    a, T1 = normaliza(x1)
    b, T2 = normaliza(x2)
    filas = []
    for (x, y), (u, v) in zip(a, b):
        filas.extend([[-x, -y, -1, 0, 0, 0, u*x, u*y, u],
                      [0, 0, 0, -x, -y, -1, v*x, v*y, v]])
    A = np.array(filas)
    if np.linalg.matrix_rank(A) < 8:
        raise ValueError("Configuración degenerada")
    Hn = np.linalg.svd(A, full_matrices=True)[2][-1].reshape(3, 3)
    H = np.linalg.solve(T2, Hn @ T1)
    return H / np.linalg.norm(H)

def sampson(F, x1, x2):
    a, b = homogeneos(x1), homogeneos(x2)
    Fa, Ftb = a @ F.T, b @ F
    numerador = np.sum(b * Fa, axis=1)**2
    denominador = np.sum(Fa[:, :2]**2, axis=1) + np.sum(Ftb[:, :2]**2, axis=1)
    return numerador / np.maximum(denominador, 1e-30)

An independent check constructs a known homography and compares reprojected positions. Fitting does not recover absolute scale for H\mat{H}, so directly comparing unnormalized entries can give a false error.

[ ]Check DLT homographyBrowser
plano = np.array([[-1.,-1.],[-1.,1.],[1.,-1.],[1.,1.],[0.2,0.4],[-0.4,0.3]])
H_true = np.array([[1.1, 0.15, 0.2], [-0.1, 0.9, -0.3], [0.05, -0.08, 1.]])
dest_h = homogeneos(plano) @ H_true.T
dest = dest_h[:,:2] / dest_h[:,2,None]
H_est = homografia_dlt(plano, dest)
pred_h = homogeneos(plano) @ H_est.T
pred = pred_h[:,:2] / pred_h[:,2,None]
print('máximo error de reproyección:', np.max(np.linalg.norm(pred-dest,axis=1)))

RANSAC rejects degenerate samples. The following threshold is in pixels for the square root of Sampson distance; the method compares its square to avoid unnecessary roots. Final estimation fits the consensus, but this code performs no nonlinear refinement.

[ ]Consensus and triangulationBrowser
def ransac_f(x1, x2, n_iter, umbral, semilla=0):
    rng = np.random.default_rng(semilla)
    mejor = np.zeros(len(x1), dtype=bool)
    for _ in range(n_iter):
        ids = rng.choice(len(x1), 8, replace=False)
        try:
            F = eight_point_normalized(x1[ids], x2[ids])
        except (ValueError, np.linalg.LinAlgError):
            continue
        consenso = sampson(F, x1, x2) < umbral**2
        if consenso.sum() > mejor.sum():
            mejor = consenso
    if mejor.sum() < 8:
        raise ValueError("No se encontró un consenso suficiente")
    return eight_point_normalized(x1[mejor], x2[mejor]), mejor

def triangula(P1, P2, x1, x2):
    puntos = []
    for (u, v), (up, vp) in zip(x1, x2):
        A = np.stack([u*P1[2]-P1[0], v*P1[2]-P1[1],
                      up*P2[2]-P2[0], vp*P2[2]-P2[1]])
        X = np.linalg.svd(A)[2][-1]
        if abs(X[3]) < 1e-12:
            raise ValueError("Punto en el infinito")
        puntos.append(X[:3] / X[3])
    return np.array(puntos)

The next scene has varying depth, Gaussian noise and deliberately substituted correspondences. It is a synthetic workflow test, not a camera measurement. The second camera’s true projection matrix uses convention X2=RX1+t\vb{X}_2=\mat{R}\vb{X}_1+\vb{t}. Compare detected consensus with simulation labels that would be unknown in real images.

[ ]Synthetic scene with noise and outliersBrowser
rng = np.random.default_rng(4)
X = np.column_stack([rng.uniform(-2, 2, 80), rng.uniform(-1.5, 1.5, 80), rng.uniform(4, 9, 80)])
R = np.array([[np.cos(0.08), 0, np.sin(0.08)], [0, 1, 0], [-np.sin(0.08), 0, np.cos(0.08)]])
t = np.array([-0.7, 0., 0.])
x1 = proyecta(X, K, np.eye(3), np.zeros(3))
x2 = proyecta(X, K, R, t)
x1 += rng.normal(0, 0.3, x1.shape)
x2 += rng.normal(0, 0.3, x2.shape)
atipicos = rng.choice(len(X), 16, replace=False)
x2[atipicos] = rng.uniform([0, 0], [640, 480], (len(atipicos), 2))
F, consenso = ransac_f(x1, x2, 250, 1.2, semilla=8)
verdaderos = np.ones(len(X), dtype=bool)
verdaderos[atipicos] = False
print("consenso:", consenso.sum(), "de", len(X))
print("correctos retenidos:", (consenso & verdaderos).sum(), "atípicos retenidos:", (consenso & ~verdaderos).sum())
P1 = K @ np.column_stack([np.eye(3), np.zeros(3)])
P2 = K @ np.column_stack([R, t])
Xt = triangula(P1, P2, x1[verdaderos], x2[verdaderos])
print("mediana del error 3D con pose verdadera:", round(float(np.median(np.linalg.norm(Xt-X[verdaderos], axis=1))), 3))

The next cell estimates pose from F\mat{F}, enforces essential-matrix structure and tests all four solutions. Translation has unit norm, so reconstructed points are expressed in baseline units, not metres. Cheirality is evaluated only on consensus and does not replace a reprojection or parallax test.

[ ]E decomposition and cheiralityBrowser
def pose_desde_F(F, K1, K2, x1, x2):
    E = K2.T @ F @ K1
    U, s, Vt = np.linalg.svd(E)
    if np.linalg.det(U) < 0:
        U[:, -1] *= -1
    if np.linalg.det(Vt) < 0:
        Vt[-1, :] *= -1
    W = np.array([[0., -1., 0.], [1., 0., 0.], [0., 0., 1.]])
    Rs = [U @ W @ Vt, U @ W.T @ Vt]
    ts = [U[:, 2], -U[:, 2]]
    a = np.linalg.solve(K1, homogeneos(x1).T).T
    b = np.linalg.solve(K2, homogeneos(x2).T).T
    a = a[:, :2] / a[:, 2, None]
    b = b[:, :2] / b[:, 2, None]
    P1 = np.column_stack([np.eye(3), np.zeros(3)])
    candidatos = []
    for Rc in Rs:
        for tc in ts:
            Xc = triangula(P1, np.column_stack([Rc, tc]), a, b)
            delante = (Xc[:, 2] > 0) & ((Xc @ Rc.T + tc)[:, 2] > 0)
            candidatos.append((int(delante.sum()), Rc, tc, Xc))
    return max(candidatos, key=lambda c: c[0]), s

(n_delante, R_est, t_est, X_est), valores_E = pose_desde_F(F, K, K, x1[consenso], x2[consenso])
print("puntos delante de ambas cámaras:", n_delante, "de", consenso.sum())
print("determinante de R:", round(float(np.linalg.det(R_est)), 6))
print("escala de t elegida:", round(float(np.linalg.norm(t_est)), 6))
angulo = np.degrees(np.arccos(np.clip((np.trace(R_est @ R.T)-1)/2, -1, 1)))
angulo_t = np.degrees(np.arccos(np.clip(t_est @ (t/np.linalg.norm(t)), -1, 1)))
correctos_consenso = verdaderos[consenso]
error_3d = np.linalg.norm(np.linalg.norm(t)*X_est[correctos_consenso]-X[consenso][correctos_consenso], axis=1)
print('error de rotación (grados):', round(float(angulo), 3))
print('error de dirección de traslación (grados):', round(float(angulo_t), 3))
print('mediana 3D con pose estimada y escala verdadera:', round(float(np.median(error_3d)), 3))

The decomposition uses singular vectors of E\mat{E}, which are the same as those of its projection to (a,a,0)(a,a,0). To compare with truth in this scene, multiply reconstruction by the true baseline length, unavailable in a monocular problem without another measurement. Cameras and labels are known in this demonstration only because we generated them.

In this run, rotation error is 0.341 degrees and translation-direction error 0.431 degrees. Median 3D error on correct consensus pairs is 0.374 units even when true scale is supplied; with true pose it is 0.041. These are results for this synthetic scene, not general bounds. The experiment illustrates that a small angular error can produce appreciable depth error. Joint pose and point fitting by reprojection, with more views and sufficient parallax, is a next step that has not been run here.

Local lab: calibrate a camera

This lab requires local Python with mujoco, opencv-python-headless, scipy and numpy. It generates a white-bordered board in MuJoCo, renders 24 reproducible poses and detects corners in images. True focal length is calculated from image height and vertical field of view, assuming square pixels. The comparison includes rendering and corner-detection effects, not just exact geometry. In one local run with MuJoCo 4.0.1 and OpenCV 5.0.0 all 24 views were detected, with RMS 0.089 px and estimated focal length 514.36 px versus configured 514.68 px. These are measurements from that run, not a guarantee for other versions.

[ ]Calibrate the rendered boardLocal GPU
import numpy as np
import cv2
import mujoco
from scipy.spatial.transform import Rotation

cols, rows, side = 10, 7, 0.06
geoms = []
for j in range(rows):
    for i in range(cols):
        x, y = (i-(cols-1)/2)*side, (j-(rows-1)/2)*side
        color = '0.03 0.03 0.03 1' if (i+j)%2 else '0.97 0.97 0.97 1'
        geoms.append(f'<geom type="box" pos="{x} {y} 0" size="{side/2} {side/2} 0.001" rgba="{color}"/>')
xml = f'''<mujoco><visual><global offwidth="640" offheight="480"/></visual>
<worldbody><light pos="0 0 1" dir="0 0 -1" diffuse="0.8 0.8 0.8"/>
<camera name="cam" pos="0 0 0" fovy="50"/>
<body name="board" pos="0 0 -1.2"><freejoint/>
<geom type="box" pos="0 0 -0.003" size="{side*(cols/2+1)} {side*(rows/2+1)} 0.001" rgba="0.97 0.97 0.97 1"/>
{''.join(geoms)}</body></worldbody></mujoco>'''
model = mujoco.MjModel.from_xml_string(xml)
data = mujoco.MjData(model)
renderer = mujoco.Renderer(model, 480, 640)
obj = np.zeros((rows-1, cols-1, 3), np.float32)
obj[:,:,:2] = np.mgrid[0:cols-1, 0:rows-1].T * side
obj = obj.reshape(-1, 3)
objs, imgs = [], []
g = np.random.default_rng(12)
for i in range(24):
    angles = g.uniform([-0.4,-0.4,-0.25], [0.4,0.4,0.25])
    quat = Rotation.from_euler('xyz', angles).as_quat()
    data.qpos[:3] = [g.uniform(-0.1,0.1), g.uniform(-0.1,0.1), g.uniform(-1.5,-0.9)]
    data.qpos[3:7] = quat[[3,0,1,2]]
    mujoco.mj_forward(model, data)
    renderer.update_scene(data, camera='cam')
    gray = cv2.cvtColor(renderer.render(), cv2.COLOR_RGB2GRAY)
    ok, corners = cv2.findChessboardCorners(gray, (cols-1, rows-1))
    if ok:
        corners = cv2.cornerSubPix(gray, corners, (5,5), (-1,-1),
            (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER,30,0.001))
        objs.append(obj.copy()); imgs.append(corners)
renderer.close()
if len(imgs) < 8:
    raise RuntimeError('Muy pocas vistas detectadas para este experimento')
rms, K_cal, dist, rvecs, tvecs = cv2.calibrateCamera(objs, imgs, (640,480), None, None)
f_true = 480/(2*np.tan(np.deg2rad(50)/2))
print('vistas:', len(imgs), 'RMS:', rms, 'focal verdadera:', f_true)
print('K estimada:', K_cal, 'distorsión:', dist, sep='\n')

def errores_por_cuadrante(objs, imgs, rvecs, tvecs, K_cal, dist, size):
    zonas = [[] for _ in range(4)]
    for puntos, imagen, rv, tv in zip(objs, imgs, rvecs, tvecs):
        pred, _ = cv2.projectPoints(puntos, rv, tv, K_cal, dist)
        pixeles = imagen.reshape(-1,2)
        error = np.linalg.norm(pixeles-pred.reshape(-1,2), axis=1)
        for (u,v), e in zip(pixeles,error):
            zonas[int(v >= size[1]/2)*2 + int(u >= size[0]/2)].append(float(e))
    return [float(np.median(z)) if z else None for z in zonas]

print('mediana por cuadrante:', errores_por_cuadrante(objs,imgs,rvecs,tvecs,K_cal,dist,(640,480)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

For a real webcam, print a flat board, measure each side and save several fixed-resolution photos in a local tablero folder. Tilt the board in both directions and cover centre and edges; avoid blur and reflections. Enter the inner-corner count in patron and measurement in side_real, in metres. The following cell runs after capturing images and is not part of the automatic test because it requires physical material. The workflow can also be tested with OpenCV calibration images, whose pattern has 7 by 6 inner corners; square size is unspecified, so square units are used. Keep a separate image set to evaluate generalization; a quadrant median computed on fitting views is diagnostic, not independent evaluation.

With the 13 images left01 through left14 available in that collection (left10 is missing), this run detected 9 boards and obtained fitting RMS 0.175 px. Quadrant medians were 0.150, 0.140, 0.168 and 0.134 px in top-left, top-right, bottom-left and bottom-right order. These are fitting results on those public images, not a measurement of your webcam or an out-of-sample evaluation.

[ ]Calibrate real board imagesLocal GPU
from pathlib import Path
side_real = 0.025  # reemplaza por la medida de tu tablero, en metros
patron = (9, 6)    # esquinas interiores, no número de cuadrados
paths = sorted([*Path('tablero').glob('*.png'), *Path('tablero').glob('*.jpg')])
if not paths:
    raise RuntimeError('Guarda primero fotografías PNG del tablero en la carpeta tablero')
obj_real = np.zeros((patron[0]*patron[1],3), np.float32)
obj_real[:,:2] = np.mgrid[0:patron[0],0:patron[1]].T.reshape(-1,2)*side_real
objs_real, imgs_real = [], []
size = None
for path in paths:
    gray = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE)
    if gray is None:
        raise ValueError(f'No se pudo leer {path}')
    this_size = (gray.shape[1], gray.shape[0])
    if size is not None and size != this_size:
        raise ValueError('Todas las imágenes deben tener la misma resolución')
    size = this_size
    ok, corners = cv2.findChessboardCorners(gray, patron)
    if ok:
        corners = cv2.cornerSubPix(gray, corners, (5,5), (-1,-1),
            (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER,30,0.001))
        objs_real.append(obj_real.copy()); imgs_real.append(corners)
if len(imgs_real) < 8:
    raise RuntimeError('Se necesitan más vistas detectadas y variadas')
rms_real, K_real, dist_real, rv_real, tv_real = cv2.calibrateCamera(objs_real,imgs_real,size,None,None)
print('vistas detectadas:',len(imgs_real),'de',len(paths),'RMS:',rms_real)
print('K:',K_real,'distorsión:',dist_real,sep='\n')
print('mediana por cuadrante:',errores_por_cuadrante(objs_real,imgs_real,rv_real,tv_real,K_real,dist_real,size))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofEpipolar constraint
Prove: Derive the epipolar constraint for two cameras with relative motion X2=RX1+t\vb{X}_2=\mat{R}\vb{X}_1+\vb{t}.
0
Let x1\vb{x}_1 and x2\vb{x}_2 be normalized directions of a point visible in both cameras, with positive depths λ1\lambda_1 and λ2\lambda_2.

Step 1 of 3. What relationship do the rays satisfy?

ProofSingular values of E
Prove: Prove that a nonzero essential matrix has two equal singular values and one zero.
0
Let E=[t]×R\mat{E}=[\vb{t}]_\times\mat{R} with t≠0\vb{t}\ne0 and R\mat{R} a rotation.

Step 1 of 2. What does rotation do to singular values?

CodeNormalized eight points
Implement eight_point(x1, x2) for at least eight nondegenerate pairs of two-dimensional points. Return a fundamental matrix with unit Frobenius norm and rank two. Normalize each set to zero centre and mean distance sqrt(2), fit with full SVD, enforce rank two and denormalize.
import numpy as np
def eight_point(x1, x2):
  pass
Shift+Enter to run
Numeric
For samples of eight correspondences, 40% outliers and 99% probability of at least one outlier-free sample, what is the minimum number of independent iterations?
Quiz
What happens if the cameras differ only by rotation?
Key idea
A camera produces rays. Calibration relates rays to pixels; a second view supplies parallax, but depth becomes fragile when the baseline is small.