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 · 18 sections from the book · 11 optionalPDFessentials+ usefuleverythingthe full book ↗

Lecture Notes 11 — Panoramas, homographies⧉

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 · 15 sections on this page, from 6 chapters of the book

Pinhole image formation and linear perspective⧉

Homogeneous coordinates⧉

in the book↗

The projection equation is doing something slightly awkward. Multiplying by $f$ is a clean linear operation (a matrix could do it), but the division by $Z$ is not linear, and it makes the projection annoying to compose with the other operations we care about: moving the camera, rotating it, translating the scene. We would like the whole pipeline to be matrix multiplications, because then we can chain and invert them with the linear algebra you already know.

The standard fix is homogeneous coordinates. Write a 2D image point not as $(x, y)$ but as a triple $(x, y, 1)$, and agree that any nonzero scaling of that triple denotes the same point: $(x, y, 1)$, $(2x, 2y, 2)$, and $(wx, wy, w)$ all stand for the same 2D point, recovered by dividing through by the last coordinate. The payoff is that the messy division by $Z$ becomes part of this "divide by the last coordinate" convention, so projection turns into an ordinary matrix multiply followed by the standard homogeneous normalization. As a bonus, translation, which is not a linear operation on ordinary $(x, y)$ coordinates, also becomes a matrix multiply in homogeneous coordinates, which is exactly why all of computer graphics and vision lives in them. We keep the machinery light here; the appendix has the details.

The rule that $(wx, wy, w)$ all mean the same point ("up to scale") is precisely what lets perspective's divide-by-depth hide inside a linear framework: the projection produces a homogeneous triple, and the final divide-through is the division by $Z$. For a finite point with nonzero last coordinate, this representation loses no additional information: divide to recover its ordinary coordinates. Points with zero last coordinate represent directions at infinity and cannot be normalized this way. Projection itself still discards scene depth.

Concretely, the perspective projection $x'=fX/Z,\; y'=fY/Z$ becomes a single matrix applied to the homogeneous 3D point $(X,Y,Z,1)$:

$$ \begin{pmatrix} \tilde x \\ \tilde y \\ w \end{pmatrix} \simeq \begin{pmatrix} f & 0 & 0 & 0 \\ 0 & f & 0 & 0 \\ 0 & 0 & 1 & 0 \end{pmatrix} \begin{pmatrix} X \\ Y \\ Z \\ 1 \end{pmatrix} = \begin{pmatrix} fX \\ fY \\ Z \end{pmatrix}. $$

The division by $Z$ is now implicit: the result is the homogeneous triple $(fX, fY, Z)$, and the up-to-scale convention recovers the actual image point by dividing through by the last coordinate $w=Z$, giving $(fX/Z,\; fY/Z)$. The awkward nonlinear divide has been swept entirely into the one convention that defines homogeneous coordinates.

A $3\times3$ transformation of ordinary 3D points (a rotation, a scaling, a shear) carries over to homogeneous 4-vectors by padding it out with a $1$ in the extra diagonal slot and zeros elsewhere. A rotation $R$ becomes

$$ \begin{pmatrix} R & \mathbf{0} \\ \mathbf{0}^\top & 1 \end{pmatrix}, $$

a $4\times4$ matrix that rotates the $(X,Y,Z)$ part and leaves the homogeneous weight untouched; any linear map on the coordinates fits this pattern.

Translation is the operation homogeneous coordinates buy us for free. On ordinary coordinates it is not linear (you cannot add a constant with a matrix multiply), yet here it becomes a matrix, with the shift $\mathbf{t}=(t_x,t_y,t_z)$ sitting in the last column:

$$ \begin{pmatrix} 1 & 0 & 0 & t_x \\ 0 & 1 & 0 & t_y \\ 0 & 0 & 1 & t_z \\ 0 & 0 & 0 & 1 \end{pmatrix} \begin{pmatrix} X \\ Y \\ Z \\ 1 \end{pmatrix} = \begin{pmatrix} X+t_x \\ Y+t_y \\ Z+t_z \\ 1 \end{pmatrix}. $$

A rigid camera pose (a rotation and a translation together) is therefore the single $4\times4$ matrix $\left(\begin{smallmatrix} R & \mathbf{t} \\ \mathbf{0}^\top & 1 \end{smallmatrix}\right)$, exactly the extrinsics we meet in the next section.

Surprisingly, this same "carry a value scaled by a weight, then divide it out at the end" trick is exactly how we correctly handle transparency in RGBα images: a pixel's color is stored premultiplied by its alpha, $(\alpha R, \alpha G, \alpha B, \alpha)$, and the true color is recovered by dividing through by $\alpha$, the homogeneous divide all over again. So homogeneous coordinates and premultiplied alpha use the same mathematical pattern, which is why filtering and compositing both insist on it (→ Compositing, segmentation and matting).

fig-point-line-duality
Figure 2.2.14 (reproduced). Point-line duality in homogeneous 2D. A line ax + by + c = 0 is the triple (a, b, c); a point is the triple (x, y, 1); both are defined only up to scale. A point lies on a line iff the dot product (a, b, c)·(x, y, 1) = 0, an equation symmetric in point and line. Hence two points cross-product to the line joining them, and two lines cross-product to their intersection, the same operation, with the roles swapped.

