Module contents
Lesson 20 of 33Advanced 120 min

Visual SLAM and visual-inertial odometry

Develop monocular visual odometry, bundle adjustment and Schur elimination, keyframe SLAM, IMU preintegration and visual-inertial odometry, and review learned dense SLAM.

After this lesson you can

  • Implement monocular visual odometry with features, eight-point estimation, triangulation and PnP.
  • Formulate bundle adjustment and solve it efficiently using the Schur complement.
  • Describe tracking, local mapping and loop closure in keyframe SLAM.
  • Derive IMU preintegration between keyframes and its role in visual-inertial odometry.
  • Explain monocular scale ambiguity and how IMU or stereo can resolve it.

Before you start

A camera sees direction, not meters

A camera and IMU can estimate motion without continuously receiving GPS. Images provide rich geometric constraints; the accelerometer and gyroscope provide temporal and metric information, but both have biases and need calibration. A visual-inertial system does not guarantee localization against a textureless wall, under degenerate motion, or with incompatible timestamps.

In the feature pipeline, a detector selects repeatable points and a descriptor summarizes their neighborhood. ORB uses corners and binary descriptors compared by Hamming distance. The ratio between the best and second neighbor can reject ambiguous matches; RANSAC tests geometric hypotheses and selects consensus. Repeated texture, moving objects, and low parallax still cause errors. A visual match is not yet a reliable 3D landmark.

Two views and odometry

Monocular visual odometry initializes two calibrated views with the essential matrix E=[t]×RE=[t]_\times R, decomposes its four candidates, and uses cheirality to select points in front of both cameras. Translation is recovered only up to scale. Triangulating with little parallax yields uncertain depths; under pure rotation, translation-based triangulation is degenerate. After creating 3D points, PnP estimates the next pose from 3D–2D correspondences and RANSAC guards against outliers. The reconstruction is updated and new points created when geometry permits.

The eight-point algorithm solves a linear system for the epipolar relation x2⊤Ex1=0x_2^\top E x_1=0, after normalizing coordinates to improve conditioning. The noisy resulting matrix is projected to a rank-two essential matrix with two equal singular values. High consensus does not guarantee good reconstruction: a nearly planar scene can also fit a homography, and small translation produces nearly parallel rays. Compare alternatives, triangulation angles, and positive depth before building the map.

For a point observed from several cameras, the angle between rays and pixel uncertainty determine depth uncertainty. A small residual can coexist with highly uncertain depth when rays have little parallax. PnP needs 3D–2D correspondences at a consistent scale and a nondegenerate spatial configuration; if points come from monocular reconstruction, the new translation inherits that arbitrary scale. RANSAC limits the influence of wrong correspondences, but a coherent set of outliers can form a false hypothesis.

For any s>0s>0, scaling centers and points by ss leaves pinhole camera pixels unchanged: both XcX_c and ZcZ_c change by the same factor. Global scale is part of the monocular gauge, along with rigid frame transformation. In sequential estimation scale can also drift, although ideal joint reconstruction has one indeterminate global scale. To evaluate a monocular trajectory against truth, align using a Sim(3) similarity and state whether alignment uses the entire trajectory; it can hide global scale errors, but not local scale changes.

InteractiveThe elusive scale

━ Estimate · dashed line: simulated truth. Monocular scale drifts by construction; this is not output from a real SLAM system.

Scale reference
6.0
Position error0.898 m
Synthetic planar model with prescribed scale drift, not a SLAM run. The IMU option integrates acceleration with known orientation, gravity, and initial velocity and small bias; stereo obtains depth from noisy disparity with known focal length and baseline. These are simplified scale references, not complete VIO.

A second camera with calibrated baseline provides metric distance: in rectified stereo Z=fB/dZ=fB/d. An IMU can provide scale through metric accelerations, but only if motion, gravity, biases, orientation, and time offset allow them to be separated. Motion without sufficient acceleration and other degeneracies weaken those constraints. The figure deliberately fixes several of these quantities; a real system must estimate or calibrate them.

Bundle adjustment and Schur

