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.
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 , then . Homogeneous rigid motion and the transformation tree compose this change with the rest of the robot. To invert an ideal pixel, gives a camera-frame direction; in world coordinates the ray is , with . Depth remains undetermined.
A lens is not a pinhole
Lens distortion modifies normalized coordinates before multiplication by . For , the usual radial and tangential model is
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 . For each view without distortion, its plane and image are related by . If and is column of , orthogonality and equal norms of the first two rotation columns give two linear constraints:
Several views with different orientations produce a homogeneous system for the six independent elements of , up to scale. After recovering 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 ; 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 is positive definite; its factorization recovers and allows normalization to . 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 are proportional to and , and the third to . Fix a common scale, form and project the approximate matrix to 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 unchanged.
Homography and DLT
A homography is an invertible planar projective transformation, , with rank-three 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: .
DLT writes . Each pair contributes two independent equations in the nine entries of . At least four pairs in a nondegenerate configuration determine the solution up to scale. Stack equations into 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 . 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 . Normalized rays and , together with baseline , lie in a plane. Epipolar geometry expresses their coplanarity:
The skew-symmetric matrix satisfies . The inner product above is zero because lies in the plane generated by and . In the second image, gives coefficients of the line containing the match; the epipole is the other camera centre’s projection and satisfies . With translation parallel to the image plane, the epipole can be at infinity and lines parallel. Coordinates must be undistorted before applying these equations.
If , singular values of are : , whose eigenvalues are . Multiplying by a rotation does not change singular values. Under pure rotation , 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 . Stack equations , calculate the homogeneous solution by SVD and zero the smallest singular value of the resulting matrix. Then denormalize: . 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, . Project its SVD to singular values , with 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 and signs of and are chosen to make rotations proper, take
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 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 is entirely correct with probability , the probability at least one of samples is correct is . To reach probability , it suffices that
This formula assumes independent samples and representative proportion ; an outlier-free sample alone guarantees neither an accurate nor nondegenerate model. For , and , 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 is exact for independent draws with replacement from a population with correct fraction . If elements are drawn without replacement from pairs, of them correct, the exact probability is when . It can be lower than for small samples. In real data 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.
Triangulation seeks the 3D point compatible with two projections. In linear form each view contributes rows and ; 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 , baseline and disparity , . If disparity uncertainty is small, first-order propagation gives . This is a local approximation, not a reliable distribution when is near zero. Increasing distance or reducing baseline therefore destabilizes depth even with well-measured pixels.
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.
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 each design-matrix row is . In the minimal case the matrix is : full SVD is needed to obtain its ninth right vector, which generates the null space. Homography fitting uses the same principle and normalization.
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 , so directly comparing unnormalized entries can give a false error.
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.
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 . Compare detected consensus with simulation labels that would be unknown in real images.
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 , 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.
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 , which are the same as those of its projection to . 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.
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)))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.
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))npm run lab and open the connection link.Exercises
Step 1 of 3. What relationship do the rays satisfy?
Step 1 of 2. What does rotation do to singular values?
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