What perspective preserves, and what it destroys⧉

optional

Perspective projection, the divide-by-$Z$, is a destructive operation, and knowing exactly what it keeps and what it loses is the core intuition behind a great deal of the book.

What survives is short: straight lines stay straight (a 3D line not passing through the camera center projects to an image line; a line through that center collapses to a point), and incidence survives (if a point lay on a line, its image lies on the image of the line). That is essentially all. What is destroyed is more striking: angles and lengths are not preserved. Parallel lines in the world generally do not stay parallel: they converge to a vanishing point. A right angle can project to any angle; a circle can become an ellipse; equal-length fence posts shrink with distance. There is no way to read a true length or a true angle off a single photograph without more information, because the depth that would let you undo the divide-by-$Z$ has been thrown away.

The vanishing point deserves a moment, because it is the most visible signature of perspective. Take a 3D line and march along it toward infinity; its projected image approaches a single fixed point, the vanishing point for that direction. Every line with the same 3D direction (every member of a family of parallels) marches to the same vanishing point, because in the limit the projection forgets position and keeps only direction. Different directions give different vanishing points; sets of parallel lines lying in a common plane (the ground, say) give vanishing points that all fall on one line, the horizon for that plane (Figure 2.2.18). This is the geometry that painters codified as one-, two-, and three-point perspective, and it is what forced-perspective film tricks exploit, the hobbits-and-Gandalf shots in The Lord of the Rings: place a near object and a far object so they project to plausibly related sizes, and the camera cannot tell they are not the same distance away.

fig-perspective-vanishing-points
Figure 2.2.18 (reproduced). Perspective projection and vanishing points. A set of parallel 3D lines (same direction) converges in the image to a single vanishing point; a different direction gives a different vanishing point. All directions parallel to one ground plane yield vanishing points lying on a common line, the horizon for that plane. Vanishing points are the image signature of perspective's divide-by-Z, and the only invariants of the projection are lines and incidence.

Morphing⧉

View morphing: the geometrically-correct in-between of two views⧉

optional

There is a case where the flat 2-D morph above is silently wrong. Suppose $I_0$ and $I_1$ are not two arbitrary pictures but two photographs of the same 3-D scene from different viewpoints, such as a face rotating between two camera angles. A naive linear morph then bends straight lines and shrinks the object: the in-between is not a valid view of any rigid scene (Figure 11.3.8). The reason is fundamental. Linearly interpolating image positions is not the same as interpolating the underlying 3-D geometry. A straight edge in the world projects to a straight line in both photos, but the midpoint of its two image projections is generally not where that edge would project from an in-between camera; the linear average cuts a chord across the true projective path, so straight lines sag and the silhouette pinches inward.

The fix, due to Seitz and Dyer (1996) in View Morphing, restores physical validity with three steps:

  1. Prewarp both images by homographies that rectify them to a common plane, so the two image planes become parallel and corresponding epipolar lines are horizontal and aligned (the same rectification used in stereo).
  2. Linearly interpolate the now-rectified images, a plain morph. But in this rectified frame the linear interpolation is geometrically correct, because corresponding points are constrained to move along aligned scanlines, so averaging their positions tracks the true motion.
  3. Postwarp the interpolated result by an interpolated homography to the desired in-between view.

Under rectified equal-intrinsic cameras translated parallel to their image planes, a fixed visible 3-D point moves linearly in image coordinates along the baseline. This is the special geometry exploited by view morphing Seitz & Dyer 1996. It does not imply that every camera motion admits a plain linear image blend. Correspondences, visibility and the pre/postwarps still determine whether the interpolated view is valid.

Video 1. Video: View Morphing, interpolating between two photographs along a physically valid path, so the in-between frames look like real camera motion rather than a flat cross-dissolve. Seitz & Dyer 1996 (Seitz & Dyer 1996), reproduced with permission.

The connection outward is direct. View morphing needs corresponding points between the two views and the epipolar geometry relating them: exactly the correspondence problem of Chapter 12.8, Optical flow and stereo. Supply that correspondence densely and automatically and you can synthesize in-between views with no hand-drawn lines at all: the bridge from morphing to image-based rendering, and to flow-driven frame interpolation (Chapter 30.4, Frame interpolation and slow-motion synthesis), where the two "views" are simply adjacent video frames.

fig-view-morph-prewarp
Figure 11.3.8 (reproduced). Why two views need view morphing. Top, naive 2-D morph: linearly interpolating image positions between two views of a rotating object bends straight edges and shrinks the object; the in-between is not a valid view of any rigid scene, because averaging image points is not averaging 3-D geometry. Bottom, view morphing (Seitz & Dyer): prewarp (rectify both images to a common plane so epipolar lines are horizontal and aligned) → linearly interpolate (now correct, since corresponding points move along aligned scanlines) → postwarp to the target in-between view. Straight lines stay straight and the object keeps its shape, a true perspective in-between.

Perspective distortion and its correction⧉

optional