Bundle adjustment minimizes reprojection residuals rij=zij−π(Ti,Xj)r_{ij}=z_{ij}-\pi(T_i,X_j) over cameras and points, with weights and, where appropriate, robust losses. Fixing gauge is essential: a singular normal matrix is not repaired by attributing physical meaning to arbitrary damping. Local adjustment optimizes a window and its points and may hold some cameras fixed as a boundary; that choice conditions the solution.

After linearizing and writing Hδ=bH\delta=b, separate cameras cc and points pp:

[HccHcpHpcHpp][δcδp]=[bcbp],(Hcc−HcpHpp−1Hpc)δc=bc−HcpHpp−1bp.\begin{bmatrix}H_{cc}&H_{cp}\\H_{pc}&H_{pp}\end{bmatrix} \begin{bmatrix}\delta_c\\\delta_p\end{bmatrix}= \begin{bmatrix}b_c\\b_p\end{bmatrix},\quad (H_{cc}-H_{cp}H_{pp}^{-1}H_{pc})\delta_c=b_c-H_{cp}H_{pp}^{-1}b_p.

The Schur complement eliminates points first and then recovers δp=Hpp−1(bp−Hpcδc)\delta_p=H_{pp}^{-1}(b_p-H_{pc}\delta_c). Without factors connecting points to each other, HppH_{pp} decomposes into 3×33\times3 blocks; solve each block instead of forming inverses. Reduction can create connections between cameras observing the same point, so it is not always sparse. A poorly observed point can make its block singular: use an appropriate model, elimination or damping and check conditioning.

The right-hand side changes with the matrix: forgetting HcpHpp−1bpH_{cp}H_{pp}^{-1}b_p solves a different problem. After recovering points, compare the full step with a dense solve on a small case; this detects incorrect signs and transposes. In LM, damping is added to blocks before elimination, and the step is accepted based on nonlinear cost. Linear approximation and observation covariances must use the same units, for example pixels or normalized coordinates, not a mixture.

InteractiveThe bundle-adjustment arrow

The camera block occupies the first 12 rows and columns. Reduction eliminates 15 point parameters; both results were checked against a dense solve.

System
Dimension27 × 27
Solution difference6.4e-15
Synthetic numerical system with two free cameras and five points, built from a Jacobian with observation structure. The reduced matrix and full solution were actually calculated; the data are not a camera reconstruction.

With 50 six-parameter cameras and 20 000 three-parameter points, there are 60 300 variables versus 300 in the camera system. If both matrices were dense float64, they would occupy approximately 27.09 GiB and 0.687 MiB respectively. That dense-storage comparison excludes point blocks, observations, fill, and reduced-system construction cost. Large problems use sparse structures and suitable solvers.

Keyframes and preintegration

Keyframe SLAM such as ORB-SLAM combines frame tracking, local mapping, keyframe selection, local optimization, and loop recognition. Selecting keyframes balances parallax, coverage, and cost; too many increase computation, too few may lose geometry. Loop closure verifies a match and corrects drift; it does not replace tracking or make association infallible.

IMU preintegration summarizes many samples between keyframes without adding a variable per sample. With RiR_i from body to world and gravity gg in world coordinates,

ΔRij=Ri⊤Rj,Δvij=Ri⊤(vj−vi−gΔt),Δpij=Ri⊤(pj−pi−viΔt−12gΔt2).\Delta R_{ij}=R_i^\top R_j,\quad \Delta v_{ij}=R_i^\top(v_j-v_i-g\Delta t),\quad \Delta p_{ij}=R_i^\top(p_j-p_i-v_i\Delta t-\tfrac12g\Delta t^2).

Angular rates and specific forces are integrated after subtracting biases, together with covariance and bias Jacobians. If the bias estimate changes little, a first-order correction approximates reintegration; large changes or incompatible models require reintegration. Rotation is corrected on SO(3), not by adding matrices. Forster and colleagues formulate manifold preintegration and its uncertainties.

