Skip to main content
Open In Colab This section was written by Ruimeng Yang (pull request #43), with help from an AI coding agent on the code. It reproduces the ideas of Chapter 41 of Foundations of Computer Vision by Antonio Torralba, Phillip Isola, and William T. Freeman. In this section you build a homography estimator from scratch in PyTorch, check it on synthetic point correspondences, see when it works and when it breaks, and finish by correcting the perspective of a synthetic image. By the end you should be able to:
  • explain what a planar homography does,
  • move between Euclidean and homogeneous coordinates,
  • estimate a homography with the normalized DLT algorithm,
  • measure reprojection error,
  • use RANSAC to reject outliers,
  • warp a planar image patch with inverse warping,
  • and recognize failure modes such as degenerate point sets and overwhelming outlier rates.

What a homography does

A homography is a 3×33 \times 3 matrix that maps points from one image plane to another. It describes the mapping exactly when the scene is planar, or when the camera only rotates about its optical center. This section stays deliberately narrow. It works on synthetic data so the geometry is easy to see, and it is not a panorama stitcher. The aim is to show how the math, the point correspondences, the robust estimation, and the final perspective correction fit together. You implement DLT, RANSAC, and inverse warping in PyTorch and use them to:
  • visualize how one plane is warped into another,
  • estimate a homography from noisy correspondences,
  • measure reprojection error,
  • reject outliers with RANSAC,
  • and rectify a synthetic checkerboard with inverse warping.
Throughout, the section moves back and forth between pictures and equations, so you can connect the matrix notation to something geometric.

Homogeneous coordinates and p~′∼Hp~\tilde{\mathbf{p}}' \sim H\tilde{\mathbf{p}}

A 2D point p=(x,y)\mathbf{p} = (x, y) becomes a homogeneous 3-vector by appending a 1: p~=[xy1].\tilde{\mathbf{p}} = \begin{bmatrix}x \\ y \\ 1\end{bmatrix}. A homography is a non-singular matrix H∈R3×3,p~′∼Hp~.H \in \mathbb{R}^{3 \times 3}, \qquad \tilde{\mathbf{p}}' \sim H\tilde{\mathbf{p}}. The symbol ∼\sim means equal up to scale. In homogeneous coordinates, multiplying a point by any nonzero scalar does not change the represented Euclidean point. After applying HH, you convert back to Euclidean coordinates by dividing by the last component: p~′=[uvw]⇒p′=(uw,vw).\tilde{\mathbf{p}}' = \begin{bmatrix}u \\ v \\ w\end{bmatrix} \quad \Rightarrow \quad \mathbf{p}' = \left(\frac{u}{w}, \frac{v}{w}\right). Because HH is defined only up to a scale factor, compare estimated and ground-truth homographies after normalizing them to a common scale. A counting argument helps here. A homography is written as a 3x3 matrix, which suggests 9 entries, but multiplying the whole matrix by any nonzero constant gives the same geometric mapping. That means one overall scale is arbitrary, so the homography has 8 degrees of freedom, not 9. Each point correspondence contributes two constraints, one for the destination x-coordinate and one for the destination y-coordinate. Therefore four non-collinear point pairs are the minimum needed for DLT, while using more than four correspondences gives an overdetermined least-squares system. To estimate HH from correspondences, you use the normalized Direct Linear Transform (DLT):
  1. normalize source and destination points for numerical stability,
  2. write the linear constraints implied by each correspondence,
  3. solve the resulting homogeneous system with SVD,
  4. denormalize the result back into the original coordinate system.
DLT also needs point configurations that constrain the full 2D projective warp. If all correspondences are collinear or nearly collinear, the system becomes poorly conditioned because the data do not sufficiently constrain the whole plane. The failure cases at the end of this section demonstrate that degeneracy. The implementation here does not filter degenerate samples, but production estimators often reject them before accepting a fit. The last coordinate ww lets a matrix represent perspective effects, and dividing by ww is the step that brings the transformed point back to ordinary 2D coordinates.
Output from cell 3

Synthetic data setup

You create a regular 2D grid of points, define a known homography, and use it to generate perfect correspondences. This gives a clean baseline before noise and outliers are added.

Visualizing the known transformation

The next figures show a regular source grid on one plane and the warped grid on the destination plane. The first is the conceptual plane-to-plane view; the second is the literal before-and-after view of the same coordinates. A homography bends the square boundary into a quadrilateral while still preserving straight lines. Every source point stays on the same underlying plane, but perspective changes spacing, orientation, and apparent parallelism. DLT and RANSAC try to recover exactly this planar warp from noisy point matches. The labeled corners A, B, C, and D form a non-collinear quadrilateral. This is the geometric reason four non-collinear correspondences are the minimum for DLT: they are the smallest set that constrains a full planar projective warp rather than only a line-like slice of it. Output from cell 7 Output from cell 7

Noisy correspondences and outliers

Real feature matches are never perfect. You perturb the destination points with Gaussian noise and then replace a fraction of them with random outliers. This tests both least-squares estimation and robust estimation under controlled conditions. Some destination points stay close to the clean warp, while the outliers jump far away. A few bad matches are enough to damage a plain least-squares fit. The hard part is not only estimating a homography, but deciding which correspondences deserve to influence the estimate.
Output from cell 9

Estimation: DLT versus RANSAC

You first estimate a homography from all correspondences with normalized DLT. Then you run RANSAC: repeatedly sample four points, score each candidate by reprojection error, and refit on the best inlier set. The outputs below show the DLT pipeline, a plot of observed against predicted destination points that illustrates reprojection error, and a numerical comparison of plain DLT and RANSAC. DLT answers the question “which matrix best explains these equations?” RANSAC adds the question “which correspondences should you trust before solving those equations?” The SVD step recovers a normalized homography HnormH_{\text{norm}}. You then map it back to the original coordinate system with H=Tdst−1HnormTsrc.H = T_{\mathrm{dst}}^{-1} H_{\mathrm{norm}} T_{\mathrm{src}}. This denormalization step is why point normalization improves numerical stability without changing the final geometric mapping. Output from cell 11
Output from cell 13

RANSAC inliers and outliers

The next plot colors the matched destination points by whether RANSAC classified them as inliers or outliers. The left panel is the synthetic ground-truth split and the right panel is RANSAC’s estimate, on the same axes. RANSAC does not try to explain every point. It looks for the largest self-consistent subset of matches and ignores the points that break that consistency. Once the inliers are identified, the homography is refit using only those correspondences. Output from cell 15 Output from cell 15

Validation against ground truth

A homography is only defined up to scale, so the estimated and true matrices are normalized before they are compared. Three kinds of metrics are reported:
  • Frobenius matrix error: how far the estimated homography is from the ground truth after scale normalization,
  • mean reprojection error: the average Euclidean mismatch between predicted and observed destination points,
  • RANSAC precision and recall: how accurately the robust estimator separated true inliers from outliers.
Lower matrix and reprojection errors are better; higher precision and recall are better. Reprojection error tells you whether the estimated geometry lands in the right place, while precision and recall tell you whether RANSAC trusted the right correspondences.

Perspective correction with inverse warping

A homography moves more than sparse points. Once you know the mapping between two views of the same plane, you can move every pixel on that plane. This makes homographies useful for rectification: undoing a perspective distortion so the plane looks fronto-parallel again. You create a synthetic checkerboard, warp it with a known homography, and rectify it with inverse warping. The figure compares the original, distorted, and rectified views. Dense warping needs interpolation, because inverse-mapped coordinates usually land between integer pixel locations.
Output from cell 18
Bilinear interpolation is needed because inverse-mapped source coordinates are almost never integers. A destination pixel often lands between four source pixels, so you blend those neighbors instead of rounding to the nearest one. This avoids staircase artifacts. The rectified board is fronto-parallel again, but interpolation slightly softens the edges. The example is idealized: the checkerboard is perfectly planar, the four corner correspondences are noise-free, and there is no lens distortion, occlusion, or lighting change. The rectification error is therefore mainly a resampling artifact from interpolating twice. Real photographs add many more complications.

Parameter study

Two practical questions matter:
  1. How does measurement noise affect reprojection error?
  2. How do outliers and the inlier threshold affect robust estimation?
The next experiment sweeps over both.
Output from cell 21
Increasing noise weakens each correspondence, so reprojection error rises even when every match is correct. Increasing the outlier ratio makes plain DLT fragile, while RANSAC stays stable only as long as it can still find a consistent model. The inlier threshold is a tradeoff: too small rejects noisy but valid points, too large admits outliers. The first two panels plot a geometric error; the last plots precision and recall, which are unitless rates. Keeping them on separate axes avoids a misleading comparison.

Failure cases: degeneracy and extreme outliers

Homography estimation needs well-conditioned correspondences. Two common problems are:
  • Nearly collinear points: the DLT system is poorly constrained because the points do not span the plane.
  • Too many outliers: RANSAC may never draw a minimal sample made only of inliers.
The left panel shows a narrow band of nearly collinear points; the right shows a field dominated by outliers with only a few inliers. A low error on a thin strip of points does not mean the homography is stable over the whole plane, and overwhelming outliers can defeat even a robust estimator. Good estimation needs both clean matches and good spatial coverage.
Output from cell 24

Summary

You implemented, in PyTorch and from scratch:
  • homogeneous coordinate conversion,
  • point normalization,
  • normalized DLT,
  • reprojection error,
  • RANSAC-based robust fitting,
  • and inverse image warping for perspective correction.
The experiments showed that:
  1. normalized DLT works well when correspondences are clean and well spread out,
  2. RANSAC is essential when mismatches are present,
  3. inverse warping turns an estimated homography into a dense rectification tool,
  4. degenerate point sets and extreme outlier rates can still defeat the estimator.
A natural extension is to replace the synthetic corners with real detections and study how interpolation, occlusion, and imperfect corner localization affect rectification.