You photograph a cathedral. Standing at its foot, you tilt the camera up to fit the spire in the frame, and the result has a defect you did not put there and cannot quite name: the two towers, which you know to be plumb and parallel, lean toward each other as they rise, as though the building were tapering to a point somewhere above the clouds. This is keystoning, or converging verticals, and architectural photographers find it objectionable enough that an entire class of equipment, and an entire panel of software tools, exists to undo it.

The first instinct is to blame the lens. It is the wrong instinct, and correcting it is the whole point of this chapter. Keystoning is not an optical defect; it is perspective projection doing exactly its job. The same geometry that makes railroad tracks meet at the horizon makes a bundle of parallel verticals converge when you tilt the sensor off the wall. Once you see it that way, the cure writes itself. Because the leaning-tower image is a perspective image of a real, flat, rectangular façade, a single projective warp, a homography, the top rung of the degrees-of-freedom ladder from Chapter 11.1, Warping, can re-render that façade as if the camera had been aimed straight at it, sensor parallel to the wall, verticals plumb. This chapter is that one move: why the distortion is projection and not optics, how to recover the homography (by hand from four corners, or automatically from vanishing points), the optical way to dodge it at capture (the tilt-shift lens), and the price you pay for fixing it in software (you resample, and only a plane comes out exactly right).

Keystoning is projection, not a lens flaw⧉

optional

Start with the symptom and pin down exactly when it appears. Aim the camera up at a tall building and its parallel verticals converge toward the top; aim it down and they splay apart toward the bottom. A wide-angle lens makes the same projective effect read as an exaggerated near/far stretch: the close end of a façade looms huge, the far end shrinks away. None of this is the glass misbehaving.

The cause is the single fact about perspective projection to keep in mind: projection preserves straight lines, but not parallelism, angles, or lengths. A straight line in the world images as a straight line. That survives. But a bundle of lines that are parallel in the world need not stay parallel in the image; instead they image as a bundle of lines converging to a single point, the vanishing point (the image of the point at infinity where the world parallels "meet"). The towers stay perfectly straight in your photograph; they simply stop being parallel. That is projection, not aberration (Figure 11.6.1).

Contrast this with the one perspective-like artifact that is an optical defect: radial lens distortion, barrel and pincushion, which bends straight lines into curves and comes from the lens. Keystoning bends nothing. If you lay a ruler along a keystoned tower the edge is dead straight; the lines have only lost their parallelism. The two corrections are different operations on different causes: radial distortion is undone by a nonlinear radial warp (a lens-distortion model), keystoning by the linear projective warp of this chapter, a contrast developed in detail in Part 22, Compound lenses, and aberration correction (Aberrations correction: radial distortion correction), where that lens defect and its cure now live.

The giveaway that fixes the cause precisely: if the image plane is parallel to the subject plane, sensor parallel to the façade, then world lines that are parallel to the sensor stay parallel in the image, and there is no convergence at all. Convergence appears exactly when you tilt the sensor off the wall. So keystoning is a function of nothing but camera orientation relative to the plane you care about, and a quantity that depends only on orientation is precisely the kind of thing a homography can undo.

fig-keystoning-cause
Figure 11.6.1 (reproduced). Keystoning is the tilt, not the lens. Left: the camera tilted up at a building; the world-parallel verticals image as lines converging to a vanishing point above the frame; the façade's true rectangle has become a trapezoid. Right: the same façade shot fronto-parallel (sensor parallel to the wall); the verticals stay parallel and the rectangle stays a rectangle. The distortion tracks the camera's orientation, not its optics: projection preserves straight lines but not parallelism.

The fix is a homography: re-render the façade fronto-parallel⧉

optional

Your keystoned photograph is a perspective image of a genuine planar rectangle, the façade. And a basic fact of projective geometry is that a homography maps between any two images of a plane. So there exists a single $3\times3$ projective warp $H$ that takes your tilted-sensor image of the façade to the image you would have captured with the sensor parallel to the wall: sending the converging lines back to parallel, the trapezoid back to a rectangle. This is precisely the projective rung of the degrees-of-freedom ladder from Chapter 11.1, Warping, used here with the target being a fronto-parallel rectangle of your choosing (Figure 11.6.2).

A plane supplies a depth relation that converts perspective projection between cameras into one projective map. Pure rotation about the camera center is a separate homography case that does not require the scene to be planar. Neither statement makes general camera translation depth-independent.

There are two ways to recover $H$.

Method 1: four corner correspondences. Pick four points in the photograph that you know bound a real rectangle (the four corners of a window, or of the façade outline) and specify where each should land: the four corners of a true rectangle, verticals vertical, horizontals horizontal. A homography has 8 degrees of freedom (DOF) (a $3\times3$ matrix up to overall scale), and each point correspondence contributes two linear equations, so four correspondences exactly determine $H$; more than four overdetermine it and you solve by least squares / singular value decomposition (SVD). This is the manual perspective crop: drag four handles to the corners, declare the output a rectangle, done (Figure 11.6.2).

Vanishing points from parallel line families identify the plane’s vanishing line and can support affine rectification. Parallelizing two families does not by itself recover their true angle or the façade’s aspect ratio. Metric rectification needs additional information, such as orthogonality constraints, known dimensions or calibration Liebowitz & Zisserman 1998.

