AnyLearn
All lessons
Roboticsadvanced

Cameras and Visual Perception

From photons to 3D geometry: the pinhole model, intrinsic matrix K, lens distortion, feature matching, stereo depth, and where CNNs help (and fail) in robot perception pipelines.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 9

The pinhole camera model

A pinhole camera maps a 3D point P=[X,Y,Z]\mathbf{P} = [X, Y, Z]^\top (in camera coordinates) to a 2D pixel p=[u,v]\mathbf{p} = [u, v]^\top by perspective projection:

u=fxXZ+cx,v=fyYZ+cyu = f_x \frac{X}{Z} + c_x, \quad v = f_y \frac{Y}{Z} + c_y

In homogeneous form this is λp~=KP\lambda\,\tilde{\mathbf{p}} = K\,\mathbf{P}, where λ=Z\lambda = Z and the intrinsic matrix is

K=[fxscx0fycy001]K = \begin{bmatrix} f_x & s & c_x \\ 0 & f_y & c_y \\ 0 & 0 & 1 \end{bmatrix}

fx,fyf_x, f_y are focal lengths in pixels; (cx,cy)(c_x, c_y) is the principal point (typically near image center); ss is the skew (zero for modern sensors). The pinhole model is linear after the perspective divide — that linearity is what makes calibration tractable. The division by ZZ destroys depth: all 3D points on the same ray project to the same pixel, so the inverse mapping is a ray, not a unique 3D location.

Full lesson text

All 9 steps on one page, for reading, reference, and search.

Show

1. The pinhole camera model

A pinhole camera maps a 3D point P=[X,Y,Z]\mathbf{P} = [X, Y, Z]^\top (in camera coordinates) to a 2D pixel p=[u,v]\mathbf{p} = [u, v]^\top by perspective projection:

u=fxXZ+cx,v=fyYZ+cyu = f_x \frac{X}{Z} + c_x, \quad v = f_y \frac{Y}{Z} + c_y

In homogeneous form this is λp~=KP\lambda\,\tilde{\mathbf{p}} = K\,\mathbf{P}, where λ=Z\lambda = Z and the intrinsic matrix is

K=[fxscx0fycy001]K = \begin{bmatrix} f_x & s & c_x \\ 0 & f_y & c_y \\ 0 & 0 & 1 \end{bmatrix}

fx,fyf_x, f_y are focal lengths in pixels; (cx,cy)(c_x, c_y) is the principal point (typically near image center); ss is the skew (zero for modern sensors). The pinhole model is linear after the perspective divide — that linearity is what makes calibration tractable. The division by ZZ destroys depth: all 3D points on the same ray project to the same pixel, so the inverse mapping is a ray, not a unique 3D location.

2. Extrinsics and the full projection pipeline

The intrinsic matrix KK lives in camera space. To project a world point Pw\mathbf{P}_w, you first transform it into camera coordinates via the extrinsic rotation RSO(3)R \in SO(3) and translation t\mathbf{t}:

Pc=RPw+t\mathbf{P}_c = R\,\mathbf{P}_w + \mathbf{t}

The complete projection is λp~=K[R    t]P~w\lambda\,\tilde{\mathbf{p}} = K[R\;|\;\mathbf{t}]\,\tilde{\mathbf{P}}_w, giving a 3×43 \times 4 camera matrix P=K[R    t]P = K[R\;|\;\mathbf{t}].

For a robot, RR and t\mathbf{t} encode the camera's pose — which changes every time the robot moves. KK is fixed at manufacturing. Getting KK wrong by even a few pixels in principal point or 0.5% in focal length compounds downstream in any structure-from-motion or visual odometry pipeline. Extrinsic calibration (camera-to-LiDAR, camera-to-IMU) is a separate problem — and even 1° of angular error in a camera-LiDAR extrinsic produces metres of pixel misalignment at 20 m range.

3. Lens distortion and calibration

Real lenses deviate from the ideal pinhole. The dominant term is radial distortion: straight lines bow inward (barrel) or outward (pincushion). The distortion model maps an ideal pixel p\mathbf{p} to an observed pixel p\mathbf{p}':