With step Δt\Delta t and preintegrated rotation ΔRk\Delta R_k, a simple discretization updates Δp←Δp+ΔvΔt+12ΔRk(am−ba)Δt2\Delta p\leftarrow\Delta p+\Delta v\Delta t+\tfrac12\Delta R_k(a_m-b_a)\Delta t^2, Δv←Δv+ΔRk(am−ba)Δt\Delta v\leftarrow\Delta v+\Delta R_k(a_m-b_a)\Delta t and ΔR←ΔRExp⁡((ωm−bg)Δt)\Delta R\leftarrow\Delta R\operatorname{Exp}((\omega_m-b_g)\Delta t). Order matters: velocity and position use the rotation at the start of the step in this scheme. The cell uses that discrete-time approximation and holds biases constant during the interval; unlike a production inertial factor, it does not propagate full covariance.

Gyro bias changes the orientation of integrated specific force, so it also affects Δv\Delta v and Δp\Delta p. The figure compares those three effects with exact reintegration of the same discrete samples; “exact” means repeating that integrator, not solving continuous physics exactly. The demonstration’s numerical Jacobians do not replace analytic covariance propagation required by a robust estimator.

InteractivePreintegrating between keyframes
ΔvxΔvyΔvz

■ Reintegration · ■ First-order correction. Errors compare rotation, velocity and position, not a measured trajectory.

0.00
Angular error0.000000 rad
Error Δv0.00000 m/s
Error Δp0.00000 m
One hundred synthetic 0.01 s samples; reintegration is compared with a first-order correction around nominal bias, whose Jacobian is calculated by central differences. The plot shows Δv in the initial frame; ΔR, Δv and Δp errors are calculated against reintegration.
[ ]Reintegration and bias correctionBrowser
import numpy as np
from scipy.spatial.transform import Rotation
dt=.01;times=np.arange(100)*dt
omega=np.c_[.2*np.sin(times),.15*np.ones(len(times)),.3+.1*np.cos(times)]
acc=np.c_[.4*np.ones(len(times)),.2*np.sin(times),9.81*np.ones(len(times))]
bg=np.array([.02,-.01,.015]);ba=np.array([.05,-.03,.02]);wm=omega+bg;am=acc+ba
def integrate(bg,ba):
    R=np.eye(3);v=np.zeros(3);p=np.zeros(3)
    for w,a in zip(wm,am):
        p+=v*dt+.5*(R@(a-ba))*dt**2;v+=R@(a-ba)*dt;R=R@Rotation.from_rotvec((w-bg)*dt).as_matrix()
    return R,v,p
R0,v0,p0=integrate(bg,ba);h=1e-5;Jr=np.zeros((3,3));Jv=np.zeros((3,3));Jp=np.zeros((3,3))
for k in range(3):
    d=np.eye(3)[k]*h;Rp,vp,pp=integrate(bg+d,ba);Rm,vm,pm=integrate(bg-d,ba)
    Jr[:,k]=(Rotation.from_matrix(R0.T@Rp).as_rotvec()-Rotation.from_matrix(R0.T@Rm).as_rotvec())/(2*h)
    Jv[:,k]=(vp-vm)/(2*h);Jp[:,k]=(pp-pm)/(2*h)
pre=[]
for i in range(-10,11):
    delta=np.array([i*.01,0,0]);R,v,p=integrate(bg+delta,ba)
    Rc=R0@Rotation.from_rotvec(Jr@delta).as_matrix();vc=v0+Jv@delta;pc=p0+Jp@delta
    pre.append({'bias':round(i*.01,2),'exactV':v.round(4).tolist(),'correctedV':vc.round(4).tolist(),
                'rotError':round(float(Rotation.from_matrix(Rc.T@R).magnitude()),7),
                'vError':round(float(np.linalg.norm(vc-v)),6),'pError':round(float(np.linalg.norm(pc-p)),6)})

print('cambio +0.10 rad/s:',pre[-1])

Visual-inertial odometry can use a filter such as MSCKF, which projects feature constraints while eliminating their positions, or sliding-window optimization with states, points, and inertial factors. To limit cost, marginalizing old states retains a condensed constraint on the remainder; discarding them without it loses information. The marginalized prior is tied to a linearization point, so relinearizing some variables while freezing others can change observability and consistency. Sensor extrinsics and timing must also be calibrated.

