BookNotesSlidesP-sets Syllabusdraft · v0.2.64.1
◀▲⌂▶
💬Comments welcome. To leave a note, select any text and click the note / highlight button that pops up — or open the panel with the tab at the top-right (‹). Notes are visible only inside our private review group.
Course notes · 16 sections from the book · 8 optionalPDFessentials+ usefuleverythingthe full book ↗
💡 In a hurry? Jump to this chapter’s 2 big lessons ↓

Lecture Notes 13 — RANSAC, blending⧉

Course notes cut from Computational Photography, an AI-powered Slopendium for this lecture. Each section links back to its home in the book; sections marked optional go beyond what the lecture needs.

Contents · 13 sections on this page, from 5 chapters of the book

Robustness: the ratio test and RANSAC⧉

in the book↗

A candidate correspondence can select the wrong repeated window, miss an occlusion, or match unrelated texture. These outliers can dominate a least-squares geometric fit. Descriptor ambiguity tests and geometric consensus address different parts of the problem.

Two classic filters make matching usable, and they attack the problem from opposite ends. One prunes matches before any geometry is fit, by spotting which matches are ambiguous. The other fits a transform despite the outliers that survive pruning, by replacing the fragile least-squares average with a robust consensus vote. Neither alone is enough; together they turn a 50%-garbage match set into a clean geometric model.

The ratio test: reject ambiguous matches before fitting⧉

optional

The instinct, when you have a keypoint in image A and a set of candidates in image B, is to keep the match if the nearest descriptor is close. Lowe's ratio test (Lowe 2004 Lowe 2004) says that is the wrong question. Closeness in absolute terms is unreliable because a descriptor on a high-contrast corner is close to its true partner, a descriptor on flat texture is far from everything, and a single threshold on distance cannot serve both. The right question is about ambiguity: is the nearest match decisively better than the second-nearest one?

So for each keypoint, find its two nearest neighbors in descriptor space, at distances $d_1\le d_2$, and accept the match only if

$$ \frac{d_1}{d_2} < \rho, \qquad \rho \approx 0.7\text{–}0.8. $$

The logic is clean. A distinctive point (a unique corner of a window frame) has one obviously-best partner and everything else far away, so $d_1\ll d_2$ and the ratio is small: keep it. A point on repeated texture (one brick among a hundred) has a best match that is barely better than the next brick over, so $d_1\approx d_2$, the ratio is near $1$, and the match is thrown out (Figure 12.5.1). The test measures exactly the failure mode that breaks matching: it does not ask "is this match good?" but "is there a competitor that makes this match untrustworthy?" That is why it works where an absolute-distance threshold does not, because repeated structure produces near-ties, and near-ties are precisely what the ratio catches.

The ratio threshold is empirical and descriptor-dependent. Handle fewer than two candidates and zero second-neighbor distance explicitly. If a search returns squared distances, compare their ratio with the square of the distance-ratio threshold. Mutual nearest-neighbor checks impose another useful consistency condition but do not replace geometry.

fig-ratio-test
Figure 12.5.1 (reproduced). Ambiguity, not distance, is the test. Left: one query keypoint and its two nearest descriptors in the other image, with distances $d_1$ (nearest) and $d_2$ (second-nearest). A distinctive match has $d_1\ll d_2$, with one clear winner, and passes ($d_1/d_2<\rho$, kept). An ambiguous match (a point on repeated texture) has $d_1\approx d_2$, with two near-tied candidates, and fails (rejected). Right: histograms of the ratio $d_1/d_2$ for true versus false matches, which separate cleanly around $\rho\approx0.8$: true matches pile up at small ratios, false matches spread toward $1$. The threshold slices between the two populations.

Rejecting ambiguity costs some correct matches too. A real window corner may have a nearly identical neighbor on the same façade, so its descriptor does not identify a unique partner even when the best candidate happens to be right. Lowering the ratio threshold generally rejects more such cases. This is a precision/recall choice before geometric fitting, not proof that the remaining pairs are correct.

RANSAC: fit from a minimal random sample, score by consensus⧉

in the book↗

After the ratio test, outliers remain, so we must fit the transform in a way that tolerates them, without letting every bad match directly influence every fitted hypothesis. RANSAC, RANdom SAmple Consensus, from Fischler & Bolles (1981) Fischler & Bolles 1981, does this with an idea that is simple and exactly right. Rather than fit one model to all the data and hope, fit many models to tiny random subsets and let the data vote.

The loop, for fitting a transform $T$ (Figure 12.5.5 shows it on a homography):

  1. Draw a minimal random sample, the fewest matches that determine the model. Two points for a line, four point-pairs for a homography $H$, and so on. Minimal is deliberate: the smaller the sample, the higher the chance it lands entirely on inliers.
  2. Fit $T$ from just that sample (reject repeated or collinear configurations before solving; numerical conditioning still matters).
  3. Score by consensus. Count how many of all the other matches agree with this $T$, the inliers, using the test $\lVert \mathbf{x}'_i - T(\mathbf{x}_i)\rVert < \epsilon$: a match is an inlier if mapping $\mathbf{x}_i$ through $T$ lands within $\epsilon$ pixels of its claimed partner $\mathbf{x}'_i$.
  4. Repeat, keeping the $T$ with the largest inlier set.
  5. Refit that winning model by least squares on all its inliers. Recompute residuals and the inlier set after refinement; the consensus may still contain outliers or reflect the wrong motion model.