Either way, once $H$ is known you apply it by the primitive from Chapter 11.1, Warping: inverse-warp and resample. Loop over the output pixels, push each one back through $H^{-1}$ to find where it came from in the input, and resample the input there,

$$ \text{out}(\mathbf{x}) = \text{in}\!\big(H^{-1}\mathbf{x}\big), $$

with the same forward-versus-inverse reasoning (loop over output, never over input, so every output pixel is filled exactly once) and the same reconstruction-filter care as every other warp in the part. Nothing about rectification is special in the applying; the only work is the solving of $H$.

In practice this is Lightroom's Transform / "Upright" panel (with auto and guided modes, where guided mode lets you draw the lines that should be vertical or horizontal), Photoshop's perspective crop, and the dedicated tools in architecture software. The user experience is "drag the building straight"; the engine underneath is the four-point or vanishing-point homography.

fig-rectify-before-after
Figure 11.6.2 (reproduced). Rectifying by homography. Left: the keystoned input, verticals converging; four corner handles dragged onto the corners of a known-rectangular feature (the façade outline), and the recovered vertical vanishing point marked above the frame. Right: the output after applying $H$, the façade re-rendered fronto-parallel, verticals plumb, the feature now a true rectangle. The four correspondences (input corners $\to$ rectangle corners) give $8$ equations and fix the $8$-DOF homography; it is then applied by inverse warp, $\text{out}(\mathbf{x})=\text{in}(H^{-1}\mathbf{x})$.
fig-pano-rectify
Figure 11.6.3 (reproduced). Rectification you can try (interactive). Drag the four handles onto something you know is a rectangle (a façade, a document, a sign) and a single homography re-renders it: full rectify sends the quad to a true rectangle (document flattening), while verticals only straightens just the converging verticals (architectural keystone correction) and leaves the horizontal perspective. Upload your own photo to feel the "only the chosen plane rectifies exactly" limit first-hand.

For the vanishing-point route, detect several lines believed to be parallel in the scene and estimate their common vanishing point. Sending the vertical family's vanishing point to infinity makes its lines parallel in the output; the output orientation then makes them vertical. A second independent family constrains the plane's vanishing line. This explains what automatic straightening is estimating, and why an incorrect line family or an unknown aspect ratio can still produce the wrong rectification.

Artists have run the same homography in reverse for five centuries. An anamorphosis is a picture painted on a plane so that it looks right from one viewpoint only, the skull stretched across the floor of Holbein's The Ambassadors (1533) or Julian Beever's pavement drawings that stand up out of the street. The painter starts from the picture as it should look, upright and facing the viewer, and sends it to the floor through the homography between the two planes, seen from the intended eye (Figure 11.6.4).

fig-anamorphosis
Figure 11.6.4 (reproduced). Anamorphosis, a homography painted on the floor (interactive). Left: the floor seen by a camera; drag to orbit. From most viewpoints the painting is a long smear; "view from the eye" puts the camera at the intended viewpoint, the red dot on its pole, and the picture stands up. Stage 2 adds the floor seen from above: the painting as it is actually painted, here 5 m long for a 1 m picture. Stage 3 lets us move the eye, at distance $D$ in front of the picture's base and height $h$, and gives the homography from a floor point $(x,y)$ to the upright picture $(X,Z)$: $X=Dx/(y+D)$, $Z=hy/(y+D)$. The ray through the picture's top edge comes down to the floor only if $h$ exceeds the picture's height, and the lower the eye, the longer the painting. The globe is drawn after Beever's; the photographs are from the book's sample library.

The optical alternative at capture: tilt-shift / Scheimpflug⧉

optional

The homography fixes perspective in post. There is an older way to fix it at capture, in the lens, so that the verticals never converge in the first place: the view camera and its modern descendant the tilt-shift lens.

The trick is geometric. A normal lens projects an image circle just big enough to cover the sensor, centered on the sensor. A view-camera (or tilt-shift) lens projects an image circle larger than the sensor, and lets you shift the lens (or the back) sideways or up to select an off-center part of that larger circle, all while keeping the sensor parallel to the façade. Because the sensor stays parallel to the subject plane, the world verticals stay parallel in the image: no convergence, no post-warp, no resampling penalty (Figure 11.6.5). You compose the tall building by shifting the lens up rather than by tilting the camera up.

A useful way to see the shift: it is geometrically the same as taking a wider, centered shot and cropping to the off-axis region you wanted, which is exactly why a software "perspective crop" can approximate a shift lens (at the cost of resolution, since you are throwing away the rest of the frame). The shifted-sensor image and the would-be-tilted image of the same façade differ by, unsurprisingly, a homography, which is the precise sense in which the optical fix and the software fix are two routes to the same place.

The view camera's other movement, tilt, does something different: it controls the plane of focus rather than perspective, via the Scheimpflug condition (the lens plane, sensor plane, and subject plane all meet along a single line). Tilt is how you get a steeply receding plane (a tabletop, a landscape) entirely in focus at a wide aperture; reversed, it is the trick behind the "miniature/tilt-shift" toy-town look. We only note tilt-shift here as the at-capture counterpart of the rectifying homography; the optical derivation belongs to Part 22, Compound lenses, and aberration correction (Scheimpflug, image circle, the view-camera movements), cross-referenced and not repeated.