A camera–IMU time offset can resemble a rotation or translation error when the robot turns. Spatial calibration fixes the transformation between frames; temporal calibration relates capture instants, not just arrival. In a windowed filter, feature projection eliminates point variables using a basis of the appropriate Jacobian’s null space, whereas Schur eliminates them from normal equations. Both methods retain constraints between states under their linearized assumptions, but are not identical implementations and do not themselves solve association errors.

Learned models and scope

Learned dense SLAM uses networks to construct or refine correspondences, depth, and constraints. DROID-SLAM combines learned updates with geometric adjustment; MASt3R-SLAM uses 3D reconstruction priors and dense matching. Do not turn these descriptions into measurements from this machine. The official DROID-SLAM repository states at least 11 GB for its demos, above the 8 GB planned in this design; no learned model was run here under that limit.

Lab: geometry and adjustment from scratch

The synthetic scene has 80 points, three calibrated cameras, and image noise in normalized coordinates. Eight correspondences in the second view are altered. EE is estimated using eight points and RANSAC, inliers are triangulated, the third pose is estimated by DLT resection and RANSAC, points and the third camera are refined using Schur and LM, and new points are triangulated in views two and three. The first two cameras remain fixed: this removes gauge and also conditions the solution on the estimated second pose, so it is not unconstrained global BA. The camera Jacobian is approximated by central differences; the point Jacobian is analytic.

[ ]Two views, PnP and SchurBrowser
import numpy as np
from scipy.spatial.transform import Rotation
from scipy.optimize import least_squares

def project(R,t,points):
    q=(R@points.T).T+t;return q[:,:2]/q[:,2,None]
def normalize(points):
    center=points.mean(axis=0);scale=np.sqrt(2)/np.mean(np.linalg.norm(points-center,axis=1))
    T=np.array([[scale,0,-scale*center[0]],[0,scale,-scale*center[1]],[0,0,1.]])
    return (T@np.c_[points,np.ones(len(points))].T).T[:,:2],T
def eight_point(a,b):
    a,Ta=normalize(a);b,Tb=normalize(b);x,y=a.T;u,v=b.T
    A=np.column_stack((u*x,u*y,u,v*x,v*y,v,x,y,np.ones(len(a))))
    _,_,V=np.linalg.svd(A,full_matrices=True);F=V[-1].reshape(3,3);U,S,V=np.linalg.svd(F);S[-1]=0
    E=Tb.T@(U@np.diag(S)@V)@Ta;U,S,V=np.linalg.svd(E)
    return U@np.diag([(S[0]+S[1])/2]*2+[0])@V
def sampson(E,a,b):
    a=np.c_[a,np.ones(len(a))];b=np.c_[b,np.ones(len(b))];Ea=(E@a.T).T;Etb=(E.T@b.T).T
    numerator=np.sum(b*Ea,axis=1)**2;return numerator/(Ea[:,0]**2+Ea[:,1]**2+Etb[:,0]**2+Etb[:,1]**2+1e-20)
def robust_eight(a,b,rng,trials=500,threshold=.004):
    best=np.zeros(len(a),bool)
    for _ in range(trials):
        ids=rng.choice(len(a),8,replace=False);E=eight_point(a[ids],b[ids]);mask=sampson(E,a,b)<threshold**2
        if mask.sum()>best.sum():best=mask
    if best.sum()<8:raise ValueError('sin suficientes correspondencias')
    return eight_point(a[best],b[best]),best
def triangulate(P,Q,a,b):
    result=[]
    for (x,y),(u,v) in zip(a,b):
        A=np.stack([x*P[2]-P[0],y*P[2]-P[1],u*Q[2]-Q[0],v*Q[2]-Q[1]])
        _,_,V=np.linalg.svd(A);X=V[-1];result.append(X[:3]/X[3])
    return np.array(result)
