Homography, RANSAC and panoramas

Four point pairs fix a homography; RANSAC finds four good ones among many bad; chaining homographies stitches a panorama.

What you'll learn
  • Solve for a homography from four correspondences with the SVD
  • Explain RANSAC and compute how many iterations it needs
  • Chain homographies to a reference image and find the panorama's canvas

When the camera only rotates — or the scene is flat — two photos are related by a homography: a 3 × 3 matrix acting on homogeneous pixel coordinates,

\[\begin{pmatrix} x' w \\ y' w \\ w \end{pmatrix} = H \begin{pmatrix} x \\ y \\ 1 \end{pmatrix},\]

followed by division by \(w\). That division is what lets parallel lines converge. \(H\) is defined only up to scale, so it has 8 degrees of freedom, and each point pair gives 2 equations: four pairs determine it.

The unit square mapped onto a moving quadrilateral. H is re-solved from the four corner pairs every frame; the grid lines stay straight but stop being parallel. Force the fourth corner onto a parallelogram and the bottom row of H becomes (0, 0, 1): an affine map.

computeHomography writes the two equations per pair as rows of an 8 × 9 matrix \(A\) with \(A\mathbf{h} = 0\), and takes \(\mathbf{h}\) as the right singular vector of the smallest singular value — the least-squares solution of the SVD lesson:

for i in range(4):
    x, y = points1[i]; u, v = points2[i]
    A[2*i]     = [-x, -y, -1,  0,  0,  0, x*u, y*u, u]
    A[2*i + 1] = [ 0,  0,  0, -x, -y, -1, x*v, y*v, v]
U, s, V_T = np.linalg.svd(A, full_matrices=True)
H = V_T[-1].reshape(3, 3)
H /= H[2, 2]

The repository’s testHomography passes: the error against the reference matrix is \(4.6 \times 10^{-11}\).

RANSAC

Matches contain outliers, and a single wrong pair ruins a least-squares fit. RANSAC (random sample consensus) repeats a cheap experiment: draw the minimum number of matches, fit a model, count how many matches agree within a threshold, keep the best.

RANSAC fitting a line (2-point samples) to 24 good points and 16 outliers. A sample containing an outlier gives a line few points agree with; the first all-inlier sample wins and is never beaten. The readout gives the iterations needed for 99% confidence.

If a fraction \(w\) of matches are inliers and a sample needs \(s\) of them, a sample is all-inlier with probability \(w^s\); to see at least one with probability \(p\) takes

\[N = \frac{\log(1 - p)}{\log(1 - w^s)}\]

iterations. The count explodes as \(w\) falls and \(s\) grows:

Iterations for 99% confidence, on a log scale. At w = 0.5 a homography needs 72 draws, a fundamental matrix (s = 8) 1,177; at w = 0.2 the fundamental matrix needs 1.8 million.

The code’s 1000 iterations are therefore generous for a homography. Two details in ransac.py: np.random.randint(0, len(points1) - 1) can never pick the last match (the upper bound is exclusive), and the four indices are drawn with replacement, so a sample can repeat a point and make \(A\) degenerate. np.random.choice(len(points1), 4, replace=False) fixes both. And the best four-point \(H\) is returned as is; refitting on all its inliers is standard, as the next test shows.

A test with a known answer

The repository’s panorama photos are not committed, so the pipeline was run on img.png and a copy warped by a known \(H\). The repo’s RANSAC found 108 inliers among 119 ratio-test matches; its \(H\) moves the image corners up to 12.9 px from where the true \(H\) sends them. Refitting with all 108 inliers (cv2.findHomography(p1, p2, 0)) halves that to 5.8 px, and across 20 random seeds the un-refitted error ranged from 3.9 to 30.9 px — the refit is worth its one line.

A panorama of the campus scene assembled from the left crop and the warped right view, with a black wedge at the lower right where no image covers the canvas.
The two views stitched with the recovered homography.

Stitching many images

Pipeline: detect ORB features (500 per image), match pairs with two nearest neighbours and ratio 0.7, fit a homography with RANSAC (1000 draws of 4 matches, 2 px), chain homographies to the centre image, bound the canvas by projecting every image's corners and shifting to (0,0), then warp and paste with the centre image first. Pipeline: detect ORB features (500 per image), match pairs with two nearest neighbours and ratio 0.7, fit a homography with RANSAC (1000 draws of 4 matches, 2 px), chain homographies to the centre image, bound the canvas by projecting every image's corners and shifting to (0,0), then warp and paste with the centre image first.
The stitching pipeline in 02_Panorama_Stitching, with the settings the code uses.

createStichedImage picks the middle image as the reference, chains each neighbour’s homography to it (computeHtoref), projects every image’s corners to find the canvas, shifts everything so the top-left corner is (0, 0), then warps and pastes from the centre outwards. The README notes the stitching “has some errors”; the main one is a spelling mismatch. __main__.py initialises each image with the key 'HtoRefrence', while the stitcher reads and writes 'HtoReference', so the first read of the centre image’s matrix raises KeyError: 'HtoReference'. With the key spelled consistently the chain works. The final paste loops over every pixel in Python; mask = stitched.sum(axis=2) == 0 and stitched[mask] = warped[mask] does the same in one vectorised step.

Try it yourself. Feed computeHomography four points of which three are collinear and print the singular values of \(A\) — what happens to the smallest two? Then, in computeHomographyRansac, refit on the inliers of the best model and compare corner errors as above.

View source on GitHub →