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
Titles jump to the section below; ↗ opens it in the book.
Robustness: the ratio test and RANSAC⧉
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⧉
optionalThe 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
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.
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⧉
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):
- 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.
- Fit $T$ from just that sample (reject repeated or collinear configurations before solving; numerical conditioning still matters).
- 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$.
- Repeat, keeping the $T$ with the largest inlier set.
- 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
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).


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⧉
optionalThe 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:
- MLESAC (Torr & Zisserman 2000) replaces the hard inlier count with a likelihood score. Instead of asking whether a point is in or out at threshold $\epsilon$, it models inliers and outliers as a mixture and scores a model by how probable the data is under it. This makes the choice between near-tied models less brittle than a binary count.
- PROSAC (Chum & Matas 2005) attacks the iteration budget directly: rather than sample uniformly, draw from the most confident matches first (ranked by descriptor-match quality). Good matches are more likely to be inliers, so a clean minimal sample is found in far fewer iterations, often an order of magnitude fewer, while degrading gracefully to plain RANSAC if the confident matches mislead.
- LO-RANSAC Chum, Matas & Kittler 2003 (LO-RANSAC) adds a local optimization: each time the best model improves, run a quick inner refit (least squares on the current inliers, possibly with a looser-then-tighter threshold) before continuing. This closes the gap between RANSAC's coarse minimal-sample estimate and the true optimum, with little extra cost.
- MAGSAC++ (Barath et al., 2020) reduces sensitivity to a single inlier threshold by marginalizing over noise scales and using the resulting weights in iterative fitting. It still needs a maximum noise scale; it does not remove every threshold or guarantee a fit when the model or matches are wrong.
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⧉
optionalThe 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
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
to $A$. If $T_1,T_2$ normalize source and destination coordinates, denormalize with $H=T_2^{-1}H_nT_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⧉
optionalWith $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.

Automatic panorama stitching from multiple views and feature matching⧉
The feature pipeline, recalled⧉
optionalThe 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):
- Detect distinctive points independently in each image: Harris corners, or SIFT keypoints when scale and rotation invariance are needed (Chapter 12.3, Sparse matching). Detection is run separately per image and must be repeatable: a point found in one view but missed in the other can never be matched.
- Describe each point's neighborhood with an invariant vector $\mathbf{f}$: a normalized patch, or the 128-D SIFT descriptor (Chapter 12.3, Sparse matching). The descriptor must be distinctive yet invariant: similar for the same scene point across the two views, different for unrelated points.
- Match by nearest descriptor, then prune the ambiguous matches with Lowe's ratio test $d_1/d_2<\rho$ (with $\rho\approx0.7$–$0.8$, the threshold called $\rho$ in Chapter 12.5, Robustness: the ratio test and RANSAC), which keeps a match only when its nearest descriptor is decisively closer than its second-nearest. This raises the inlier fraction $w$ that RANSAC will exploit next.
- Robustly fit the model, here the homography $H$, from the surviving, still-outlier-ridden matches with RANSAC (Chapter 12.5, Robustness: the ratio test and RANSAC). The remainder of this chapter is about what "for us" means: how RANSAC specializes to a homography.
After feature initialization, direct photometric refinement can use additional image information when exposure and visibility are modeled appropriately.


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⧉
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
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.
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
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.

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.
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⧉
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.
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⧉
Registration provides a common coordinate system, but residual geometry can remain. Photometric differences include:
- Exposure / auto-exposure drift. The camera re-meters between shots (or you nudged the shutter or ISO), so the same wall is brighter in one frame than the next.
- White-balance drift. Auto white balance shifts per frame, leaving a color cast that differs across the seam.
- Vignetting. Lens shading often darkens the corners, so the same scene point is darker when it lands near a frame edge than when it lands at the center, which can produce disagreeing brightness ramps across the overlap.
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⧉
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:
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.
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)⧉
A useful teaching approximation splits each image into two bands and blends them differently. It illustrates multiscale blending without requiring a full pyramid.
- The low band $L_i = G_\sigma * I_i$ (a Gaussian blur) carries exposure, white balance, and vignetting, the slow stuff we want to merge smoothly. Smooth-blend it with the feathering weights above. A wide transition spreads the low-frequency mismatch gradually, although a visible brightness band can remain.
- The high band $H_i = I_i - L_i$ (the residual detail) carries the sharp edges and texture. Here a smooth average is exactly what causes ghosting, so we do the opposite, winner-take-all: at each pixel keep the high-frequency detail from the single source with the highest weight,
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.

Multiband / Laplacian-pyramid blending: a transition per band⧉
optionalA 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$,
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:
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.
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.
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⧉
optionalEvery 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,
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.
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.
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.
The complete pipeline, end to end⧉
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.
The default scene in the stitcher below, and the panorama in the gallery, is Guédelon, a medieval castle in Treigny, Burgundy, France, that since 1997 has been built from nothing using only 13th-century methods and materials: stone quarried on site, oak hewn with period tools, lime mortar burnt in wood-fired kilns, a human-powered treadwheel crane. It is experimental archaeology run as a decades-long public project, and the walls rise a little each year. These photographs are the (human) author's own: Guédelon sits about ten miles from where Frédo grew up, which is why it shows up here as a test scene rather than a laboratory scene. The overlapping, slightly exposure-varied frames of its big round tower make it a good blending workout.

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⧉
optionalParallax: 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:
- Rotate about the no-parallax point. If the camera pivots about its entrance pupil viewpoint translation is reduced under a central-camera approximation and the homography is once again valid. This is precisely why tripod panoramas use a nodal slide to position the lens's pupil over the axis of rotation.
- Accept it locally. Route the seam through low-parallax regions (distant sky, uniform wall) using the graph cut once more, and blend, so that the unavoidable mismatch is hidden where the scene is far away or featureless enough that no one notices.
- Go 3-D. When translation is essential to the shot, abandon the single-homography model and estimate scene depth with genuine multi-view geometry (Hartley and Zisserman). This is the hand-off to structure-from-motion and to Matching pixels across space and time, where a per-pixel, depth-aware warp replaces the one global map.
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.
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
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.
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.