def decompose(E,a,b):
    U,_,V=np.linalg.svd(E)
    if np.linalg.det(U)<0:U[:,-1]*=-1
    if np.linalg.det(V)<0:V[-1]*=-1
    W=np.array([[0.,-1.,0.],[1.,0.,0.],[0.,0.,1.]])
    P=np.c_[np.eye(3),np.zeros(3)];best=None
    for R in (U@W@V,U@W.T@V):
        for t in (U[:,2],-U[:,2]):
            X=triangulate(P,np.c_[R,t],a,b);score=np.sum((X[:,2]>0)&(((R@X.T).T+t)[:,2]>0))
            if best is None or score>best[0]:best=(score,R,t,X)
    return best[1:]
def dlt_pose(X,z):
    Xh=np.c_[X,np.ones(len(X))];zero=np.zeros_like(Xh);u,v=z.T
    A=np.empty((2*len(X),12));A[0::2]=np.c_[Xh,zero,-u[:,None]*Xh];A[1::2]=np.c_[zero,Xh,-v[:,None]*Xh]
    _,_,V=np.linalg.svd(A,full_matrices=False);P=V[-1].reshape(3,4)
    if np.linalg.det(P[:,:3])<0:P=-P
    U,s,V=np.linalg.svd(P[:,:3]);R=U@V
    if np.linalg.det(R)<0:U[:,-1]*=-1;R=U@V
    return R,P[:,3]/np.mean(s)
def pose_refine(R,t,X,z):
    start=np.r_[Rotation.from_matrix(R).as_rotvec(),t]
    def fun(p):return (project(Rotation.from_rotvec(p[:3]).as_matrix(),p[3:],X)-z).ravel()
    result=least_squares(fun,start,max_nfev=80)
    return Rotation.from_rotvec(result.x[:3]).as_matrix(),result.x[3:]
def pnp_ransac(X,z,rng,trials=350,threshold=.01):
    best=np.zeros(len(X),bool);pose=None
    for _ in range(trials):
        ids=rng.choice(len(X),8,replace=False)
        try:R,t=dlt_pose(X[ids],z[ids]);pred=project(R,t,X)
        except np.linalg.LinAlgError:continue
        depth=((R@X.T).T+t)[:,2];mask=(np.linalg.norm(pred-z,axis=1)<threshold)&(depth>0)
        if mask.sum()>best.sum():best=mask;pose=(R,t)
    if best.sum()<8:raise ValueError('PnP no encontró consenso')
    R,t=pose_refine(*pose,X[best],z[best]);return R,t,best
def ba_schur(cameras,points,observations,iterations=8):
    # Camera 0 and 1 are fixed to remove world and scale gauge; camera 2 is optimized.
    p=np.r_[Rotation.from_matrix(cameras[2][0]).as_rotvec(),cameras[2][1]].copy();X=points.copy();lam=1e-3
    def residuals(p,X):
        cams=[cameras[0],cameras[1],(Rotation.from_rotvec(p[:3]).as_matrix(),p[3:])]
        return np.stack([project(R,t,X)-z for (R,t),z in zip(cams,observations)])
    cost=float(np.sum(residuals(p,X)**2));history=[cost]
    for _ in range(iterations):
        rr=residuals(p,X);R=Rotation.from_rotvec(p[:3]).as_matrix();t=p[3:]
        Hcc=np.zeros((6,6));bc=np.zeros(6);Hpp=[];bp=[];Hcp=[]
        for j in range(len(X)):
            C=np.zeros((3,3));b=np.zeros(3);B=np.zeros((6,3))
            for k,((Rc,tc),z) in enumerate(zip([cameras[0],cameras[1],(R,t)],observations)):
                q=Rc@X[j]+tc;u,v,d=q;D=np.array([[1/d,0,-u/d**2],[0,1/d,-v/d**2]])
                Jp=D@Rc;r=rr[k,j];C+=Jp.T@Jp;b-=Jp.T@r
                if k==2:
                    Jc=np.empty((2,6));h=1e-6
                    for a in range(6):
                        dparam=np.eye(6)[a]*h
                        Jc[:,a]=(project(Rotation.from_rotvec((p+dparam)[:3]).as_matrix(),(p+dparam)[3:],X[j:j+1])[0]-project(Rotation.from_rotvec((p-dparam)[:3]).as_matrix(),(p-dparam)[3:],X[j:j+1])[0])/(2*h)
                    Hcc+=Jc.T@Jc;bc-=Jc.T@r;B+=Jc.T@Jp
            Hpp.append(C+lam*np.eye(3));bp.append(b);Hcp.append(B)
        S=Hcc+lam*np.eye(6);rhs=bc.copy()
        for C,b,B in zip(Hpp,bp,Hcp):S-=B@np.linalg.solve(C,B.T);rhs-=B@np.linalg.solve(C,b)
        dc=np.linalg.solve(S,rhs);dx=np.array([np.linalg.solve(C,b-B.T@dc) for C,b,B in zip(Hpp,bp,Hcp)])
        pn=p+dc;Xn=X+dx;new=float(np.sum(residuals(pn,Xn)**2))
        if new<cost:p,X,cost=pn,Xn,new;lam=max(lam/3,1e-8)
        else:lam*=10
        history.append(cost)
    return (Rotation.from_rotvec(p[:3]).as_matrix(),p[3:]),X,np.array(history)