Here is why this beats least squares. A least-squares fit averages in every match, so a handful of gross outliers drag the answer off (Figure 12.5.3, the canonical picture: the least-squares line tilts toward the outliers, while RANSAC's best minimal-sample line threads the inlier majority). RANSAC instead ignores outliers rather than averaging them: a minimal sample that happens to be all-inlier defines a model the inlier majority votes for, and inconsistent outliers contribute little support to that hypothesis. Structured outliers can form a competing consensus. The method is robust even when most of the matches are wrong, which is exactly the regime keypoint matching lives in.

Suppose an independent trial yields an all-inlier, nondegenerate minimal sample with probability approximated by $w^s$. To make the probability of at least one such trial at least $p$, choose the ceiling of

$$ N = \left\lceil\frac{\log(1-p)}{\log\!\big(1-w^{s}\big)}\right\rceil. $$

Read the three dependencies off this formula, because they are the design knobs. The sample size $s$ sits in an exponent, so larger minimal samples raise the cost quickly; you want the minimal solver and not one match more (this is why "minimal sample" is load-bearing, not a stylistic choice). The inlier fraction $w$ sets the base of the exponential, so a cleaner match set converges much faster. And $N$ itself is the good exponential: more iterations drive failure down geometrically, and iterations are cheap (a four-point solve plus a residual count). A concrete case from the slides: with a homography ($s=4$) and a 50% inlier fraction ($w=0.5$), a single draw succeeds only 6% of the time, but $N=100$ iterations cuts the failure probability to about $1$ in $600$, and $N=1000$ to astronomically small. Even at a punishing $w=0.1$, raising $N$ buys success; you simply pay more iterations. RANSAC trades one fit to all samples for a search over hypotheses. The trial probability quantifies one part of that search under stated assumptions; it does not make the result immune to outliers or model error.

Turned around, the same expression is the probability that all $N$ trials fail, $(1-w^{s})^{N}$, and plotting it against $w$ for several $N$ shows the three knobs at once (Figure 12.5.2).

fig-ransac-failure
Figure 12.5.2 (reproduced). The probability that RANSAC never draws an all-inlier sample, $(1-w^{s})^{N}$, against the inlier fraction $w$ (interactive). Stage 1: one iteration count $N$; drag along the plot to move $w$, and the panel works out the numbers: the chance $w^{s}$ that one sample is all inliers, the chance that all $N$ samples fail, the same for $N=10$ to $10^{6}$, and the $N$ needed to succeed with probability $p$. Stage 2: the curves for $N=10, 100, \dots, 10^{6}$. Each tenfold increase in $N$ moves the curve to lower $w$ by a constant factor, $10^{-1/s}$, about 1.8 for a homography; a larger $s$ moves every curve the other way. At $w=0.5$ and $N=100$, a homography ($s=4$) fails with probability $1.6\times10^{-3}$ and a seven-point fundamental matrix ($s=7$) with probability $0.46$. The logarithmic axis shows the tails that the linear one flattens to zero.
fig-ransac-line-fit
Figure 12.5.3 (reproduced). RANSAC versus least squares on a line-fitting example. A set of 2-D points: an inlier majority lying along a line, plus a few gross outliers off to the side. Least squares (fit to all points) is dragged toward the outliers because the squared residuals of the far points dominate the sum and tilt the line. RANSAC draws minimal samples of two points; a sample landing on two inliers defines a line that the inlier majority votes for (the largest consensus set), and the outliers are simply ignored. The RANSAC line passes cleanly through the inlier majority while the least-squares line bends toward the outliers.
fig-ransac-demo
Figure 12.5.4 (reproduced). Interactive: step through RANSAC. A point cloud of inliers along a hidden line plus an adjustable fraction of outliers. Hit Step to draw one random minimal sample (two points), its candidate line, and the consensus band of inliers within the threshold; the best-so-far model (most votes) stays drawn boldly. A side plot shows the iteration count $N=\log(1-p)/\log(1-w^{s})$ blowing up as the inlier rate $w$ drops; drag the outlier fraction and watch it climb. That $N$ is how many independent draws give at least one all-inlier sample with probability $p$, assuming $w$ is known; a clean sample is necessary for a good line but does not guarantee that the best-voted line is the right one. Changing the threshold restarts the search on the same points. Run it to convergence and optionally least-squares-refit on the winning consensus set.
fig-ransac-homography
Figure 12.5.5 (reproduced). RANSAC on a real homography. Left: two views of a scene with raw nearest-neighbor matches drawn as lines, many of them crossing wildly, the signature of outliers (a corner in one image "matched" to an unrelated point in the other). Right: the RANSAC inlier set, the subset of matches consistent with a single homography $H$ (the four-point minimal solver, scored by reprojection within $\epsilon$). These lines are clean and roughly parallel, all obeying one consistent warp; the recovered $H$ is shown beside them. The same match set, before and after consensus filtering.
💡 Big lesson

Consensus is more robust than averaging. A least-squares fit is an average: it minimizes a sum of squared residuals, so it is perfectly behaved when every data point is a slightly-noisy inlier, and catastrophically fragile the instant one point is a gross outlier, because that one term dominates the sum. RANSAC's move is to stop averaging the raw data and instead let the data vote: fit from a minimal sample (small enough to occasionally be outlier-free), score by how many others agree, and keep the model with the most votes, and average only at the very end, after the outliers have been excluded. The pattern recurs far beyond matching: whenever your data is contaminated by points that don't merely add noise but actively lie, replace the global average with a consensus-of-a-clean-subset. Robustness is not a better fit to all the data; it is knowing which data to fit. Consensus has its own failure: when the data are degenerate, or when the outliers are themselves consistent (a repeated pattern, a second moving object), the largest agreeing set can support the wrong model.

The usual bound approximates sampling without replacement and assumes the estimated inlier rate is meaningful. Degenerate samples and structured outliers reduce effective success. Handle rates near zero or one explicitly, use a finite trial cap, and report failure when the support is inadequate. A homography’s inliers should cover the image region being warped, not occupy one small corner.

The sample-size exponent has a large practical effect. With an inlier fraction of one half and a four-match minimal sample, only about one draw in sixteen is all-inlier under the independent-draw approximation. Reaching a 99 percent chance of at least one all-inlier sample takes about 72 draws. With an inlier fraction of one fifth, the same calculation gives about 2,876 draws. A modest improvement in match quality can therefore save much more work than the inlier percentages suggest. These counts concern drawing an all-inlier sample, not guaranteed recovery: degenerate configurations, localization error, and a wrong geometric model can still defeat the fit.

Variants and degeneracy⧉

optional

The sample-and-score skeleton is so useful that a family of variants has grown around it, each improving one piece while keeping the loop intact:

All four keep the draw-a-sample, score-by-agreement, keep-the-best loop; they change how you sample, how you score, or how you refine, never the core idea.

There is one caveat that no amount of iteration fixes: RANSAC finds consensus, not truth. The algorithm trusts whatever model the most points agree on, but a degenerate configuration can make a wrong model win with overwhelming consensus. The textbook case lives in two-view geometry (Chapter 36.1, Multiple view geometry): if you are estimating the fundamental matrix $F$ to recover 3-D structure, but all the matched points happen to lie on a single plane (a building façade, a tabletop), then the data is consistent with infinitely many $F$'s, and RANSAC will confidently return one of them. It is geometrically valid by its inlier count, but useless for reconstruction. Consensus and correctness diverge exactly when the data is degenerate. The standard guards are a planar-versus-3-D check (test whether the inliers are explained by a homography alone, which flags the planar degeneracy) and choosing minimal solvers matched to the geometry you actually want. The lesson sits one level above the algorithm: a method that rewards agreement will be fooled by data that agrees for the wrong reason.

These three pieces, the ratio test, RANSAC, and a degeneracy guard, are what make sparse matching usable. The automatic-panorama chapter in the Multiple-Exposure-Imaging part, Chapter 20.2, Automatic panorama stitching from multiple views and feature matching, runs the full pipeline in anger: Harris corners Harris & Stephens 1988 → descriptors → ratio test → RANSAC homography → blend; and the same robust-fitting machinery underwrites every two-view estimator in Chapter 36.1, Multiple view geometry. Prune ambiguous matches, fit by consensus, and check for degeneracy.


Manual panorama stitching from multiple views⧉

Solving for $H$ from correspondences⧉

optional

The goal is concrete: given $\geq 4$ matched point pairs $\mathbf{x}_i \leftrightarrow \mathbf{x}_i'$, find the homography $H$ that maps each $\mathbf{x}_i$ to $\mathbf{x}_i'$. In manual stitching the user supplies these pairs by clicking matching landmarks across the overlap; automatically they come from feature matching (next chapter).

At first glance $\mathbf{x}'\simeq H\mathbf{x}$ looks nonlinear, because of the divide. The trick is to clear the denominator by cross-multiplying. Take $x' = (ax+by+c)/(gx+hy+i)$, multiply both sides by the denominator, and you get $ax+by+c-x'(gx+hy+i)=0$, a single equation that is now linear in the unknown entries of $H$. Each correspondence yields two such equations (one from $x'$, one from $y'$). Stack them into

$$ A\,\mathbf{h} = \mathbf{0}, $$

where $\mathbf{h}$ is the 9-vector of $H$'s entries and $A$ has two rows per correspondence. Four pairs give 8 equations.

The all-zero vector trivially solves the homogeneous equations and cannot represent a homography. Direct linear transformation (DLT) instead minimizes $\lVert A\mathbf h\rVert^2$ subject to $\lVert\mathbf h\rVert=1$, using a right singular vector. Before fitting, normalize coordinates in each image to zero centroid and mean distance $\sqrt2$, then undo the normalizations.

For a normalized correspondence $(x,y)\mapsto(u,v)$, add the two rows

$$\begin{bmatrix}-x&-y&-1&0&0&0&ux&uy&u\\0&0&0&-x&-y&-1&vx&vy&v\end{bmatrix}$$

to $A$. If $T_1,T_2$ normalize source and destination coordinates, denormalize with $H=T_2^{-1}H_nT_1$.

Algorithm 1
assert number_of_pairs >= 4
reject_repeated_or_nearly_collinear_configurations(pairs)
source, T1 = normalize_points(source_points)
target, T2 = normalize_points(target_points)
A = dlt_rows(source, target)
h = full_right_null_vector(A)  # retain the ninth vector for an 8-by-9 minimal system
H = inverse(T2) @ reshape3x3(h) @ T1
check_rank_and_projection_denominators(H)
H = refine_geometric_error(H, pairs)

Setting the bottom-right coefficient to one is safe only when that coefficient is not near zero. Its value depends on coordinates, not on a universal camera-angle threshold. Avoid normal equations when QR or SVD can solve the fit with better conditioning.

Four pairs determine a homography only in a nondegenerate configuration, with no three points collinear in either image. More well-distributed correspondences improve estimation, but a cluster in one corner can still extrapolate poorly. DLT minimizes algebraic error; refine using projected pixel residuals for a geometric fit.

Why four, and when fewer will do. The number four is not magic; it is just the eight degrees of freedom of a projective homography divided by the two equations each correspondence supplies. Assume less motion and you need fewer pairs, because every assumption you are willing to make removes degrees of freedom. A full projective map has 8 DOF → 4 pairs. Forbid perspective convergence (keep parallel lines parallel) and you drop to an affine map, 6 DOF → 3 pairs. Allow only translation, rotation, and a single scale (a similarity) and it is 4 DOF → 2 pairs. Adding translation to in-plane rotation and scale gives those 4 DOF; rigid translation-plus-rotation is 3 DOF → still 2 pairs (one is not quite enough); and pure translation is 2 DOF → one pair. The lesson recurs all through the book: a stronger model is cheaper to fit and more robust to noise, but only pays off when the assumption is actually true. Use the simplest transform the geometry allows, and no simpler. (For panoramas specifically, a known focal length turns the inter-image map into a 3-DOF rotation, fittable from as few as two correspondences. That is the basis of the rotation-only stitchers in the next chapter.)

Warping and assembling the panorama⧉

optional

With $H$ in hand for each frame, we build the wide image. Pick one image's coordinate frame as the canvas, the reference, and for every other image, warp it into that frame using its homography (warping each frame one by one toward the reference). The union of the warped frames is the panorama; output pixels that no source image reaches remain invalid or transparent.

Inverse warping evaluates each covered output location in its source image. It avoids forward-splat sampling gaps, but cannot fill areas outside all source footprints. Carry a validity mask instead of using black as missing data. A corner bounding box is valid only when no projective pole crosses the source rectangle; check denominator signs and impose finite canvas limits before allocation. Resample with antialiasing appropriate to local minification (Chapter 11.1, Warping).

Two loose ends, both pointers. First, the warped frames overlap and will not match exactly (exposure, vignetting, and tiny misalignments differ between shots), so they must be merged seamlessly; that is the job of the blending section (feathered, two-scale, or Poisson). Second, warping everything onto a single flat reference plane stretches badly at very wide fields of view; cylindrical or spherical projections (and the stereographic "little planet") are the fix, covered later under other projections.

fig-pano-manual
Figure 20.1.6 (reproduced). Manual stitching, end to end (interactive). Click the same feature four times in each of two photographs; the homography from those four correspondences reprojects the second image into the first one's frame, on a canvas of fixed size, twice the first image's width and height with the first image in its bottom-left corner, and a feathered blend merges them into one panorama. A canvas sized to fit the warped image would explode when the four points come close to a degenerate configuration. Upload your own overlapping pair. This is the whole manual pipeline, by hand.

Automatic panorama stitching from multiple views and feature matching⧉

The feature pipeline, recalled⧉

optional

The detect → describe → match → robustly-fit pipeline is built in full in Part 12, Matching pixels across space and time, and there is no profit in re-deriving it here. Chapter 12.3, Sparse matching, develops the detectors and descriptors: the structure tensor $M=\sum w\,\nabla I\,\nabla I^\top$ and its eigenvalue partition into flat / edge / corner, the Harris response $R=\det M-k(\operatorname{tr}M)^2$ and Shi–Tomasi, the scale axis that Harris lacks, and SIFT: Difference-of-Gaussians scale-space, the 26-neighbor space-and-scale extremum, a canonical orientation, and the $4\times4\times8=128$-dimensional descriptor, together with the broader detector/descriptor zoo. Chapter 12.5, Robustness: the ratio test and RANSAC, develops the clean-up: Lowe's ratio test and RANSAC. For panorama stitching we simply use that pipeline, so a one-paragraph recall is enough before we turn to the homography-specific orchestration that this chapter owns.

Here is the pipeline as it runs on a pair of overlapping frames, with each stage a pointer into that part (Figure 20.2.1):

After feature initialization, direct photometric refinement can use additional image information when exposure and visibility are modeled appropriately.

fig-pano-harris
Figure 20.2.2 (reproduced). Harris, component by component (interactive). The structure-tensor pipeline shown live on an image you can upload: luminance → gradient magnitude → the corner-response heatmap $R=\det M-k(\operatorname{tr}M)^2$ → the corners surviving threshold and non-maximum suppression, with the detector's $k$, scale $\sigma$, threshold, and corner-count knobs exposed.
fig-pano-2nn
Figure 20.2.3 (reproduced). Why the ratio test works (interactive). Two overlapping crops of one photograph, the second warped by a known rotation and scale, have their Harris corners matched by normalized-patch descriptors, and each match is checked against the known warp: green right, red wrong. Left: the matches spread by their best-match distance $d_1$; right: by the ratio $d_1/d_2$ to the second-nearest neighbor. A match is kept left of the dashed threshold, black rings mark the ones a threshold gets wrong, and each plot gives its accuracy and the best accuracy any threshold could reach; "best thresholds" moves both sliders to those cuts. On the facade, whose repeated windows make wrong matches as close as right ones, the best distance cut reaches about 72%, hardly better than rejecting every match (70%), and the ratio about 90%: a match to the wrong window has a second-nearest neighbor, the right window or another one, almost as close, so its ratio is near 1. Change the overlap, the warp or the photograph, or pool all six samples.

A synthetic warp provides exact correspondence truth but omits many real capture changes. Evaluate ratio and distance thresholds on repeated texture, exposure differences and non-overlap. The ratio test rejects ambiguity in descriptor space; it can also reject correct matches or retain a wrong distinctive one.

RANSAC for a homography⧉

in the book↗

We now have point correspondences, most of them good (inliers) but some still wrong (outliers), and we want the homography $H$. A plain least-squares fit over all matches is hopeless: least squares minimizes squared error, which gives large residuals disproportionate influence, so even a handful of gross outliers drags the fit arbitrarily far from the truth. We need a robust estimator, one that can find the right model while ignoring the bad data.

RANSAC, RANdom SAmple Consensus, due to Fischler and Bolles (1981), does this with a simple loop:

Project homogeneous coordinates before measuring pixel error. Define $\pi(a,b,c)=(a/c,b/c)$ and use

$$e_i=\lVert\mathbf x_i'-\pi(H\tilde{\mathbf x}_i)\rVert_2,$$

where $\tilde{\mathbf x}_i$ is the homogeneous source point and $\mathbf x_i'$ is the two-dimensional target. Reject unstable denominators. A symmetric transfer error can additionally measure the reverse direction.

Algorithm 2
best_inliers = []
for trial in range(iteration_budget):
    sample = random_distinct_matches(4)
    if degenerate(sample): continue
    H = normalized_DLT(sample)
    if invalid_model(H): continue
    errors = projected_pixel_errors(H, matches)
    inliers = indices_where(errors < tolerance_pixels)
    if better_consensus(inliers, errors, best_inliers):
        best_inliers = inliers
if len(best_inliers) < 4:
    return failure("insufficient consistent matches")
H = normalized_DLT(matches[best_inliers])
H = refine_geometric_error(H, matches[best_inliers])
return validate_and_rescore(H, matches)

Choose the tolerance in the coordinates actually scored; resizing changes pixel units. Check spatial coverage as well as the number of inliers. A large cluster on one repeated facade can support an incorrect or poorly extrapolated panorama.

RANSAC searches for a model supported by many correspondences. An all-inlier minimal sample can still be poorly conditioned, and repeated structure can support a coherent wrong model. Sampling, scoring, refitting and final validation are all needed.

Under independent trials with inlier fraction $w$ and minimal sample size $s$, a conventional budget is

$$N=\left\lceil\frac{\ln(1-p)}{\ln(1-w^s)}\right\rceil.$$

For $w=0.5$, $s=4$ and $p=0.99$, this gives 72 draws. It estimates the chance of at least one all-inlier sample, not the probability of a correct final panorama. Degeneracy, correlated matches and an inaccurate inlier estimate weaken that interpretation. Bound the budget and handle $w=0$ and $w=1$ explicitly (Chapter 12.5, Robustness: the ratio test and RANSAC).

The two-image pipeline now estimates a map from automatic matches. Multi-image systems also need a reliable overlap graph, globally consistent camera estimates and photometric compensation; Brown and Lowe combine these with blending (Brown & Lowe 2007). Disconnected groups should produce separate panoramas or a clear failure, not an arbitrary placement.

fig-ransac-line
Figure 20.2.4 (reproduced). RANSAC on a toy line fit, four panels. (1) A scatter of points: a clear linear trend plus scattered outliers. (2) A random minimal sample of two points and the line through them; count how many points fall within a band $\pm\varepsilon$ of it (the consensus set). (3) A bad draw (one sample point is an outlier) gives a tilted line with few inliers, and is discarded. (4) The best draw's line, with its large consensus set highlighted, followed by a least-squares re-fit on the inliers alone. The minimal-sample-then-consensus loop, in miniature.
fig-pano-ransac
Figure 20.2.5 (reproduced). RANSAC, step by step (interactive). On two real overlapping photos and their ratio-tested matches: Step draws a random four-match sample (gold), fits $H$, and recolours every match as inlier (green) or outlier (red) by its reprojection error, also drawing image 2's boundary reprojected into image 1; a best-so-far counter tracks the largest consensus set. Raise the ratio threshold to admit more (and worse) matches and watch RANSAC still lock onto the right model.
fig-stata-stitch-pipeline
Figure 20.2.6 (reproduced). The whole pipeline on a real pair (the MIT Stata Center, two overlapping views). Detect & describe: Harris corners fire at trackable two-dimensional structure, and each gets an orientation-normalized descriptor patch. Match & verify: nearest-descriptor matching gives many putative correspondences, a good fraction of them wrong; RANSAC keeps only the inliers consistent with a single homography. Warp & blend: the recovered homography warps one view onto the other and the overlap is blended, yielding a seamless panorama. Every stage of this chapter, end to end, on one scene.

Match reliable overlapping pairs and retain the original frames. Use the overlap graph to initialize camera poses, then refine globally (Chapter 20.4, Bells and whistles). Repeatedly resampling a growing mosaic can accumulate blur; render original sources into the final canvas once.

There is one stage we have black-boxed throughout as "warp and blend": the final compositing of the overlapping, exposure-mismatched frames into a seam-free image. It is substantial enough to own the next chapter, and it is the last thing standing between this pipeline and a finished panorama. So the complete end-to-end interactive stitcher, and a gallery of many-frame results, are deferred to the end of Chapter 20.3, Blending, once the blend step they depend on has actually been built, where you can run detect → describe → match → RANSAC → warp → blend in one place. See "the complete pipeline, end to end" there.


In CompPhotoRoom

The panorama merge of Chapter 8.13, A raw developer in the browser is this pipeline end to end, with the analysis view showing corners, accepted and rejected matches, and the bundle adjustment's before/after; the result installs as a re-editable photograph.

An incorrect match can have a very large residual under the correct homography, so including every match in ordinary least squares lets a few bad pairs pull the fit away from the true alignment. RANSAC temporarily fits a small subset and asks how many other pairs support that geometric explanation. The minimal subset itself is not the final estimate: after finding a useful consensus, refit using its inliers and check their residuals and spatial distribution. Four nearly collinear pairs, or many inliers clustered in a small corner, constrain the geometry less reliably than well-distributed correspondences.

The exponent $s$ explains why RANSAC draws a minimal sample first and uses more points only after finding consensus. At $w=1/2$, a four-point sample is all-inlier with probability $1/16$; an eight-point sample has probability $1/256$. Adding points to each random hypothesis can therefore make finding a clean one much more expensive. A matching filter helps when it raises the inlier fraction while retaining enough well-distributed correct pairs; discarding matches indiscriminately does not guarantee that improvement.

Blending⧉

in the book↗

Two registered views can still disagree in exposure, color or vignetting. Residual parallax and moving subjects may also remain. Inspect geometry before blending: a smooth transition can conceal a brightness step, but it cannot make two displaced copies of an object coincide.

Choose source regions and transition widths according to the remaining mismatch. Feathering, multiscale blending and gradient-domain reconstruction offer different controls; they are not an ordering from universally inferior to superior methods.

💡 Big lesson ((L10.4) · the eye cares about gradients, not absolute values)

A source change can introduce an edge that was absent from the scene. Blending reduces that discontinuity or moves the transition to a less conspicuous location. Smooth brightness and color errors can remain visible, so inspect the whole image as well as the seam.

Keep the original frames and editable source masks so the final choice of content and blend can be revised (L13.1).

Why a hard seam is visible: the photometric mismatch⧉

in the book↗

Registration provides a common coordinate system, but residual geometry can remain. Photometric differences include:

A hard source switch can turn a brightness mismatch into a visible step. A broad transition may be less conspicuous, but it can still appear as shading or a color band. Correct systematic exposure and lens falloff before asking the blend to hide them.

Use common linear-light values for a radiometric weighted average. The overlapping images are alternative measurements, not independent light sources being added. Appearance-oriented gradient or pyramid operations can use another declared domain, but their result then follows that rendering objective rather than a radiance average.

A hard source cut is a useful baseline and can work well where images agree. Blending is needed when the chosen boundary leaves a visible mismatch.

Feathering / alpha blending, and why it ghosts⧉

in the book↗

The first real idea, smooth blending, is to make each output pixel a weighted average of the sources, with each source's weight falling off toward its own frame boundary:

$$ I_{\text{out}}(p) = \frac{\sum_i w_i(p)\,I_i(p)}{\sum_i w_i(p)}. $$

A source counts fully in its interior and fades to zero at its edge, so the transition is gradual and the seam softens into a cross-fade rather than a step.

A source-space ramp is inexpensive and can be warped with the image, although it is not the exact distance to the warped boundary. Multiply weights by valid coverage, accumulate weighted color and total weight, and normalize only where that total is positive. Keep uncovered output transparent or explicitly invalid. When filtering near source borders, carry associated color and coverage together to avoid blending invalid black into the image.

Feathering averages residual misalignment as well as noise. A wider transition can spread doubled edges over a larger area. Narrowing it reduces mixed content but may expose a brightness step or cut through an object.

The diagnosis is what motivates everything that follows. Feathering uses one transition width for all frequencies. But the right width is frequency-dependent: the low frequencies, such as the exposure and vignetting ramp we actually want to merge, need a wide, smooth blend; the high frequencies, the sharp detail we want crisp and un-ghosted, need a narrow, almost-abrupt transition. One width cannot serve both. That single realization is the entire rest of the ladder.

[figure fig-blend-feather-ghost not built]
Figure 20.3.1 (reproduced). Feathering and its failure. The starting point is a two-image mosaic that is already geometrically registered yet still shows a hard, visible seam down the overlap, because the frames differ in exposure, white balance, and vignetting (a hard cut makes the mismatch a step edge the eye reads as a real boundary; geometry is solved, color is not). Top: distance-to-boundary weights $w_i$ (a separable ramp, $1$ in each frame's interior falling to $0$ at its edge) give a smooth weighted average $I_{\text{out}}=\sum_i w_i I_i / \sum_i w_i$, softening that seam. Bottom (the catch): where registration is slightly off (parallax, a moving branch), averaging misaligned high-frequency detail produces a doubled / ghosted edge and overall blur; widening the feather only worsens it. The lesson printed beside it: one transition width cannot serve both the slow exposure ramp (wants wide) and the sharp detail (wants narrow).

For three overlapping frames, keep one weighted-color accumulator and one weight accumulator. For each valid warped sample, add its color times its weight to the first and its weight to the second. Divide only after all frames have contributed. A location covered by three equally weighted samples then averages three samples, rather than averaging the third sample with an already averaged pair and giving it twice their individual influence.

A weight ramp can be constructed in each source rectangle and warped with the image. It provides a convenient fade toward the source borders, although after a projective warp it is not generally the Euclidean distance to the boundary in output pixels. Carry a separate validity mask so samples outside the captured image do not darken the accumulator.

Two-scale blending: the simple split (the pset method)⧉

in the book↗

A useful teaching approximation splits each image into two bands and blends them differently. It illustrates multiscale blending without requiring a full pyramid.

$$ H_{\text{out}}(p) = H_{\,\arg\max_i w_i(p)}(p). $$

Selecting one high-band value avoids averaging two values at that pixel. It does not guarantee a single intact object: the selected source can change across the object, and its low-frequency contribution can still be mixed.

Recombine by addition, $I_{\text{out}}=L_{\text{out}}+H_{\text{out}}$. This can reduce feathering blur, but inspect seams where the selected high-band source changes and low-frequency ghosts around moving objects.

This two-band teaching method is related to pyramid blending, but winner-take-all detail is not identical to a conventional two-level Gaussian-mask blend. More bands allow additional transition scales; they do not repair incorrect registration.

fig-blend-twoscale-split
Figure 20.3.2 (reproduced). Two-scale blending. Left: one source is split by a Gaussian into a low band $L_i = G_\sigma * I_i$ (exposure, white balance, vignetting, the slow stuff) and a high band $H_i = I_i - L_i$ (sharp detail). Right, two rules: the low band is smooth-blended with the feathering weights over a wide transition (merges the exposure ramp with no visible step); the high band is composited winner-take-all, $H_{\text{out}}(p)=H_{\arg\max_i w_i(p)}(p)$, an abrupt switch that keeps detail crisp and avoids ghosts. Recombine $I_{\text{out}}=L_{\text{out}}+H_{\text{out}}$. A side-by-side of hard cut vs. plain feather vs. two-scale shows two scales already capturing most of the gain.
fig-twoscale-blend-motivation
Figure 20.3.3 (reproduced). Why two-scale blending earns its keep, on a real exposure-mismatched pair, the leaning tower at the Guédelon site, with one frame deliberately brightened to exaggerate the exposure difference (the lecture's tower example). Smooth (feather) blend: a single wide alpha ramp over the overlap leaves a soft exposure band across the sky and ghosts the scaffolding into doubled edges where the registration is imperfect (the zoom makes the doubling plain). Two-scale blend: the low band is feathered over a wide transition (the exposure step disappears) while the high band is taken winner-take-all (the edges stay single and crisp): seam and ghost both gone. The weight schematic underneath contrasts the wide base ramp with the abrupt detail step.
fig-multiband-blend-demo
Figure 20.3.4 (reproduced). Interactive: blend two images across a seam, four ways. Drag the seam and switch between hard cut (a visible line), feather (a linear alpha ramp: narrow shows the seam, wide ghosts and bands), 2-scale, and the full Laplacian-pyramid (multiband) blend, which blends each frequency band over a width matched to its scale. Toggle the pyramid bands to watch the join hide band by band (fine bands cross sharply, coarse bands cross gently) so the seam and the ghosting both vanish. Try the aligned Earth/Jupiter pair, two faces, or the high-contrast ramp where feather banding is glaring.
fig-pano-blending-real
Figure 20.3.5 (reproduced). The three regimes on a real stitch (the Stata Center pair, where the two views differ in exposure). No blending: a hard copy-paste leaves a visible seam, a brightness step down the overlap boundary. Linear feather: a smooth alpha ramp removes the step but, applied to every frequency at once, can leave a soft band or ghost double-edges where alignment is imperfect. Two-scale: blend the low band wide and composite the high band winner-take-all and the seam vanishes while detail stays crisp.

Multiband / Laplacian-pyramid blending: a transition per band⧉

optional

A Laplacian pyramid provides a finite set of scales, not a continuum. Burt and Adelson blend corresponding band-pass levels using masks whose support grows with scale (Burt & Adelson 1983 (Laplacian pyramid); Burt & Adelson 1983 (spline blending)). Include the coarsest residual and use matching expansion operators during reconstruction (Chapter 6.6, Pyramids and wavelets).

The per-band blend is one line. At each level $k$ take a convex combination governed by a mask $m^k$,

$$ L^k_{\text{out}} = m^k\,L^k_A + (1-m^k)\,L^k_B, $$

and reconstruct by collapsing, $I_{\text{out}} = \sum_k \operatorname{expand}(L^k_{\text{out}})$. The whole method is build-two-pyramids, blend-each-band, collapse:

Algorithm 3
LA = laplacian_pyramid(A)
LB = laplacian_pyramid(B)
GM = gaussian_pyramid(mask)        # mask blurred more at coarse levels
for each level k:
    L_out[k] = GM[k] · LA[k] + (1 - GM[k]) · LB[k]
return collapse(L_out)

Build the masks with a Gaussian pyramid so they remain smooth blending weights rather than signed band-pass coefficients. Fine-band transitions are narrow in source-image units; coarse transitions are wider. With several sources and incomplete coverage, normalize valid weights at each level. Extend source data and masks consistently to prevent invalid borders contaminating the pyramid.

Box (L16 · prefilter before you downsample)

Building the Gaussian and Laplacian pyramids correctly requires blurring before you decimate at every level. Skip the prefilter and high frequencies alias into the coarse levels, and once aliased, they masquerade as genuine low frequencies. The blend then produces bold false low-frequency artifacts (moiré, color blotches) that no amount of clever masking can remove, because the masking operates band-by-band and the corruption is in the wrong band. The pyramid's quality is only ever as good as its prefilter. This is why the pyramid construction, not merely the blend formula, is load-bearing here. (Big lesson L16; first appears in BASIC (Resampling). See Chapter 6.6, Pyramids and wavelets.)

Replace the spatial mask $m$ with a per-pixel quality weight (well-exposedness, local contrast, saturation) and the identical machinery fuses an exposure bracket straight into a tone-mapped image. That is exposure fusion (Mertens et al. (exposure fusion)), which ships on phones: same pyramid blend, different mask, no high-dynamic-range (HDR) radiance map ever formed. We return to it in the HDR and cell-phone chapters.

fig-blend-mask-pyramid
Figure 20.3.6 (reproduced). Multiband blending and why the mask must use a Gaussian pyramid. The binary blend mask is built into a Gaussian pyramid $m^k = G^k(\text{mask})$: at the coarse levels it is heavily blurred (a wide transition), at the fine levels barely blurred (a sharp transition). Overlaid on the band-pass levels of the source, this shows the transition width tracking the band's scale, wide where we blend the slow exposure ramp, narrow where we keep crisp detail; a Laplacian pyramid of the mask would give the wrong widths and reintroduce ghosting. End to end, each source is decomposed into Laplacian-pyramid bands, each band blended with its own mask level, $L^k_{\text{out}} = m^k L^k_A + (1-m^k) L^k_B$, and the blended pyramid collapsed, $I_{\text{out}} = \sum_k \operatorname{expand}(L^k_{\text{out}})$, into one seamless mosaic. Compared with two-scale (Figure 20.3.2), every frequency now gets a transition matched to its scale, so even a strong exposure step or fine repeating texture across the seam blends invisibly.

The image and mask pyramids have different jobs. The image's Laplacian bands separate detail by scale. The mask's Gaussian levels remain smoothly varying selection weights; they are not signed detail coefficients. At a coarse image level, a transition spanning a few samples covers a wide region in the original image. At a fine level, the transition covers fewer original pixels. Thus a broad exposure mismatch can blend gradually while fine texture changes source over a narrower region. This improves the compromise available to one fixed feather width, but it cannot repair geometric misalignment or guarantee an invisible seam.

Seam optimization: route the seam instead of fading it⧉

optional

Every rung so far blends over a fixed seam, wherever the overlap happens to fall, and then works to disguise it. Seam optimization asks the prior question (Agarwala et al. 2004, Kwatra et al. 2003): where should the seam even be? Choose the boundary so it threads through pixels where the two images already agree, and there is barely anything left to blend. Route it along a uniform patch of sky rather than across a face, and the seam is half-hidden before any blending begins (Figure 20.3.8).

This is naturally posed as discrete optimization on a graph. Label each output pixel with the source it comes from, $\ell_p$, and minimize an energy with two terms,

$$ E = \sum_p D_p(\ell_p) + \sum_{(p,q)} V_{pq}(\ell_p, \ell_q), $$

a data term $D_p$ (a label must respect coverage: a pixel can only take a source that actually covers it) plus a smoothness term $V_{pq}$ that penalizes a label change between neighbors by how much the two sources disagree there. Minimizing $E$ over the two-source case is a min-cut / max-flow computation (a graph cut), which is globally optimal for a fixed binary submodular energy. Arbitrary two-label costs and general multi-label problems do not share that guarantee. The mechanics are the subject of Chapter 10.9, Seam optimization.

Box (L10.5 · image edits as discrete optimization on a graph)

The optimizer here is standard: graph cut / min-cut is a solved problem. The energy is the entire design. Set $V_{pq}$ to the color disagreement between the sources at this edge, and the min-cut automatically prefers to cut where the images match, along a uniform sky, not through a person's face. This is the affinity principle turned inside out: instead of "average things that belong together," it is "do not cut between things that belong together." The art is choosing what counts as disagreement, not running the solver. (Big lesson L10.5; first appears in Chapter 10.9, Seam optimization.)

How does this compose with the rest of the ladder? Seam optimization decides where to put the boundary; you then still run a Poisson or pyramid blend across that optimal seam to mop up whatever residual exposure mismatch survives. Graph-cut then gradient-domain reconstruction is the canonical photomontage recipe (Agarwala et al. 2004): cut along the edges, then reconstruct across them. It is the explicit meeting point of this part's blend ladder with the gradient-domain leg of EDGES MATTER.

Video 1. Video: Interactive Digital Photomontage (Agarwala, Dontcheva, Agrawala, Drucker, Colburn, Curless, Salesin and Cohen 2004) (YouTube).

Motion-aware seam costs or explicit region constraints can favor taking an object from one frame. Color disagreement alone does not guarantee that the whole object receives one label; missing background coverage can also prevent removing it.

fig-blend-seam-graphcut
Figure 20.3.8 (reproduced). Routing the seam, not fading it. Two overlapping registered frames; a person has walked between exposures. Rather than blend a fixed seam down the overlap, a graph cut labels each output pixel with its source $\ell_p$, minimizing $E=\sum_p D_p(\ell_p)+\sum_{(p,q)}V_{pq}(\ell_p,\ell_q)$ where $V_{pq}$ is the color disagreement between sources. The min-cut seam threads through low-disagreement pixels (along uniform sky and ground, around the person, not through them) so the walker is taken wholly from one frame (deghosting). A Poisson or pyramid blend then cleans up any residual exposure mismatch along the chosen seam.

The complete pipeline, end to end⧉

in the book↗

With blending built up (from the hard seam through feathering, two-scale, multiband, Poisson, and seam routing), the panorama pipeline is finally complete. We can now put the whole thing in one place: the geometry of Chapter 20.2, Automatic panorama stitching from multiple views and feature matching (detect → describe → match → RANSAC → warp) followed by the photometric step of this chapter (blend). The interactive stitcher below runs every stage live, and the gallery shows the same pipeline scaled to many hand-held frames, both deferred here from the matching chapter precisely because the final blend they depend on is only now in hand.

fig-pano-stitch
Figure 20.3.9 (reproduced). The whole pipeline, live (interactive). Drop up to six overlapping photos and the book's panorama pipeline runs end to end: Harris corners, naive patch features, brute-force matching of every pair, a reference chosen as the best-connected image, the ratio test, RANSAC per pair, a global bounding box that sizes (and bounds) the output, and reprojection with a choice of naive, linear-feather, or two-scale blending (and an optional cylindrical pre-warp). The panorama is on top; below, each input is a column (reference centered) you can switch between image, corners (click one to see its matches), and the pre-ratio / post-ratio / RANSAC-inlier match sets. The blending choices here are exactly the methods built up earlier in this chapter.

For a multi-image panorama, refine geometry and photometry over the overlap graph, then resample the original frames into the chosen output projection (Chapter 20.4, Bells and whistles). Blending operates on those sources and validity masks.


Bells and whistles optional⧉

optional

Parallax: when translation breaks the homography⧉

The deeper limit is geometric, and it is not a bug to be tuned away. Recall from Chapter 20.1, Manual panorama stitching from multiple views why a homography can align two frames in the first place: it is exact under a central-camera model for pure rotation about the projection center or points on a plane; a very distant scene can make translation effects negligible. Under pure rotation every scene point, near or far, moves between the two views by the same projective map, which is what let a single $3 \times 3$ homography $H \simeq K R K^{-1}$ stand in for the whole scene, with no dependence on depth.

The moment the camera translates (the photographer takes a step sideways), that guarantee collapses. Now near and far objects shift by different amounts: this is motion parallax, the everyday effect by which nearby fence posts streak past a train window while distant mountains barely move. And no single homography can align both: line up the background and the foreground doubles; line up the foreground and the background tears (Figure 20.4.9).

Translation makes correspondence depend on scene depth, so one projective transform generally cannot describe the whole overlap. A local displacement field can encode that variation where correspondence exists; a single global homography cannot.

Because the limit is structural, the practical escapes either avoid the translation or stop using a homography:

A handheld sweep may include viewpoint translation and rolling-shutter motion. Their magnitude depends on capture, and narrow strips can conceal some mismatches without making the underlying central-camera assumptions exact.

fig-deghost-seam
Figure 20.4.8 (reproduced). Deghosting as a seam choice over moving regions. A person walks through the overlap between two frames and so appears in two different places. Naive blend: cross-fading the overlap averages the two positions, leaving the person doubled and translucent, a ghost. Deghosted: the disagreement region (large per-pixel difference after alignment) is detected, and the graph-cut seam is routed around the moving blob so the person is taken whole from a single frame, then blended along that seam. Same machinery, flipped: keep every copy for a stroboscopic pano, or keep none to erase transient people.
fig-parallax-breaks-homography
Figure 20.4.9 (reproduced). Parallax: why a translated camera breaks the homography. The camera takes a step sideways between two shots, so a near object and a far object shift by different amounts (motion parallax). Align on the background: the distant wall registers perfectly, but the near object is doubled. Align on the foreground: the near object registers, but the background tears. No single 2-D homography can satisfy both at once, because translation through a 3-D scene produces a depth-dependent displacement an 8-degrees-of-freedom (DOF) global warp cannot represent. The cure is to pivot about the no-parallax point, route the seam through far regions, or go fully 3-D.

Source selection makes several different composites possible. In an overlap containing a walking person, assigning the whole person to one frame can avoid a translucent double exposure. Choosing separate complete appearances can intentionally make a sequence-of-motion composite. Removing the person altogether requires some source to show the background behind each removed region. A seam cost can favor cuts around the person, but if keeping an object whole is a requirement, that requirement must be encoded rather than assumed to follow from local smoothness. Blend after selecting content; blending alone cannot decide which event the panorama should depict.

Recap: big lessons in this lecture

💡 Big lesson

Consensus is more robust than averaging. A least-squares fit is an average: it minimizes a sum of squared residuals, so it is perfectly behaved when every data point is a slightly-noisy inlier, and catastrophically fragile the instant one point is a gross outlier, because that one term dominates the sum. RANSAC's move is to stop averaging the raw data and instead let the data vote: fit from a minimal sample (small enough to occasionally be outlier-free), score by how many others agree, and keep the model with the most votes, and average only at the very end, after the outliers have been excluded. The pattern recurs far beyond matching: whenever your data is contaminated by points that don't merely add noise but actively lie, replace the global average with a consensus-of-a-clean-subset. Robustness is not a better fit to all the data; it is knowing which data to fit. Consensus has its own failure: when the data are degenerate, or when the outliers are themselves consistent (a repeated pattern, a second moving object), the largest agreeing set can support the wrong model.

💡 Big lesson ((L10.4) · the eye cares about gradients, not absolute values)

A source change can introduce an edge that was absent from the scene. Blending reduces that discontinuity or moves the transition to a less conspicuous location. Smooth brightness and color errors can remain visible, so inspect the whole image as well as the seam.