The trade-off is the familiar capture-versus-post one. The optical correction preserves resolution and avoids resampling artifacts entirely, but it demands special, expensive, manual gear and must be decided at capture. You cannot recover uncaptured detail or change the original focus plane merely by rectifying geometry. The software homography is free and deferrable (decide later, in front of the computer), but it resamples, which is the catch of the next section.

fig-tilt-shift-scheimpflug
Figure 11.6.5 (reproduced). Fixing perspective in the lens. The view-camera / tilt-shift lens projects an image circle larger than the sensor. Shift moves the sensor (or lens) to an off-center part of that circle while keeping the sensor parallel to the façade, so the verticals never converge, the optical alternative to a post-capture homography (and geometrically equivalent to shooting wider and cropping off-axis). Tilt instead rotates the lens so the lens, sensor, and subject planes meet in a line (the Scheimpflug condition), placing a slanted plane entirely in focus. Cross-ref Part 22, Compound lenses, and aberration correction.
fig-tilt-shift-lens-photo
Figure 11.6.6 (reproduced). A real tilt-shift lens, the at-capture optical fix for the converging verticals discussed here. The knobs and geared rings let the photographer shift and tilt the lens relative to the sensor, realizing the shift and Scheimpflug movements the schematic above diagrams. (Author's photograph.)

Cropping wide-angle photographs: recenter with a homography, don't just crop⧉

optional

There is a workflow many photographers (this author included) have quietly adopted: shoot wide and crop later. Modern autofocus and high-resolution sensors make it painless: extend your arm over a group, aim roughly, and trust the wide-angle lens to catch everyone, then crop to the good part afterward. It is a useful way to shoot when there is no time to compose.

But it hides a subtle problem. If the interesting part sits off to one side of the wide frame and you crop it, that crop still carries wide-angle perspective distortion, with widened faces and splayed verticals, even though it now looks like a zoomed-in telephoto shot. The zoom is real (you kept fewer pixels), but the distortion is gratuitous: it is there only because the cropped region was off the optical axis, where rectilinear projection stretches hardest. The cropped region carries the wide lens's distortion, which it would not have had if you had simply aimed the camera at it.

To simulate rotating the viewing direction about the same center, use $H=K_{\rm new}RK^{-1}$ after accounting for lens distortion. Define $R$ as mapping old camera rays into the new camera frame. This applies across scene depths, but only to rays present in the input. A crop instead keeps the old image-plane orientation. Reprojection changes off-axis rendering; it cannot provide the detail of a longer-lens capture or the perspective of a camera moved farther away.

The move is everywhere a fixed wide lens must impersonate a moving telephoto one: video-surveillance virtual pan/tilt/zoom (one wide camera serving many "virtual" zoomed feeds), and action cameras, whose ultrawide footage is routinely reframed in software after the fact. Use the demo below to compare the two results. Aim at an off-center part of a real wide-angle shot, dial in a zoom, and compare the homography view against a plain crop of the same region: the plain crop keeps the wide-angle skew, the homography removes it (Figure 11.6.7). This local-projection view of wide-angle correction is the seed of the content-preserving projections in the next section Carroll, Agrawala & Agarwala 2009.

fig-wide-angle-crop
Figure 11.6.7 (reproduced). Cropping a wide-angle photo, two ways. Pick an off-center region and a zoom (target focal length): the plain crop keeps the wide-angle stretch because the region is off-axis, while the virtual rotation + zoom re-renders that region as if the camera had physically turned and zoomed toward it: each output pixel is looked up in the original through the homography $K_{\text{in}}R\,K_{\text{out}}^{-1}$, built from the known field of view, with $R$ carrying the virtual camera's viewing directions back into the original camera's frame. That removes the off-axis perspective stretch. Both views keep straight lines straight, and neither corrects the lens's own distortion. Enter the 35 mm-equivalent focal length (or let EXIF supply it), then drag to aim and slide to zoom. (Author's wide-angle captures.)

Cropping selects pixels from the existing projection; it does not change the projection center or viewing direction. A virtual camera rotation changes the coordinate system in which the captured rays are projected. With known intrinsics, reproject those rays into a new image centered on the region of interest, then choose the new focal length and crop. This can reduce the off-axis stretching left by a simple crop. It cannot supply rays outside the capture or recover detail lost to resampling, and straightening one set of lines does not guarantee every three-dimensional surface has become fronto-parallel.

Manual panorama stitching from multiple views⧉

in the book↗
📎 Problem set

PS6 solves a homography from four point pairs and stitches a planar mosaic. → Chapter 1.5, Problem sets (appendix).

Overlapping photographs can cover a scene wider than one frame. Stitching requires a map between their common content. For an ideal pinhole camera rotating about a fixed projection center, or for points on one plane, that map is a homography. Start by clicking correspondences; Chapter 20.2, Automatic panorama stitching from multiple views and feature matching replaces those clicks with feature matches.

The scenario, and the one rule: rotate, don't translate⧉

optional