def experiment(seed=4):
    rng=np.random.default_rng(seed);N=80
    X=np.column_stack((rng.uniform(-1,1,N),rng.uniform(-.8,.8,N),rng.uniform(3,6,N)))
    R0=np.eye(3);t0=np.zeros(3);R1=Rotation.from_euler('y',-3,degrees=True).as_matrix();t1=-R1@np.array([.4,0,0])
    R2=Rotation.from_euler('y',-6,degrees=True).as_matrix();t2=-R2@np.array([.8,.1,0])
    obs=[project(R,t,X)+rng.normal(0,.0005,(N,2)) for R,t in [(R0,t0),(R1,t1),(R2,t2)]]
    corrupt=obs[1].copy();bad=rng.choice(N,8,replace=False);corrupt[bad]=rng.uniform(-.3,.3,(len(bad),2))
    E,mask=robust_eight(obs[0],corrupt,rng);R,t,Xinit=decompose(E,obs[0][mask],corrupt[mask])
    valid=(Xinit[:,2]>0)&(((R@Xinit.T).T+t)[:,2]>0);ids=np.flatnonzero(mask)[valid];Xinit=Xinit[valid]
    R3,t3,inliers=pnp_ransac(Xinit,obs[2][ids],rng);ids=ids[inliers];Xinit=Xinit[inliers]
    cameras=[(R0,t0),(R,t),(R3,t3)];newcam,newpoints,cost=ba_schur(cameras,Xinit,[z[ids] for z in obs])
    fresh=np.column_stack((rng.uniform(-1,1,25),rng.uniform(-.8,.8,25),rng.uniform(3,6,25)))
    fresh1=project(R1,t1,fresh)+rng.normal(0,.0005,(25,2));fresh2=project(R2,t2,fresh)+rng.normal(0,.0005,(25,2))
    extra=triangulate(np.c_[R,t],np.c_[newcam[0],newcam[1]],fresh1,fresh2)
    good=(((R@extra.T).T+t)[:,2]>0)&(((newcam[0]@extra.T).T+newcam[1])[:,2]>0)
    reproj=np.linalg.norm(project(newcam[0],newcam[1],extra[good])-fresh2[good],axis=1)
    print('E consenso:',int(mask.sum()),'atípicos aceptados:',int(np.intersect1d(ids,bad).size),'PnP:',len(ids))
    print('error normalizado antes/después BA:',round(float(np.sqrt(cost[0]/(len(ids)*3*2))),7),round(float(np.sqrt(cost[-1]/(len(ids)*3*2))),7))
    print('pasos coste BA:',np.round(cost,6))
    print('nuevos puntos delante:',int(good.sum()),'mediana reproyección normalizada:',round(float(np.median(reproj)),7))
    r1err=np.degrees(Rotation.from_matrix(R@R1.T).magnitude())
    angle=np.degrees(np.arccos(np.clip(t@t1/(np.linalg.norm(t)*np.linalg.norm(t1)),-1,1)))
    r2err=np.degrees(Rotation.from_matrix(newcam[0]@R2.T).magnitude())
    center=-newcam[0].T@newcam[1];center_true=np.array([.8,.1,0.])/.4
    print('errores rot1/dirección/rot2 (grados):',round(float(r1err),3),round(float(angle),3),round(float(r2err),3))
    print('error centro 3 en unidades de línea base:',round(float(np.linalg.norm(center-center_true)),4))
    return cameras,newcam,Xinit,newpoints,cost,obs,ids
