Structure from motion: a reconstruction needs a scale explanation
运动恢复结构
Recover three calibrated views, derive pose Jacobians and Schur elimination, and test scale, missing observations and outliers.
structure-from-motionThree photographs can recover a shape without telling you its size
Walk around a small model building and take three photographs. Now imagine a full-size building, a much larger camera path and otherwise matching views. Perspective alone can make the image measurements identical. A reconstruction may put every window in the right relative place and still have no answer to “How many meters wide is the building?”
Structure from motion, or SfM, estimates scene structure and camera motion from overlapping views. In the calibrated setting used here, the unknowns are three-dimensional points and camera poses; camera intrinsics are given. With uncalibrated images, intrinsics or projective structure introduce additional unknowns and ambiguities. A point cloud, camera trajectory and low reprojection error therefore need a coordinate and scale explanation before they become measurements. Bundle-adjustment gauge freedoms
SfM is related to, but distinct from, stereo reconstruction and SLAM. Calibrated stereo can use a known physical baseline to set scale. SfM commonly reconstructs from an image collection, with camera motion among the unknowns. SLAM places reconstruction inside an ongoing localization and mapping problem with temporal and operational constraints. The exact boundaries vary by system; the important question is which quantities are known, estimated and evaluated.
| Stage | Input and output | A failure that later optimization cannot simply wish away |
|---|---|---|
| Find and match image features | Pixel locations and candidate correspondences | Repeated windows create plausible wrong matches |
| Verify geometry | A supported view relation and inlier set | Pure rotation or a dominant plane defeats a chosen initialization |
| Initialize and triangulate | An initial camera pair and sparse points | A tiny baseline gives little depth information |
| Register another image | 3D-to-2D matches and a camera pose | Bad correspondences can place a camera incorrectly |
| Bundle adjustment | Jointly refined cameras and points | An incorrect track may still be explained by a distorted solution |
| Inspect and extend | Connected, validated reconstruction | Small residuals alone do not establish completeness or metric accuracy |
The COLMAP paper is useful for this whole-system view: correspondence verification, seed selection, registration, triangulation and local/global refinement each have their own conditions. Our program implements a complete small geometric backend from supplied matches, not its feature frontend or its exact solver choices. SfM Revisited
The example starts with 24 supplied tracks, deliberately corrupts four correspondences and removes three observations in the third view. It estimates the first pair, triangulates points, registers the third camera, and jointly refines the reconstruction. Ground-truth cameras are used to generate the synthetic observations; the estimator does not receive them. Retain this distinction when adapting the example to real data.
Keep coordinates, ambiguity and optimization separate
Fix the camera convention
Let X be a world point and q its coordinates in camera j. Our rotation maps world coordinates into that camera; t is a translation vector, not the camera center:
All camera points used for the pinhole projection must have positive depth. K contains focal lengths, principal point and optional skew. The code accepts standard upper-triangular pinhole intrinsics with positive focal lengths; it does not model lens distortion. Undistort or explicitly extend the projection model before using distorted photographs.
The inspected COLMAP Rigid3d code defines a transform as R times a point plus t and obtains the inverse translation by applying the inverse rotation to −t. The 2016 paper’s camera matrix expression uses a different R/t interpretation. Both can be valid; mixing camera centers from one convention with translations from the other is not. Fixed transform convention
For any positive scale s, multiplying all scene points and translations by s leaves image projections unchanged:
A generic calibrated reconstruction also permits a common world rotation and translation: seven similarity degrees of freedom in total, before fixing a reference. We set the first camera to [I|0] and choose the second camera’s distance from it as one. This fixes a coordinate gauge; it does not measure a one-meter baseline. Degenerate geometry can have additional ambiguities even after these choices. Gauge freedom
Estimate a relative pose from image correspondences
Convert pixels to normalized camera coordinates with K inverse and append a homogeneous one. For the first camera [I|0] and second [R|t], the epipolar relation is
Each correspondence contributes one linear equation in the nine entries of E. Writing normalized coordinates as (x,y) and (u,v), its design row is
Our eight-point initializer additionally centers each image’s coordinates and scales their mean Euclidean distance from the origin to √2. Hartley describes this conditioning step for fundamental-matrix estimation; we use the coordinate normalization but impose an essential-matrix constraint after reversing the transforms. It is not a verbatim reproduction of his full procedure. Normalization, sections 4.1–5.1 The program solves the homogeneous system by SVD, reverses those coordinate transforms, then projects the estimate onto that constraint. If the unconstrained estimate has singular values σ₁, σ₂, σ₃, use
The final matrix is normalized by its Frobenius norm. This produces a constrained initial estimate, not a minimum-reprojection-error solution. For exactly eight rows, a full SVD is important: the required null vector is the ninth right-singular vector, which an eight-row reduced output can omit. The program checks design rank and tests the exact-eight case. Do not describe this teaching solver as COLMAP’s five-point minimal estimator.
RANSAC repeatedly fits sampled eight-point subsets and scores their support using a normalized-coordinate Sampson error:
This is a first-order geometric-error approximation. Linearize the epipolar constraint with respect to the four observed image coordinates. The shortest correction satisfying that linearized constraint is parallel to its gradient, with squared length equal to the squared constraint residual divided by the squared gradient norm. The two epipolar-line coordinate pairs in the denominator are exactly those four derivatives. This explains both the formula and why it is a local approximation. Its numerator and denominator both scale quadratically with E, so rescaling E does not change the score. A zero or numerically tiny denominator is treated as unsupported rather than divided through. Our threshold is in normalized-coordinate units; the example uses 2/700 because both focal lengths are 700 pixels. It is not an exact statement that every accepted match has a two-pixel Euclidean error.
The code uses 300 trials with a fixed seed, chooses the largest inlier count and breaks ties by the median inlier score. It refits the inliers only if that score improves or stays equal. It does not promise a chosen confidence level, compare a homography model, or guarantee rejection of every outlier on arbitrary data. Repetitive texture, poor spatial coverage and dominant planes still require explicit treatment in a real SfM system. Initialization and verification
Choose a pose, triangulate and register another camera
After adjusting the SVD factors of E to proper rotations, define the fixed quarter-turn matrix below. The two rotation choices and two translation signs give four candidates; the translation initially has unit length.
Triangulate matches under each, then prefer the candidate with the most points in front of both cameras. Our additional minimum-median-parallax check is a teaching threshold, not a universal reliability criterion.
For a projection matrix P and image location (x,y), two independent homogeneous equations are
Stack them for the two views and solve by SVD. The program rejects rank-degenerate solutions, points at infinity and negative depths. Noisy rays need not intersect exactly, so this linear triangulation is an initializer. With a very small angle between rays, a small image perturbation can correspond to a large depth change. Pure rotation supplies no translational baseline for this triangulation.
The third camera is registered using 3D points already reconstructed and their 2D observations. Our nonminimal calibrated pose DLT needs at least six nondegenerate correspondences; it solves a homogeneous camera matrix and projects its left block to a proper rotation. A planar configuration is rejected by this particular DLT test. That is a limitation of the chosen initializer, not a claim that calibrated pose estimation from a plane is impossible. The code does not include robust PnP/RANSAC for this stage. Image registration and triangulation
A track associates observations believed to represent the same scene point. The separate feature_tracks routine greedily merges supplied (image_id, keypoint_id) pairs and rejects merges that would put two observations from one image in the same track. That detects one structural contradiction; it does not prove semantic correspondence, and earlier greedy choices affect later possibilities.
Bundle adjustment optimizes what was actually observed
Let Ω contain only visible point-camera pairs. Bundle adjustment minimizes projection residuals jointly over the unfixed camera poses and points. We use a Huber penalty on each two-dimensional observation norm and a gauge residual:
Here camera indices start at zero, so t₁ is the second camera’s translation. Its norm equals the baseline length from the fixed first camera. Huber’s loss is quadratic near zero and grows linearly for large residual norms:
At s=0 use weight one. Both coordinates of an observation receive the same weight; weighting x and y independently would define a different loss. The gauge residual stays quadratic and is excluded from pixel-error metrics. Robustness reduces the leverage of large residuals; it does not make track validation unnecessary. This Huber choice differs from the COLMAP paper’s described Cauchy local refinement. Bundle structure COLMAP refinement
Missing observations are represented by two NaNs and contribute no residual rows. A partial NaN, an infinity, a point seen in only one camera or a camera with too few observations is rejected. The camera visibility graph must be connected to the fixed reference; otherwise disconnected components retain independent gauges. These are necessary screening rules, not a proof of identifiability for every connected graph.
Derive the pose and point Jacobians
For q=(x,y,z), with focal lengths fₓ,fᵧ and intrinsic skew kₛ, the projection derivative is
Principal-point offsets vanish from this derivative. The code evaluates an equivalent matrix expression directly from K, avoiding special assumptions about zero skew.
Use a left pose retraction with a small rotation ω and translation increment v:
Consequently,
The rotation acts on both RX and t. Substituting −[RX]× for −[q]× would omit the rotated translation. This retraction agrees with the stated first-order derivative; it is not advertised as the full finite SE(3) twist exponential with its translational Jacobian. The test suite checks all 42 free scalar coordinates of a three-camera, ten-point derivative example, and a separate directional derivative with missing observations.
Eliminate points before solving for cameras
IRLS scales each observation residual and Jacobian row by the square root of its Huber weight. A damped normal equation then partitions camera increments c from point increments p:
Here the diagonal damping is already included. Each image residual depends on one camera and one point, so V has independent 3-by-3 point blocks in this model. Solving the second block row and substituting into the first gives the Schur system:
The implementation solves each small block rather than explicitly forming its inverse, then back-substitutes after solving the reduced camera system. Cross-point penalties would change this structure; the code refuses coupled point blocks. Reduced bundle system, equations 16–20
The trial step updates cameras and points, then divides all points and translations by the second baseline length. This common rescaling preserves projection and selects the same scale gauge. A step is accepted only if the actual robust objective decreases; otherwise damping increases. The iteration budget does not guarantee convergence to the global minimum.
This program deliberately constructs dense J and H. With M cameras and N points, the reduced dense camera solve is cubic in roughly 6(M−1), while eliminating points exploits their small blocks. The cost of forming dense arrays and camera coupling still matters; no linear-time or large-scene memory claim follows from using a Schur complement. A production system chooses sparse structures and solvers around the actual visibility graph.
Recover three views from corrupted correspondences
Use Python 3.12 and NumPy 1.26.4. Save the complete code as sfm.py and run python sfm.py. The synthetic scene contains 24 points, three cameras, focal lengths of 700 pixels and independent Gaussian coordinate noise with standard deviation 0.2 pixels. Seed 41 defines the scene and noise; RANSAC uses seed 9.
Four first-pair matches are replaced with other points’ observations. Three third-view observations are missing. Initialization and bundle adjustment use this same corrupted measurement array. The program never restores the original correct observations after deciding which matches to keep.
"""Original small calibrated SfM from supplied correspondences.
Eight-point initialization, nonminimal pose DLT, Huber bundle adjustment and
point-block Schur elimination. Not a COLMAP implementation or image frontend.
"""
import json
import numpy as np
def finite(x,shape=None):
a=np.asarray(x,dtype=float)
if not np.isfinite(a).all() or (shape is not None and a.shape!=shape):
raise ValueError('Finite values with the stated shape required')
return a
def intrinsics(value):
k=finite(value,(3,3))
if k[0,0]<=0 or k[1,1]<=0 or not np.allclose(k[2],[0,0,1],atol=1e-12,rtol=0) or abs(k[1,0])>1e-12:
raise ValueError('Positive focal lengths and standard upper-triangular pinhole K required')
return k
def skew(v):
x,y,z=finite(v,(3,))
return np.array([[0,-z,y],[z,0,-x],[-y,x,0.]])
def rotation(w):
w=finite(w,(3,));angle=np.linalg.norm(w);a=skew(w)
if angle<1e-8:return np.eye(3)+a+.5*a@a
return np.eye(3)+np.sin(angle)/angle*a+(1-np.cos(angle))/angle**2*(a@a)
def project(points,r,t,k):
x=finite(points);r=finite(r,(3,3));t=finite(t,(3,));k=intrinsics(k)
if x.ndim!=2 or x.shape[1]!=3:raise ValueError('N by 3 points required')
camera=x@r.T+t
if np.any(camera[:,2]<=1e-8):raise ValueError('Point behind or too close to camera')
q=camera@k.T
return q[:,:2]/q[:,2,None]
def normalize_pixels(p,k):
p=finite(p);k=intrinsics(k)
if p.ndim!=2 or p.shape[1]!=2:raise ValueError('N by 2 pixels required')
q=np.linalg.solve(k,np.c_[p,np.ones(len(p))].T).T
return q[:,:2]/q[:,2,None]
def center_scale(p):
center=p.mean(axis=0);distance=np.linalg.norm(p-center,axis=1).mean()
if distance<1e-12:raise ValueError('Coincident image points')
scale=np.sqrt(2)/distance
transform=np.array([[scale,0,-scale*center[0]],[0,scale,-scale*center[1]],[0,0,1]])
return (p-center)*scale,transform
def essential(left,right):
"""Normalized eight-point fit, then project to the essential-matrix manifold."""
a=finite(left);b=finite(right,a.shape)
if a.ndim!=2 or a.shape[1]!=2 or len(a)<8:raise ValueError('At least eight normalized correspondences required')
a,ta=center_scale(a);b,tb=center_scale(b);x,y=a.T;u,v=b.T
design=np.c_[u*x,u*y,u,v*x,v*y,v,x,y,np.ones(len(a))]
_,s,vh=np.linalg.svd(design)
if s[7]<1e-10*s[0]:raise ValueError('Degenerate eight-point configuration')
estimate=tb.T@vh[-1].reshape(3,3)@ta
u,s,vh=np.linalg.svd(estimate);scale=(s[0]+s[1])/2
result=u@np.diag([scale,scale,0])@vh
return result/np.linalg.norm(result)
def sampson(left,right,e):
left=finite(left);right=finite(right,left.shape);e=finite(e,(3,3))
if left.ndim!=2 or left.shape[1]!=2:raise ValueError('Matching N by 2 coordinates required')
a=np.c_[left,np.ones(len(left))];b=np.c_[right,np.ones(len(right))]
ea=a@e.T;eb=b@e;residual=np.sum(b*ea,axis=1)
denom=np.sum(ea[:,:2]**2+eb[:,:2]**2,axis=1)
return np.divide(residual**2,denom,out=np.full(len(a),np.inf),where=denom>1e-20)
def ransac_essential(left,right,threshold=.003,trials=300,seed=9):
"""Fixed trial budget, normalized-coordinate Sampson distance; no confidence guarantee."""
a=finite(left);b=finite(right,a.shape)
if a.ndim!=2 or a.shape[1]!=2 or len(a)<8 or threshold<=0 or not np.isfinite(threshold) or type(trials) is not int or trials<1:
raise ValueError('Valid points, threshold and trial count required')
rng=np.random.default_rng(seed);best=None;best_score=(-1,-np.inf)
def score(e):
errors=sampson(a,b,e);mask=errors<threshold**2
return (int(mask.sum()),-float(np.median(errors[mask])) if mask.any() else -np.inf),mask
for _ in range(trials):
ids=rng.choice(len(a),8,replace=False)
try:e=essential(a[ids],b[ids])
except (ValueError,np.linalg.LinAlgError):continue
value,mask=score(e)
if value>best_score:best_score=value;best=(e,mask)
if best is None or best_score[0]<8:raise ValueError('No supported essential matrix')
e,mask=best
try:refined=essential(a[mask],b[mask])
except (ValueError,np.linalg.LinAlgError):return e,mask
value,new_mask=score(refined)
return (refined,new_mask) if value>=best_score else (e,mask)
def triangulate(a,b,r,t):
pl=np.c_[np.eye(3),np.zeros(3)];pr=np.c_[r,t]
design=np.array([a[0]*pl[2]-pl[0],a[1]*pl[2]-pl[1],b[0]*pr[2]-pr[0],b[1]*pr[2]-pr[1]])
_,s,vh=np.linalg.svd(design)
if s[-2]<1e-12*max(s[0],1) or abs(vh[-1,3])<1e-12:raise ValueError('Degenerate triangulation')
x=vh[-1,:3]/vh[-1,3]
if x[2]<=0 or (r@x+t)[2]<=0:raise ValueError('Negative triangulated depth')
return x
def recover_pose(left,right,e,min_angle=.2):
"""Cheirality choice among four poses; min median parallax is in degrees."""
u,_,vh=np.linalg.svd(e)
if np.linalg.det(u)<0:u[:,-1]*=-1
if np.linalg.det(vh)<0:vh[-1]*=-1
w=np.array([[0,-1,0],[1,0,0],[0,0,1]])
best=None
for r in [u@w@vh,u@w.T@vh]:
for t in [u[:,2],-u[:,2]]:
points=[];ids=[];angles=[];center=-r.T@t
for i,(a,b) in enumerate(zip(left,right)):
try:x=triangulate(a,b,r,t)
except (ValueError,np.linalg.LinAlgError):continue
v=x-center;cosine=np.dot(x,v)/(np.linalg.norm(x)*np.linalg.norm(v))
angles.append(np.degrees(np.arccos(np.clip(cosine,-1,1))));points.append(x);ids.append(i)
if best is None or len(ids)>len(best[3]):best=(r,t,np.array(points),np.array(ids,dtype=int),angles)
r,t,points,ids,angles=best
if len(ids)<8 or np.median(angles)<min_angle:raise ValueError('Insufficient positive depth or parallax')
return r,t,points,ids
def pose_dlt(points,pixels,k):
"""Nonminimal calibrated pose DLT; requires at least six nondegenerate 3D points."""
x=finite(points);p=normalize_pixels(pixels,k)
if x.shape!=(len(p),3) or len(x)<6:raise ValueError('At least six 3D-2D correspondences required')
rows=[]
for point,(u,v) in zip(np.c_[x,np.ones(len(x))],p):
rows.extend([np.r_[point,np.zeros(4),-u*point],np.r_[np.zeros(4),point,-v*point]])
_,s,vh=np.linalg.svd(rows)
if s[10]<1e-10*s[0]:raise ValueError('Degenerate pose DLT configuration')
matrix=vh[-1].reshape(3,4)
if np.linalg.det(matrix[:,:3])<0:matrix=-matrix
u,s,vh=np.linalg.svd(matrix[:,:3]);r=u@np.diag([1,1,np.linalg.det(u@vh)])@vh;t=matrix[:,3]/s.mean()
if np.median((x@r.T+t)[:,2])<=0:raise ValueError('Pose faces away from points')
return r,t
def residual_jacobian(rotations,translations,points,observations,k):
"""Pixel residual/Jacobian for left pose retraction; first camera is fixed."""
r=finite(rotations);t=finite(translations);x=finite(points);o=np.asarray(observations,dtype=float);k=intrinsics(k)
if r.ndim!=3 or r.shape[1:]!=(3,3) or len(r)<2 or t.shape!=(len(r),3) or x.ndim!=2 or x.shape[1]!=3 or o.shape!=(len(r),len(x),2):
raise ValueError('Compatible cameras, observations and points required')
valid=np.isfinite(o).all(axis=2);missing=np.isnan(o).all(axis=2)
if not np.all(valid|missing) or np.any(valid.sum(axis=0)<2) or np.any(valid.sum(axis=1)<3):
raise ValueError('Missing observations use two NaNs; each point needs two views and each view three points')
adjacency=valid.astype(int)@valid.astype(int).T>0;reachable={0}
while True:
grown=reachable|{j for i in reachable for j in range(len(r)) if adjacency[i,j]}
if grown==reachable:break
reachable=grown
if len(reachable)!=len(r):raise ValueError('Disconnected view graph has independent gauges')
if not np.allclose(r[0],np.eye(3)) or not np.allclose(t[0],0):raise ValueError('Gauge requires first camera [I|0]')
if not np.allclose(r@r.transpose(0,2,1),np.eye(3)) or not np.allclose(np.linalg.det(r),1):raise ValueError('Proper rotations required')
nc=6*(len(r)-1);j=np.zeros((2*int(valid.sum())+1,nc+3*len(x)));residual=np.empty(len(j));row=0
for camera in range(len(r)):
for point in range(len(x)):
if not valid[camera,point]:continue
q=r[camera]@x[point]+t[camera]
if q[2]<=1e-8:raise ValueError('Bundle point behind camera')
h=k@q;uv=h[:2]/h[2];projector=(k[:2]*h[2]-h[:2,None]*k[2])/h[2]**2
residual[row:row+2]=uv-o[camera,point]
if camera:j[row:row+2,6*(camera-1):6*camera]=projector@np.c_[-skew(q),np.eye(3)]
j[row:row+2,nc+3*point:nc+3*point+3]=projector@r[camera]
row+=2
length=np.linalg.norm(t[1])
if length<1e-12:raise ValueError('Second camera cannot share first center')
residual[-1]=100*(length-1);j[-1,3:6]=100*t[1]/length
return residual,j
def huber_system(residual,jacobian,delta=2.):
if not np.isfinite(delta) or delta<=0:raise ValueError('Positive Huber threshold required')
norms=np.linalg.norm(residual[:-1].reshape(-1,2),axis=1)
weights=np.minimum(1,delta/np.maximum(norms,1e-30));weights=np.r_[np.repeat(weights,2),1.]
loss=np.where(norms<=delta,.5*norms**2,delta*(norms-.5*delta)).sum()+.5*residual[-1]**2
root=np.sqrt(weights);return float(loss),root*residual,root[:,None]*jacobian
def schur_step(h,g,n_camera):
"""Eliminate independent 3x3 point blocks; compare against a dense solve in tests."""
n=len(g)-n_camera
if h.shape!=(len(g),len(g)) or n_camera<1 or n%3:raise ValueError('Camera and 3D point blocks required')
s=h[:n_camera,:n_camera].copy();rhs=-g[:n_camera].copy();blocks=[]
for start in range(n_camera,len(g),3):
sl=slice(start,start+3);v=h[sl,sl];w=h[:n_camera,sl]
cross=h[sl,n_camera:].copy();cross[:,start-n_camera:start-n_camera+3]=0
if not np.allclose(cross,0,atol=1e-12):raise ValueError('Point block must be independent')
inverse_cross=np.linalg.solve(v,w.T);inverse_gradient=np.linalg.solve(v,g[sl])
s-=w@inverse_cross;rhs+=w@inverse_gradient;blocks.append((sl,inverse_cross,inverse_gradient))
dc=np.linalg.solve(s,rhs);step=np.empty_like(g);step[:n_camera]=dc
for sl,cross,gradient in blocks:step[sl]=-gradient-cross@dc
return step
def retract(rotations,translations,points,step,normalize=False):
r=rotations.copy();t=translations.copy();x=points.copy();nc=6*(len(r)-1)
for camera in range(1,len(r)):
d=step[6*(camera-1):6*camera];a=rotation(d[:3]);r[camera]=a@r[camera];t[camera]=a@t[camera]+d[3:]
x+=step[nc:].reshape(x.shape)
if normalize:
scale=np.linalg.norm(t[1])
if scale<1e-12:raise ValueError('Collapsed baseline')
x/=scale;t/=scale
return r,t,x
def bundle_adjust(rotations,translations,points,observations,k,iterations=35,delta=2.):
"""Huber IRLS/LM with [I|0] fixed and arbitrary second-baseline length one."""
if type(iterations) is not int or iterations<1:raise ValueError('Positive integer iteration budget required')
r=rotations.copy();t=translations.copy();x=points.copy();nc=6*(len(r)-1);damping=1e-3;history=[]
for _ in range(iterations):
residual,j=residual_jacobian(r,t,x,observations,k);loss,weighted,jw=huber_system(residual,j,delta)
h=jw.T@jw;g=jw.T@weighted;regularized=h+damping*np.diag(np.maximum(np.diag(h),1e-6))
step=schur_step(regularized,g,nc)
try:
candidate=retract(r,t,x,step,normalize=True);rr,jj=residual_jacobian(*candidate,observations,k);new=huber_system(rr,jj,delta)[0]
except (ValueError,np.linalg.LinAlgError):new=np.inf
if new<loss:
r,t,x=candidate;history.append(new);damping=max(damping/3,1e-9)
if np.linalg.norm(step)<1e-9:break
else:damping=min(damping*10,1e12)
return r,t,x,history
def feature_tracks(matches):
"""Greedy union of supplied observation IDs; reject a repeated image in a track."""
parent={};images={};rejected=[]
def find(a):
if parent[a]!=a:parent[a]=find(parent[a])
return parent[a]
for first,second in matches:
a,b=tuple(first),tuple(second)
for obs in [a,b]:
if len(obs)!=2 or any(type(v) is not int or v<0 for v in obs):raise ValueError('Nonnegative integer image/keypoint IDs required')
if obs not in parent:parent[obs]=obs;images[obs]={obs[0]}
ra,rb=find(a),find(b)
if ra==rb:continue
if images[ra]&images[rb]:rejected.append((a,b));continue
parent[rb]=ra;images[ra]|=images[rb]
groups={}
for obs in parent:groups.setdefault(find(obs),[]).append(obs)
return sorted([sorted(g) for g in groups.values()]),rejected
def synthetic_scene(noise=.2,seed=41):
rng=np.random.default_rng(seed);points=rng.uniform([-1,-.7,4],[1,.7,7],size=(24,3))
rotations=np.array([np.eye(3),rotation([.015,.07,-.01]),rotation([-.025,-.06,.02])])
centers=np.array([[0.,0,0],[.8,.05,.02],[-.65,.12,.1]])
translations=-np.einsum('nij,nj->ni',rotations,centers);k=np.array([[700.,0,320],[0,700,240],[0,0,1.]])
clean=np.array([project(points,r,t,k) for r,t in zip(rotations,translations)])
observed=clean+rng.normal(0,noise,clean.shape)
return rotations,translations,points,observed,k
def demo():
_,_,_,observed,k=synthetic_scene();corrupt=observed.copy();corrupt[1,:4]=corrupt[1,[7,11,15,19]];corrupt[2,4:7]=np.nan
left=normalize_pixels(corrupt[0],k);right=normalize_pixels(corrupt[1],k)
e,inlier=ransac_essential(left,right,threshold=2/700)
r1,t1,points,valid=recover_pose(left[inlier],right[inlier],e)
ids=np.flatnonzero(inlier)[valid];seen=np.isfinite(corrupt[2,ids]).all(axis=1);r2,t2=pose_dlt(points[seen],corrupt[2,ids][seen],k)
rotations=np.array([np.eye(3),r1,r2]);translations=np.array([np.zeros(3),t1,t2]);measurements=corrupt[:,ids]
before,j=residual_jacobian(rotations,translations,points,measurements,k)
_,weighted,jw=huber_system(before,j);h=jw.T@jw+.01*np.eye(j.shape[1]);g=jw.T@weighted
dense=-np.linalg.solve(h,g);reduced=schur_step(h,g,12)
refined_r,refined_t,refined_x,history=bundle_adjust(rotations,translations,points,measurements,k)
after,_=residual_jacobian(refined_r,refined_t,refined_x,measurements,k)
groups,rejected=feature_tracks([((0,0),(1,2)),((1,2),(2,4)),((0,1),(2,4))])
return {'input_tracks':24,'corrupted_first_pair':4,'essential_inliers':int(inlier.sum()),'wrong_matches_retained':int(inlier[:4].sum()),'triangulated_points':len(points),'bundle_observations':int(np.isfinite(measurements).all(axis=2).sum()),
'pixel_coordinate_rmse_before':float(np.sqrt(np.mean(before[:-1]**2))),'pixel_coordinate_rmse_after':float(np.sqrt(np.mean(after[:-1]**2))),
'accepted_bundle_steps':len(history),'final_second_baseline':float(np.linalg.norm(refined_t[1])),
'dense_schur_max_difference':float(np.max(np.abs(dense-reduced))),'bundle_robust_losses':history,
'feature_tracks':groups,'rejected_track_merges':len(rejected)}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
The recorded run produced:
{
"input_tracks": 24,
"corrupted_first_pair": 4,
"essential_inliers": 20,
"wrong_matches_retained": 0,
"triangulated_points": 20,
"bundle_observations": 57,
"pixel_coordinate_rmse_before": 6.241101814975324,
"pixel_coordinate_rmse_after": 0.12029369231959552,
"accepted_bundle_steps": 16,
"final_second_baseline": 0.9999999999999999,
"dense_schur_max_difference": 3.578803919879192e-13,
"bundle_robust_losses": [
2.1872117557562136,
0.9590465376290587,
0.9259026571074429,
0.9107666619593445,
0.8904062487415821,
0.8814615535812941,
0.8482215281017165,
0.8392335950509643,
0.8362718784874253,
0.8267907093429279,
0.8248320258270487,
0.8248226279285892,
0.8248226274773125,
0.8248226274772575,
0.8248226274772569,
0.8248226274772464
],
"feature_tracks": [
[
[
0,
0
],
[
1,
2
],
[
2,
4
]
],
[
[
0,
1
]
]
],
"rejected_track_merges": 1
}
The 20 triangulated points would yield 60 point-camera observations if all were visible; three are missing, leaving 57. The error below is pixel-coordinate RMSE, over 114 scalar coordinate residuals, excluding the gauge residual. It drops from about 6.24 to 0.12 pixels after joint refinement. This is not the RMS of 57 two-dimensional Euclidean distances, a held-out-image result or proof of accurate metric depths.
All four deliberately corrupted first-pair correspondences were rejected in this run. That is a reproducible result for these inputs and seed, not a guarantee about general outliers. The scale remains arbitrary: a printed second-baseline length of 0.9999999999999999 is numerical normalization near one, not a recovered distance in meters.
The dense and Schur steps agree to about 3.58×10⁻¹³ for the recorded damped system. The accepted robust losses decrease, but only accepted steps are listed; rejected trials still count toward the 35-trial optimization budget. Tests additionally cover exact-eight nullspaces, pure rotation, planar pose-DLT failure, negative or infinite triangulations, gauge rank, missing data, invalid inputs and the greedy track conflict.
A small residual is one diagnostic, not the reconstruction’s whole meaning
This example assumes static points, correct intrinsics, a pinhole camera and supplied correspondences. It omits feature detection, lens distortion, rolling shutter, robust registration of new cameras, global camera averaging and dense surface reconstruction. Learned features may improve matching, but they do not remove scale ambiguity or make moving objects static.
Low residuals can coexist with weak depth constraints, incorrect track associations or incomplete coverage. Inspect parallax, visibility, residual distribution, connected components and sensitivity to perturbed observations. When comparing a reconstruction to known geometry, state whether you aligned translation, rotation and scale; using ground truth to set scale is not unaided metric recovery.
A measured baseline, known object length, surveyed control point arrangement or another appropriately modeled sensor can constrain scale. Its uncertainty and calibration enter the problem too. Simply renaming the reconstruction’s coordinate unit “meter” supplies none of that evidence.
Check geometry before trusting a point cloud
-
Explain the scale. A reconstruction has second-baseline length one. You multiply every world point and camera translation by five while keeping rotations and K unchanged. What happens to the images and the baseline?
Answer: The projections stay identical because their homogeneous numerator and denominator both scale by five. The baseline becomes five in the new coordinate units. Neither result determines meters without an external physical constraint.
-
Find the missing derivative term. A left pose update rotates R but also rotates t. Why is the rotation derivative −[q]× rather than −[RX]×?
Answer: The perturbed camera point is approximately q+ω×q+v, with q=RX+t. Replacing q by RX drops ω×t. The two expressions coincide only in special cases such as zero translation, which is why testing only the first camera could conceal the error.
-
Count the residuals. Twenty points are seen in three cameras, except for three missing observations. How many pixel residual scalars and total residual rows does this program build? Does replacing missing observations with zero pixels preserve the objective?
Answer: There are 60−3=57 observed point-camera pairs and 114 scalar pixel residuals. Adding the one scale-gauge residual gives 115 rows. Filling missing entries with (0,0) invents observed image locations and adds constraints that were never measured, so it changes the objective.
-
Design a reliability test. Refinement reduces coordinate RMSE from 6.24 to 0.12 pixels. What additional evidence would justify using the reconstruction to measure building dimensions?
Answer: Supply a physical scale constraint with known uncertainty, verify calibration and static-scene assumptions, and compare held-out distances or control geometry. Inspect parallax and coverage, test sensitivity to observations and report any alignment using ground truth. The training-view residual decrease alone establishes neither metric scale nor accurate unseen dimensions.
Read the system and the optimizer at different levels
The COLMAP paper explains why a successful incremental pipeline depends on correspondence quality, model selection, seed selection, registration, triangulation and refinement together. It is a system reference, not a claim that the 2016 authors invented SfM or bundle adjustment. The bundle-adjustment synthesis explains the optimization structure and its coordinate freedoms; this article uses only the explicitly recorded sections. COLMAP pipeline Bundle synthesis
A useful next experiment changes one assumption at a time: shrink the baseline, add a moving track, remove a bridge between view groups or perturb intrinsics. First predict which part should fail, then inspect its actual diagnostic. When extending to photographs, preserve a simple geometric baseline and distinguish errors in matching from errors in the optimizer. Lower final cost does not tell you which assumption was wrong.
Make a prediction, then check
Bundle adjustment lowers image error and normalizes the second baseline to one. Has it recovered distances in meters?
Learning objectives
- Separate camera translations, camera centers and arbitrary reconstruction scale.
- Recover a calibrated camera pair, triangulate points and register a third camera.
- Derive robust reprojection Jacobians and the reduced Schur system.
- Test missing observations, degeneracies and misleading low residuals.
Prerequisites & connections
Explore related knowledge →References
- Structure-from-Motion Revisited
Johannes L. Schönberger; Jan-Michael Frahm · 2016 - Bundle Adjustment — A Modern Synthesis
Bill Triggs; Philip McLauchlan; Richard Hartley; Andrew Fitzgibbon - COLMAP Rigid3d — fixed coordinate-transform conventions
COLMAP contributors - In Defense of the Eight-Point Algorithm
Richard I. Hartley · 1997
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped primary papers and pinned code, 34 formal numerical/bilingual/figure/review checks, 15 matching display equations per language, complete NumPy implementation and actual output, four explained exercises. Four SVG variants checked with four font families. Not human peer review or a real-data benchmark; detailed source and validation limits are recorded.
- 34 formal checks execute the production article program. The two-topic total is 64, including 49 core model checks plus manuscript, formula, figure and record checks; structural assertions are not independent model reproductions.
- Compared definitions, assumptions, 15 display equations, full code, actual output, four explained answers and scoped references across languages. AI-author review, not independent human expert review.
- Four original language/layout SVGs agree with program calculations and pass four-font bounds checks. Written-page language switching, copy, quiz, abbreviation search, three widths and actual long-formula scrolling were exercised; final checked-build verification is recorded separately.
- Checked camera center versus translation, exact-eight nullspace, 42 scalar-coordinate derivatives, missing-observation directional derivatives, Sampson approximation, point-block Schur versus dense solve, and gauge freedoms. Four injected errors are rejected with 57 observations; unit baseline and 0.1202936923 coordinate RMSE do not establish metric accuracy. Hartley reading is scoped, including visually inspected physical pages 4–5.
Source locations checked:
- Structure-from-Motion Revisited · Physical PDF pages 2–5 read; pipeline, verification, initialization, registration, triangulation and BA. No original system or benchmark reproduced. SHA-256 5d6896a33e55f508d0d7bd448d052b07a9aca046ceadc5fd84d0c1342d6575e6
- Bundle Adjustment — A Modern Synthesis · Physical PDF pages 21–22 and 36–37 read; Schur equations 16–20 and gauge freedoms. Exact publication date not independently verified; no priority claim. SHA-256 a42cbfbd0ffcfc9407a5da57d4b4bed45c91fac097c85ebf6ab0a37113ce2247
- COLMAP Rigid3d — fixed coordinate-transform conventions · Commit dbb4168000fa56bb93bfd978deea4346c55e7a45; lines 40–71 and 111–128 read; transform and inverse conventions only. Code not executed or copied.
- In Defense of the Eight-Point Algorithm · University-hosted original PAMI paper: first-page header/abstract text, physical pages 4–5 visually read. Sections 4.1–5.1 centering and mean-distance scaling; no benchmark adopted. PDF text body has broken font encoding. SHA-256 6cff3607cf54751b7ca75a45e3d261d9b5b028455a0c57108877abf5dd63ec9b
Related topics