r2=(ucx)2+(vcy)2r^2 = (u - c_x)^2 + (v - c_y)^2 u=u(1+k1r2+k2r4+k3r6)+tangential termsu' = u(1 + k_1 r^2 + k_2 r^4 + k_3 r^6) + \text{tangential terms}

Calibration via a checkerboard (Zhang's method) jointly estimates KK and the distortion coefficients [k1,k2,k3,p1,p2][k_1, k_2, k_3, p_1, p_2]. With OpenCV:

import cv2
ret, K, dist, rvecs, tvecs = cv2.calibrateCamera(
    obj_points, img_points, img_size, None, None
)
# Undistort a frame:
img_rect = cv2.undistort(frame, K, dist)

Never skip calibration. A well-calibrated fisheye with k1=0.4k_1 = -0.4 will project more accurately than a poorly-calibrated telephoto. Target <0.5< 0.5 px RMS reprojection error.

4. Features: corners, ORB, and matching

To track the camera or recognize objects, we need repeatable keypoints — image locations detectable from multiple viewpoints. The Harris corner detector finds pixels where image intensity varies strongly in two directions (large λmin\lambda_{\min} of the second-moment matrix). ORB (Oriented FAST + Rotated BRIEF) extends this with a binary descriptor computed from intensity comparisons:

orb = cv2.ORB_create(nfeatures=500)
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False)
matches = bf.knnMatch(des1, des2, k=2)
# Lowe ratio test
good = [m for m, n in matches if m.distance < 0.75 * n.distance]

After matching, RANSAC + the essential matrix filters outliers. The essential matrix E=[t]×RE = [\mathbf{t}]_\times R encodes relative camera motion and satisfies p2Ep1=0\mathbf{p}_2^\top E\, \mathbf{p}_1 = 0 for true correspondences. Outlier rates of 60-80% are common in textureless environments — always check inlier count before trusting a pose estimate.

5. Stereo vision and disparity

A calibrated stereo pair with baseline bb and focal length ff recovers depth ZZ from the disparity d=uLuRd = u_L - u_R (horizontal pixel shift between left and right views):

Z=fbdZ = \frac{f \cdot b}{d}

Depth uncertainty scales with Z2Z^2: double the range and depth error quadruples. The stereo matching problem (finding corresponding pixels) is solved by SGM (Semi-Global Matching) in OpenCV's StereoSGBM. Failure modes include textureless surfaces (no gradient \Rightarrow ambiguous disparity), transparent objects, and specular reflections. Stereo works poorly beyond bf/1 pxb \cdot f / 1\text{ px} — roughly 10 m for a 12 cm baseline with f=700f = 700 px. Baseline is a design tradeoff: wider bb improves long-range depth but creates more occlusion near the stereo boundary.

6. CNNs in robot perception: gains and limits

Deep networks have transformed robot perception. Key capabilities:

TaskApproachLatency (GPU)
Object detectionYOLOv8, DETR5-20 ms
Semantic segmentationSegFormer, Mask2Former20-80 ms
Monocular depthDPT, Depth Anything30-100 ms
6-DOF pose estimationPoseCNN, FoundPose50-200 ms

But CNNs have failure modes a perception engineer must know: (1) domain shift — a model trained on indoor images fails outdoors in rain; (2) scale ambiguity — monocular depth networks cannot recover metric scale without additional supervision; (3) adversarial fragility — small perturbations fool detectors with high confidence; (4) latency on edge hardware — a model fast on a V100 may be too slow on a Jetson Orin without quantization. Always validate on your deployment distribution, not just the benchmark.

7. Camera projection pipeline

From world coordinates to pixel — the full chain.

flowchart LR
  W["World point P_w"]
  E["Extrinsics R and t"]
  C["Camera coords P_c"]
  K["Intrinsics K"]
  H["Homogeneous pixel"]
  D["Distortion model"]
  P["Observed pixel p prime"]
  W --> E
  E --> C
  C --> K
  K --> H
  H --> D
  D --> P

8. Visual odometry and its drift