experiment()

For the indicated seed there were 72 accepted initial correspondences, none of the eight altered ones among those used by PnP, and 72 PnP inliers. Normalized per-coordinate RMS fell from 0.0011331 to 0.0010252. All 25 new points lay in front of both cameras and their median normalized reprojection was 0.0007522. Against synthetic truth, second-camera rotation, translation-direction, and third-camera rotation errors after BA were 0.475°, 0.513° and 0.772°; third-camera center error was 0.0288 baseline units. True baseline is used only in this evaluation, not the estimator. These are results from an artificial scene, not a real-vision benchmark or proof of metric accuracy.

Local lab: ORB on rendered images

MuJoCo generates 35 images of boxes at varying depths and a moving camera; OpenCV detects ORB, filters matches, estimates the essential matrix, and accumulates relative poses. Each recovered translation has unit norm: it is not a metric estimate per frame. Sim(3) alignment uses all truth from the simulated trajectory, so the resulting ATE evaluates shape after alignment and does not measure absolute scale. In one run with seed 52 there were a median 611.5 and minimum 405 cheirality inliers, aligned scale 0.073325, and ATE RMS 0.116774 m. Maximum cheirality depth was fixed at 1000 units of normalized translation; accepting distant points does not make them accurate. The scene is rendered, without physical camera data.

In a compatible local environment install dependencies with python -m pip install numpy mujoco==4.0.1 opencv-python-headless==5.0.0.93. Rendering needs a working OpenGL backend; colors, drivers, and versions can change detected points. The code sets the OpenCV seed and checks alignment against a known synthetic similarity before printing ATE.

[ ]ORB in MuJoCo and aligned ATELocal GPU
import os
import numpy as np
import cv2
import mujoco

rng=np.random.default_rng(52);cv2.setRNGSeed(52);geoms=[]
# Many small fixed objects at different depths form parallax and visual corners.
for i in range(250):
    x=rng.uniform(-2.2,2.2);y=rng.uniform(-1.6,1.6);z=rng.uniform(-6,-2)
    size=rng.uniform(.025,.09);c=rng.uniform(.15,1.,3)
    geoms.append(f'<geom type="box" pos="{x} {y} {z}" size="{size} {size} {size}" rgba="{c[0]} {c[1]} {c[2]} 1"/>')
xml=f'''<mujoco><visual><global offwidth="640" offheight="480"/></visual>
<worldbody><light pos="0 0 0" dir="0 0 -1" diffuse=".8 .8 .8" ambient=".5 .5 .5"/>
<body name="rig"><freejoint/><geom type="sphere" size=".01" mass="1" rgba="0 0 0 0"/>
<camera name="cam" pos="0 0 0" fovy="50"/></body>{''.join(geoms)}</worldbody></mujoco>'''
model=mujoco.MjModel.from_xml_string(xml);data=mujoco.MjData(model);renderer=mujoco.Renderer(model,480,640)
f=480/(2*np.tan(np.deg2rad(50)/2));K=np.array([[f,0,320],[0,f,240],[0,0,1.]])
orb=cv2.ORB_create(nfeatures=2000);matcher=cv2.BFMatcher(cv2.NORM_HAMMING);previous=None
Rcw=np.eye(3);tcw=np.zeros((3,1));estimate=[np.zeros(3)];truth=[np.zeros(3)];counts=[]
for k in range(35):
    a=k*.035;pos=np.array([.65*np.sin(a),.35*(1-np.cos(a)),0.])
    data.qpos[:3]=pos;data.qpos[3:7]=[1,0,0,0];mujoco.mj_forward(model,data);renderer.update_scene(data,camera='cam')
    rgb=renderer.render();gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);kp,desc=orb.detectAndCompute(gray,None)
    if k==0 and os.environ.get('VO_FIRST_IMAGE'):cv2.imwrite(os.environ['VO_FIRST_IMAGE'],cv2.cvtColor(rgb,cv2.COLOR_RGB2BGR))
    if previous is None:previous=(kp,desc);continue
    oldkp,old=previous;previous=(kp,desc)
    if old is None or desc is None:raise RuntimeError('sin descriptores')
    matches=matcher.knnMatch(old,desc,k=2);good=[a for pair in matches if len(pair)==2 for a,b in [pair] if a.distance<.75*b.distance]
    if len(good)<12:raise RuntimeError(f'pocas correspondencias en {k}: {len(good)}')
    a=np.float32([oldkp[m.queryIdx].pt for m in good]);b=np.float32([kp[m.trainIdx].pt for m in good])
    E,mask=cv2.findEssentialMat(a,b,K,method=cv2.RANSAC,prob=.999,threshold=1.)
    if E is None:raise RuntimeError('matriz esencial no estimada')
    _,R,t,inlier,_=cv2.recoverPose(E[:3,:3],a,b,K,distanceThresh=1000.,mask=mask)
    count=int(np.count_nonzero(inlier));counts.append(count)
    if count<8:raise RuntimeError(f'pocos inliers con quiralidad: {count}')
    Rcw=R@Rcw;tcw=R@tcw+t;estimate.append((-Rcw.T@tcw).ravel());truth.append(np.array([pos[0],-pos[1],0.]))