Here is the setup. You stand in one place and pan the camera across a scene, taking overlapping frames. Choose one frame as the reference; reproject, or warp, the others into its coordinate system; blend the overlaps. The output is a virtual wide-angle view assembled from shots no single exposure could have captured (Figure 20.1.1).

For a general scene, keep the camera's effective projection center approximately fixed as it turns. The ideal rotation model then relates visible scene points independently of depth. In practice, lens distortion, rolling shutter and viewpoint shifts can violate it. A panorama head adjusted around the no-parallax position reduces viewpoint shifts.

Translation creates depth-dependent parallax: a nearby railing shifts relative to a distant building. One homography generally cannot align both. Local warps or depth-aware reconstruction can address some of the discrepancy; translation does not make every possible two-dimensional correspondence map impossible. A planar scene remains an important homography case.

One pointer, in keeping with our standing division of labor. The warping itself (forward vs. inverse warp, resampling, antialiasing) and the closely related perspective-distortion correction are developed in Matching pixels across space and time. Here we need only the geometry (which $H$ relates the views) and how to solve for it.

fig-pano-4clicks
Figure 20.1.1 (reproduced). The manual stitching pipeline end to end, on two real overlapping frames of MIT's Stata Center (Frank Gehry). Top: the user clicks four pairs of corresponding points across the overlap (the colored lines link matching landmarks on the building). From those four correspondences, solve for the homography $H$ ($3\times3$, 8 DOF); bottom: warp the second frame into the first's coordinate frame and feather-blend the overlap into a single wide image (the dashed box marks frame 1's footprint). The four clicks are the only manual step: everything downstream is mechanical.
fig-pano-rotate-vs-translate
Figure 20.1.2 (reproduced). Rotate, don't walk. Top: one fixed optical center, the camera fanning across the scene, so the views overlap and are related everywhere by a single homography, whatever the depths. Bottom: a camera that translates between shots, so near and far objects shift by different amounts (parallax) and no single 2D map aligns the views; the foreground slides relative to the background. Panorama stitching requires the top case.

Refresher: pinhole projection is "divide by depth"⧉

in the book↗

Everything below is a consequence of one fact about the pinhole camera, so let us refresh it. A 3D point $(x,y,z)$ in the camera's frame images to the point $(x/z,\,y/z)$ on the plane $z=1$. Projection is division by depth. This is why far things look small: a larger $z$ shrinks $(x/z,y/z)$ toward the center. The whole nonlinearity of perspective lives in that single divide.

Define $R$ to transform a ray expressed in camera 1 coordinates into camera 2 coordinates. If the camera-to-world orientations are $Q_1,Q_2$, then $R=Q_2^{\mathsf T}Q_1$. This convention avoids confusing a physical camera rotation with the inverse coordinate transform.

We know the ray from each source pixel, but not the depth of the scene point along it. Under pure rotation, all positive depths along that ray share the same destination direction.

Why you don't need 3D: depth cancels for a pure rotation⧉

in the book↗

The idea is best stated as an observation about a single viewing ray: all points along one viewing ray reproject to the same place. A pixel $(x,y)$ in image 1 is the image of an entire ray of 3D points $(tx,\,ty,\,t)$, one for every depth $t$, all sharing the same direction. Rotate that whole ray by $R$ and re-project. The rotation scales linearly, so the rotated ray is $R\,(tx,ty,t)^\top = t\,R\,(x,y,1)^\top$: the depth $t$ is a common factor of all three coordinates. But projection divides by the third coordinate, and dividing kills that common factor. Every point on the ray, at every depth, lands on the exact same pixel in the rotated view. The destination pixel does not depend on depth at all (Figure 20.1.3).

We may therefore represent the source ray at any convenient nonzero scale. Rotating it and dividing by its third coordinate gives the same destination pixel regardless of the chosen depth.

Chaining the three steps, un-project (apply $K^{-1}$ to go from pixels to rays), rotate (apply $R$), re-project (apply $K$ to go from rays back to pixels), gives the view-to-view map

$$ \mathbf{x}' \simeq H\,\mathbf{x}, \qquad H = K_2\,R\,K_1^{-1}, $$

Here $K_1,K_2$ are the two intrinsics matrices and $R$ follows the convention above. With equal intrinsics this becomes $KRK^{-1}$; with normalized image coordinates it becomes $R$. The relation holds for rays with a valid destination projection, not for all output locations regardless of visibility.

The pure-rotation model avoids estimating scene depth. Fitting and rendering it still require numerical care, and geometric error minimization is nonlinear even though an algebraic initialization can be obtained linearly.

fig-depth-cancels-ray
Figure 20.1.3 (reproduced). Depth cancels for a pure rotation. A single viewing ray through the optical center carries scene points at many depths $(tx,ty,t)$; pinhole projection maps each to $(x/z,y/z)$, project is division by depth. Rotating the ray by $R$ multiplies all three coordinates by the same $t$; re-projecting divides it back out, so every point on the ray, near or far, reprojects to the same pixel in the rotated view. The destination pixel depends on the ray's direction and on $R$, never on depth, which is why we may simply set $z=1$.

Homographies and homogeneous coordinates⧉

in the book↗

The map $\mathbf{x}'\simeq H\mathbf{x}$ deserves its own vocabulary, because the same object recurs throughout the rest of the part. We have been implicitly using homogeneous coordinates: represent a 2D point $(u,v)$ by three numbers $(x,y,w)$, with $u=x/w$ and $v=y/w$. To recover the ordinary Euclidean point you divide by the last coordinate. A point therefore has no unique triple: every scaling $(wx,wy,w)$ names the same point, so homogeneous coordinates are defined up to scale. Two payoffs justify the bookkeeping. First, they make perspective (that very divide) and translation expressible as a single matrix multiply. Second, they are literally "treat the image as a plane at $z=1$ in 3D," which is exactly the picture from the previous section.

The construction is easiest to see one dimension down, where an image is a line and a point is a pair $(x,w)$ with $u=x/w$ (Figure 20.1.4). A camera that turns without moving sees each scene point along the same ray as before, so where the point lands in the new image cannot depend on its depth: any point of the ray will do, and $(u,1)$ is the one we have.

fig-1d-homography
Figure 20.1.4 (reproduced). A homography in one dimension (interactive). The plane drawn is $(x,w)$, with the center of projection at the origin. Stage 1: scene points (red) project along their rays onto image 1, the line $w=1$ (blue), at $u=x/w$; drag a red point along its ray and its depth changes while $u$ does not. Stage 2: image 2 is the same line turned by $\theta$ about the origin, a camera that rotated in place; each ray meets it at $u'$ (open magenta dots). Drag the square handle, or a blue point to turn its ray. Stage 3 redraws everything in camera 2's frame, where image 2 is $w'=1$, and forgets the depths: only $(u,1)$ is kept, and the $2\times2$ matrix $H=R(-\theta)$ sends it to $(x',w')$, a point still on the ray but not on image 2. Stage 4 divides by $w'$, and $u'=x'/w'$ lands exactly where the ray met image 2 in stage 2. A ray turned past $w'=0$ never meets image 2 in front of the camera, and $u'$ goes to infinity. Panorama stitching does the same in two dimensions, with $(x,y,w)$ and a $3\times3$ $H$.

A homography is represented by an invertible $3\times3$ matrix up to nonzero scale. It preserves straight lines, but can send points to infinity where the homogeneous denominator vanishes. Not every arbitrary corner arrangement gives a finite, nonsingular warp of the entire source rectangle.

How much freedom does $H$ have? It has nine entries, but it is defined up to scale, since $H$ and $kH$ produce the same map, because scaling all of $(w'x',\,w'y',\,w')$ by $k$ leaves the Euclidean point $(x',y')$ unchanged. So a homography has 8 degrees of freedom, not 9. It tells us exactly how much data we need: 4 point correspondences supply 8 numbers, just enough to pin $H$ down. (This is the same $s=4$ minimal sample random sample consensus (RANSAC) draws in the next chapter, Chapter 20.2, Automatic panorama stitching from multiple views and feature matching.)

Writing out $H=\left(\begin{smallmatrix}a&b&c\\ d&e&f\\ g&h&i\end{smallmatrix}\right)$, the per-point formula is

$$ x'=\frac{ax+by+c}{gx+hy+i}, \qquad y'=\frac{dx+ey+f}{gx+hy+i}. $$

The shared denominator $w'=gx+hy+i$ is the perspective divide; the entries $g$ and $h$ are what make parallel lines converge. Setting $g=h=0$ (and $i\neq0$) makes the denominator constant, which removes the perspective entirely and leaves a plain affine map. This standard projective-geometry material is laid out at length in Hartley and Zisserman and Szeliski.

fig-homography-quad
Figure 20.1.5 (reproduced). What a homography does to a plane. The input rectangle (left) maps to an arbitrary quadrilateral (right): parallel edges need not stay parallel; they may converge toward a vanishing point, but every straight line stays straight. This is the most general projective map of a plane, with 8 degrees of freedom; an affine map (no perspective) would keep the rectangle a parallelogram.
fig-pano-homography
Figure 11.1.4 (reproduced). Homography refresher (interactive). Get a feel for the $3\times3$ map before we solve for it: drag the four corners of a single image to reproject it and watch the matrix update, or edit the coefficients directly and watch the corners move. Zero the bottom-row perspective terms $g,h$ and the warp drops to affine, a parallelogram, no convergence; restore them for full projective freedom. The four draggable corners are the four correspondences that fix all eight degrees of freedom, exactly the four you will click to stitch in the next section. (The same sandbox introduces the homography in Chapter 11.1, Warping and resampling.)

Solving for $H$ from correspondences⧉

in the book↗

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⧉

in the book↗

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.

Another application: document flattening and merging⧉

optional

Everything above needed pure rotation because general scenes have depth. But there is a second route to the same homography, and it relaxes the rule entirely: a planar scene. If the scene is a single plane, a homography relates any two views of it, even when the camera translates, because a plane imposes one depth relationship across its whole surface, with no independent per-pixel depth to cause parallax. A plane photographed from any viewpoint maps to a plane by a homography. This is the planar twin of the rotation case.

Document rectification maps four detected page corners to a rectangle. Set its aspect ratio from known page dimensions or another justified constraint; arbitrary target dimensions can stretch the page. A homography cannot flatten a curved book page or remove lens distortion by itself (Figure 20.1.7).

The same machinery also handles document merging. To capture a document or whiteboard too big for one frame, shoot overlapping planar patches and stitch them with planar homographies, the identical pipeline as a panorama, except the homography is justified by the flat scene rather than by pure rotation. This is the basis of book scanning, mosaicing microscope slides, and tiling aerial or satellite images of locally flat ground.

Panoramas (rotation) and document rectification or merging (plane) are the same homography solve; only the geometric reason the homography is valid differs. Perspective-distortion correction (straightening a building's converging verticals) is the very same trick, and is developed alongside the warp machinery in Matching pixels across space and time.

fig-doc-flatten
Figure 20.1.7 (reproduced). Document flattening as the planar-scene case (interactive). A drawing photographed at an angle (left) appears as a keystoned quadrilateral; drag the four handles onto its corners and they become correspondences to a target rectangle. Solving for $H$ and warping yields a fronto-parallel, "scanned" page (right) with the rectangle restored and verticals upright, because the page is planar, so the homography holds even though the camera translated off to the side. Switch between three real children's drawings (a cat sketch, a lion on black paper, a framed dolphin) or upload your own page; only content on the page's plane rectifies exactly, so the surrounding wall stays distorted. Children's drawings photographed for this book.

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.

Special optics⧉

Tilt-shift and the Scheimpflug principle⧉

optional

A normal lens is mounted with its optical axis perpendicular to the sensor and centered on it. A tilt-shift lens (also called a perspective-control lens) breaks that rigid mounting in two independent ways, and the two do entirely different jobs.

Shift slides the lens parallel to the sensor, keeping the axis perpendicular. Because the lens projects a circular image and the sensor samples a rectangle out of it, shifting moves the rectangle to a different part of the image circle, as if you had cropped off-center from a wider view. The payoff is perspective control: point a camera up at a building and the verticals converge (the classic keystoning); raise the lens by shifting instead, keep the sensor vertical, and the building's edges stay parallel, because the projection plane never tilted. For a panorama, moving the sensor behind a stationary lens preserves the viewpoint. Shifting the lens on a fixed camera body moves the entrance pupil and can introduce parallax, especially for nearby objects. A lens-mounted support with rear shift or a compensating camera movement addresses this distinction. The only cost is that the lens must throw a much larger image circle than the sensor needs, so there is room to shift into.

fig-tilt-shift-perspective
Figure 22.7.1 (reproduced). The shift movement and perspective control. Tilting the whole camera up to fit a tall building makes the verticals converge, the classic keystoning; instead keeping the sensor vertical and raising the lens within its oversized image circle keeps the verticals parallel, because the projection plane never tilts.

Tilt is the more surprising motion: rotate the lens so its axis is no longer perpendicular to the sensor. For an ordinary lens, the plane of sharp focus is parallel to the sensor, a flat slab at one distance. Tilt the lens and that plane also tilts, but not by the same angle, and it pivots about a line you can locate exactly. The Scheimpflug condition Scheimpflug 1904 says it cleanly: the lens plane, the sensor (image) plane, and the plane of sharp focus all intersect along a single line in space, the Scheimpflug line. When the lens is untilted, the three planes are mutually parallel and that line sits at infinity (the familiar slab-at-one-distance case); tilt the lens and the line swings in to a finite place, swinging the focus plane with it.

fig-scheimpflug-tilt
Figure 22.7.2 (reproduced). Tilt and the Scheimpflug condition. Rotating the lens tilts the plane of sharp focus; the lens plane, the sensor plane, and the focus plane all meet along one line in space, the Scheimpflug line, so the in-focus region becomes a wedge that can be laid along a receding surface like a tabletop.

There is a companion rule for where the focus plane pivots, called the hinge rule. The plane of sharp focus rotates about a second line, the "hinge", at the intersection of the front focal plane and a plane through the lens center parallel to the sensor. In the thin-lens construction its distance from the lens center is $f/\sin\theta$, where $\theta$ is the lens tilt relative to the sensor. The practical reading is that the Scheimpflug line fixes the intersection of the focus plane with the lens, while the hinge line is the axis the focus plane swings around as you refocus: change focus and the focus plane rotates about the hinge like a trapdoor, rather than sliding back and forth as in a normal lens. Photographers use this two ways. Tilt to align the focus plane with a receding surface (a tabletop, a landscape foreground-to-background) and the whole surface is sharp at full aperture. Or tilt the other way, so the focus plane slices across the scene as a thin diagonal wedge, throwing most of the frame out of focus; that is the toy-town "miniature faking" look (the same look software now fakes with a graded blur).

Be precise about what tilt does and does not buy, because it ties straight into depth of field. Tilt redistributes the region of acceptable sharpness. It does not simply add a uniform thickness to the untilted depth of field: the in-focus region, normally a slab parallel to the sensor, becomes a wedge that fans out from the hinge line, thin near the camera and opening up far away. You are not getting more sharpness; you are choosing where to spend it (cross-reference Chapter 23.1, Bokeh, focus stacking, and depth-of-field control).