Visual odometry (VO) chains pairwise camera pose estimates to track robot motion. The algorithm at each frame: detect features \rightarrow match to prior frame \rightarrow estimate essential matrix \rightarrow recover R,tR, \mathbf{t} via decomposition \rightarrow triangulate new map points. The recovered translation is scale-ambiguous per frame; monocular VO fixes scale heuristically or with an IMU.

The painful truth: VO drifts. Without loop closure, a 100 m trajectory can accumulate 2-5% positional error. SLAM systems (covered in a later lesson) add loop-closure detection to correct accumulated drift globally. VO is still useful for short horizons and for bootstrapping a SLAM system's front end. A good rule of thumb: if your robot needs to return to a starting location, VO alone is insufficient — you need a map.

9. Choosing and combining sensors

No single camera configuration is best for all robot tasks. Practical tradeoffs:

SensorStrengthsWeaknesses
Monocular RGBCheap, light, rich textureNo metric depth, scale drift
Stereo RGBMetric depth, passiveDepth degrades beyond 10 m, needs calibration
RGB-D structured lightDense depth indoorsFails outdoors, sunlight interference
Event cameraHigh dynamic range, microsecond latencySparse output, immature software stack
Camera + IMU (VIO)Metric scale, robust to blurIMU bias drift, tight synchronization needed

For production robots, fusing a stereo camera with an IMU (VIO) and optionally LiDAR (covered next) is the current best practice for robust state estimation in unstructured environments.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. In the pinhole model $\lambda\,\tilde{\mathbf{p}} = K\mathbf{P}$, what does $\lambda$ equal?
    • The focal length $f_x$
    • The depth $Z$ of the 3D point
    • The image diagonal in pixels
    • The inverse of the principal point offset
  2. Stereo depth from disparity $d$ is $Z = fb/d$. If the baseline doubles and disparity stays constant, depth:
    • Halves
    • Stays the same
    • Doubles
    • Quadruples
  3. ORB descriptors use BRIEF, which compares pixel intensities. What makes ORB rotation-invariant?
    • It normalizes the descriptor by the image gradient magnitude
    • It orients the descriptor patch using the keypoint intensity centroid (dominant orientation)
    • It applies a Gaussian blur before computing comparisons
    • It uses Hessian matrix eigenvalues to align the patch
  4. A monocular CNN depth estimator produces visually plausible depth maps but wrong metric distances. The most likely cause is:
    • Radial distortion that was not corrected before inference
    • The model was trained without metric scale supervision and cannot recover absolute depth
    • The network uses too few parameters for the input resolution
    • Feature matching failed on textureless surfaces
  5. The essential matrix $E = [\mathbf{t}]_\times R$ encodes what information?
    • The intrinsic parameters $K$ of both cameras
    • The relative rotation and translation between two calibrated cameras
    • The disparity map between stereo frames
    • The distortion coefficients of the lens

Related lessons

Robotics
advanced

Modelling Interaction: From Social Forces to Social Pooling

How the field learned to represent people influencing each other: the physics-inspired force model, the Social LSTM pooling layer that replaced hand-designed rules with learned ones, and the attention and graph architectures that followed.

8 steps·~12 min
Robotics
advanced

Predicting Where People Will Walk

Why forecasting human motion is not a physics problem: the multimodality that makes a single correct answer impossible, the social conventions people navigate by, and the joint prediction problem where everyone is predicting everyone else.

8 steps·~12 min
AI
advanced

Architectures for Order Book Data, and Why They Help Less Than Expected

Convolutional and recurrent networks have been applied to order book data with published success, and the architectures encode real assumptions about the book's structure. This lesson explains what each one assumes, why the gains over simple baselines are smaller than headline numbers suggest, and where the modelling effort is better spent.

10 steps·~15 min
AI
intermediate

Evaluation, and Closing the Loop

An aggregate metric tells you a model is worse than you hoped and nothing about why. Evaluation that writes results back onto each sample turns a number into a set of images you can look at. This lesson covers the evaluation methods and their protocols, per-sample true and false positive counts, how a confusion matrix cell becomes a view, and where this workflow stops.

8 steps·~12 min