renderer.close();estimate=np.array(estimate);truth=np.array(truth)
def align_sim3(source,target):
    a=source-source.mean(0);b=target-target.mean(0);U,s,Vt=np.linalg.svd(b.T@a/len(a));D=np.eye(3);D[-1,-1]=np.linalg.det(U@Vt)
    R=U@D@Vt;scale=np.sum(s*np.diag(D))/np.mean(np.sum(a*a,axis=1));offset=target.mean(0)-scale*R@source.mean(0)
    return (scale*(R@source.T)).T+offset,scale
aligned,scale=align_sim3(estimate,truth);errors=np.linalg.norm(aligned-truth,axis=1)
test=np.random.default_rng(3).normal(size=(20,3));angle=.4
rotation=np.array([[np.cos(angle),-np.sin(angle),0.],[np.sin(angle),np.cos(angle),0.],[0.,0.,1.]])
expected=2.3*(rotation@test.T).T+np.array([1.,-2.,.5]);recovered,_=align_sim3(test,expected)
assert np.max(np.abs(recovered-expected))<1e-10
print('fotogramas:',len(truth),'inliers mediana/min:',float(np.median(counts)),int(np.min(counts)))
print('escala Sim(3):',round(float(scale),6),'ATE RMS (m):',round(float(np.sqrt(np.mean(errors**2))),6),'máximo:',round(float(errors.max()),6))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofEliminating points
Prove: Derive the reduced camera system and point recovery.
0
Assume Hpp is invertible and observations do not connect points to each other.

Step 1 of 3. What follows from the system's second row?

ProofThe invisible similarity
Prove: Prove the scale ambiguity of calibrated monocular reconstruction.
0
Consider centers and points scaled by s > 0, with fixed orientations.

Step 1 of 3. How does the camera-to-point vector change in camera coordinates?

Numeric
With 50 six-parameter cameras and 20 000 three-parameter points, how many variables does the full system have before fixing gauge?
CodeSolve by blocks
Implement schur_solve(H_cc, H_cp, H_pp_blocks, b_c, b_p). H_cp has shape (C,3P), H_pp_blocks (P,3,3), b_c (C,) and b_p (P,3). Return (delta_c, delta_p) with delta_p of shape (P,3). The blocks and reduced system are invertible.
import numpy as np
def schur_solve(H_cc, H_cp, H_pp_blocks, b_c, b_p):
  pass
Shift+Enter to run
Quiz
Why marginalize old states in VIO instead of simply discarding them?
Key idea
Visual reconstruction needs well-defined observability, gauge, and calibration. IMU and stereo add metric constraints, but their quality depends on motion, biases, and synchronization.

Sources: ORB-SLAM, ORB-SLAM3, Forster and colleagues, preintegration, DROID-SLAM and MASt3R-SLAM.