From Pixels to Matches: A Visual Journey Through Classical Computer Vision


1. Frequency, Sharpening, and Hybrid Images

Gaussian blur smooths an image by averaging each pixel with its neighbours. If you treat blur only as something that removes information — fine details vanish, noise disappears — that story is true, but it misses a deeper insight.

Blur doesn't destroy information. It separates it. The blurred image contains everything that changes slowly across the image — broad shapes, smooth gradients, overall tone. And everything the blur removed? That's still recoverable — just subtract. The difference between the original and the blurred version is exactly the detail that was lost: edges, textures, fine structure.

This one observation — original = blurred + detail — unlocks a remarkable set of techniques. The same split supports sharpening and one of the most striking illusions in computer vision: hybrid images, where two different pictures coexist in the same image, and which one you see depends on how far away you stand.


1.1 Frequency Decomposition: The Simplest Separation

What does "frequency" mean for an image? Forget Fourier transforms for a moment — the intuition is simpler than that.

Look at any photograph. Some parts change slowly: the broad sweep of a clear sky, the gradual shadow gradation on a wall, the overall brightness of a face. These are low-frequency components — they describe the large-scale structure.

Other parts change rapidly: the sharp boundary where a building meets the sky, the texture of hair, the weave of fabric, the edges of letters. These are high-frequency components — they carry the fine detail.

The key idea: Gaussian blur isolates the slowly-varying part. The blurred image is the low-frequency component. And the high-frequency component? Just subtract:

$$ \text{High} = \text{Original} - \text{Low} $$

That's it. The most fundamental frequency decomposition in image processing is a single subtraction.

Frequency decomposition: Original = Low Frequency (blur) + High Frequency (detail)

Figure code: code/ch03_frequency_hybrid.py.

Frequency decomposition of a real image. Left: original. Centre: low-frequency component (Gaussian blur) — smooth structure only. Right: high-frequency component (original minus blur) — edges, textures, and fine detail.

The figure above shows this decomposition on a real image. The left column is the original. The middle column is the Gaussian-blurred version (low frequency) — notice how it preserves the overall structure but loses all sharp edges. The right column is the difference (high frequency) — it's a ghostly image of pure detail: edges, textures, and fine transitions, with everything smooth removed.

import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE).astype(np.float64)

sigma = 3.0
low = cv2.GaussianBlur(img, (0, 0), sigma)
high = img - low

# Verify the decomposition
reconstructed = low + high  # identical to img

Key takeaway: any image can be split into a low-frequency component (Gaussian blur) and a high-frequency component (original minus blur). The two sum back to the original perfectly.

What exactly are "low" and "high" frequency? Think of frequency as how quickly pixel values change across space. A region where values barely change from pixel to pixel has low spatial frequency. A region where values alternate rapidly — bright, dark, bright, dark — has high spatial frequency.

Low-frequency content encodes large-scale structure: the shape of objects, the overall illumination, smooth gradients. If you squint at an image (which optically blurs it), you're seeing the low frequencies.

High-frequency content encodes fine detail: edges, textures, noise, and sharp transitions. If you can only see it when you look closely, it's high frequency.

The σ of the Gaussian blur controls where you draw the line between "low" and "high." With a small σ (gentle blur), very little lands in the "low" band — almost only the slowest luminance drift. With a large σ (strong blur), far more is classified as low frequency, and the "high" side keeps only the sharpest edges. There is no single correct cutoff — σ is a design choice.

The subtraction $\text{High} = I - G_\sigma * I$ has an elegant interpretation in the frequency domain. The Fourier transform of a Gaussian $G_\sigma$ is another Gaussian:

$$ \hat{G}_\sigma(\omega) = e^{-2\pi^2 \sigma^2 \omega^2} $$

This is a low-pass filter: it passes low frequencies (small $\omega$) with values near 1, and attenuates high frequencies (large $\omega$) toward 0.

The blurred image in the frequency domain is:

$$ \widehat{\text{Low}}(\omega) = \hat{G}_\sigma(\omega) \cdot \hat{I}(\omega) $$

The high-frequency component is:

$$ \widehat{\text{High}}(\omega) = \hat{I}(\omega) - \hat{G}\sigma(\omega) \cdot \hat{I}(\omega) = \left(1 - \hat{G}\sigma(\omega)\right) \cdot \hat{I}(\omega) $$

The transfer function $H(\omega) = 1 - e^{-2\pi^2 \sigma^2 \omega^2}$ is a high-pass filter: it's 0 at $\omega = 0$ (removes the DC / average intensity), and approaches 1 for large $\omega$ (passes high frequencies through).

So the simple subtraction $I - G_\sigma * I$ acts, in the Fourier sense, like a high-pass filter — not a literal ideal step cutoff. You do not need an explicit FFT here; convolution with a Gaussian in the spatial domain achieves the same idea.

FFT-based frequency intuition: spectrum, low-pass mask, high-pass mask, and their results

Figure code: code/ch03_frequency_hybrid.py.

Fourier perspective on filtering. Top-right: FFT magnitude spectrum. Middle row: a low-pass circular mask keeps the centre → blurred result. Bottom row: a high-pass mask keeps the outer ring → edges and detail only.

The figure above shows this from the Fourier perspective. Starting from a photo (top-left), we compute the FFT magnitude spectrum (top-right). Applying a low-pass mask (middle-left) keeps only the central region of the spectrum — the result (middle-right) is a blurred image. Applying a high-pass mask (bottom-left) keeps only the outer ring — the result (bottom-right) is the detail image. These correspond exactly to our spatial-domain blur and subtract operations.


1.2 Image Sharpening: Unsharp Masking

With high-frequency detail defined as $\text{Original} - \text{Low}$, a natural question arises: what if we amplify it?

If the original image looks a bit soft — perhaps due to slight camera motion, a cheap lens, or lossy compression — we can make it look sharper by boosting the high-frequency content. The technique is called Unsharp Masking, and despite the counterintuitive name (why say "unsharp" when you are really sharpening?), the idea is beautifully simple.

By definition,

$$ \text{High} = \text{Original} - \text{Low} $$

To sharpen, we add a scaled version of the high-frequency detail back to the original:

$$ \text{Sharpened} = \text{Original} + k \times \text{High} $$

where $k > 0$ controls the sharpening strength. Expanding:

$$ \text{Sharpened} = \text{Original} + k \times (\text{Original} - \text{Blurred}) $$

$$ = (1 + k) \times \text{Original} - k \times \text{Blurred} $$

The parameter $k$ acts as a volume knob for detail. With $k = 0$, you get the original. As $k$ increases, edges become crisper, textures more pronounced — but push too hard and you'll amplify noise and create halos around edges.

Unsharp masking pipeline: Original → Blurred → High Frequency → Sharpened at k=0.5, 1.0, 2.0

Figure code: code/ch03_frequency_hybrid.py.

Unsharp masking pipeline: original → blur → detail (original − blur) → sharpened at three strengths k. Higher k gives crisper edges but risks halo artefacts (visible at k = 2.0).

The figure above walks through the full pipeline. Start with the original, blur it to get the low-frequency component, subtract to get the high-frequency detail, then add it back with different strengths. At $k = 0.5$, the sharpening is subtle — a gentle boost to edges. At $k = 1.0$, it's clearly sharper. At $k = 2.0$, the effect is aggressive — edges are very crisp, but notice the halo artifacts beginning to appear.

sigma = 2.0
k = 1.0

low = cv2.GaussianBlur(img, (0, 0), sigma)
high = img - low
sharpened = np.clip(img + k * high, 0, 255).astype(np.uint8)

Key takeaway: sharpening = original + k × (original − blurred). The parameter k controls strength; σ controls which details get boosted.

Why is it called "Unsharp" Masking? The name comes from darkroom photography. To sharpen a print, photographers would create a slightly blurred ("unsharp") copy of the negative on a separate film. This blurred copy was the "unsharp mask." By sandwiching it with the original and exposing them together with adjusted contrast, the difference — the high-frequency detail — was amplified. The digital version is the same idea, just expressed as arithmetic.

Choosing σ and k. The Gaussian σ determines which scale of detail gets sharpened. A small σ (say, 1) targets very fine detail — individual pixels, noise, texture grain. A larger σ (say, 3–5) targets broader features — edges, contours, text outlines. In practice:

  • For noise-free images (scanned documents, renders): small σ and moderate $k$ work well.
  • For noisy photos (phone cameras in low light): use a larger σ to avoid amplifying noise, and keep $k$ modest.
  • If you see bright/dark halos around edges, $k$ is too high. Reduce it.

The formula, rearranged. The sharpened image can be written as:

$$\text{Sharpened} = (1 + k) \cdot I - k \cdot G_\sigma * I$$

This reveals that sharpening is a linear combination of the original and the blurred image. When $k = 1$, we get $2I - G_\sigma * I$: double the original minus the blur. The original's weight always exceeds the blur's weight, so the net effect is to push pixel values away from the local average — which is exactly what "sharpening" means.

Let's derive the frequency-domain transfer function of unsharp masking. The sharpened image is:

$$ S = I + k(I - G_\sigma * I) = (1 + k)I - k , G_\sigma * I $$

Taking the Fourier transform:

$$ \hat{S}(\omega) = (1 + k)\hat{I}(\omega) - k,\hat{G}\sigma(\omega)\hat{I}(\omega) = \left[(1 + k) - k,\hat{G}\sigma(\omega)\right] \hat{I}(\omega) $$

The transfer function is:

$$ H_{\text{sharp}}(\omega) = (1 + k) - k , e^{-2\pi^2 \sigma^2 \omega^2} $$

Let's evaluate at the extremes:

  • At $\omega = 0$ (DC, constant component): $H(0) = (1+k) - k \cdot 1 = 1$. The average brightness is preserved — sharpening doesn't change the overall image intensity.
  • At $\omega \to \infty$ (highest frequencies): $H(\infty) = (1+k) - k \cdot 0 = 1 + k$. High frequencies are amplified by a factor of $1 + k$.

So unsharp masking is a high-boost filter: the DC component passes unchanged, and higher frequencies are boosted progressively; the gain at the highest frequencies tops out at $1 + k$. Larger $k$ means stronger boost at high frequencies. Larger σ means the boost begins at lower frequencies (so coarser features are affected too).

Comparison with an ideal high-boost. An "ideal" sharpening filter would have $H(\omega) = 1$ for $|\omega| < \omega_c$ and $H(\omega) = 1 + k$ for $|\omega| \geq \omega_c$. The Gaussian version transitions much more smoothly, avoiding the ringing artifacts of a hard cutoff.


1.3 Hybrid Images: Two Pictures in One

This demonstration uses only Gaussian low-pass filtering and a high-pass component $\text{Original} - \text{Low}$. The idea is: take the low-frequency content from one image and the high-frequency content from another, and add them together. You get a single image that can read as two completely different things, depending on your viewing distance.

Why does this work? Because human vision doesn't process all frequencies equally. When you view an image up close, your visual system is sensitive to fine detail — high frequencies dominate your perception. But when you step back (or squint, or see a tiny thumbnail), those high frequencies become invisible, and you perceive only the low-frequency structure.

A hybrid image exploits this by embedding two different pictures in different frequency bands. Up close, you see Image B (carried by high frequencies). From farther away, you see Image A (carried by low frequencies).

Hybrid image construction: Image A low-pass + Image B high-pass → Hybrid

Figure code: code/ch03_frequency_hybrid.py.

Hybrid image construction: Image A is low-pass filtered (smooth structure), Image B is high-pass filtered (edges and texture), and the two are summed. The result encodes both images in different frequency bands.

The construction is straightforward:

  1. Low-pass filter Image A (blur it) — this becomes the "far away" image.
  2. High-pass filter Image B (subtract its blur) — this becomes the "up close" image.
  3. Add them together.
sigma_low = 4.0   # controls A's blur — larger = smoother
sigma_high = 2.0  # controls B's detail extraction

# Low-pass: keep A's large-scale structure
low_A = cv2.GaussianBlur(img_a, (0, 0), sigma_low)

# High-pass: extract B's fine detail
high_B = img_b - cv2.GaussianBlur(img_b, (0, 0), sigma_high)

# Combine
hybrid = np.clip(low_A + high_B, 0, 255).astype(np.uint8)

Now look at the result from different distances:

Hybrid image viewed at decreasing sizes — transitions from high-freq to low-freq perception

Figure code: code/ch03_frequency_hybrid.py.

Simulated viewing distance: as the image shrinks (equivalent to moving farther away), perception shifts from Image B's high-frequency detail to Image A's low-frequency structure.

This is the magic. The GIF above simulates what happens as you move farther away from a hybrid image (or equivalently, as the image shrinks). Up close, the high-frequency content — Image B's edges and textures — dominates your perception. As the viewing distance increases (the image gets smaller), those fine details fall below your visual resolution, and what remains is Image A's smooth, low-frequency structure. Two completely different images, occupying the same pixels.

Key takeaway: a hybrid image combines the low frequencies of one image with the high frequencies of another. Up close you see the high-frequency image; from far away, the low-frequency one.

Why does viewing distance change what you see? This is rooted in the contrast sensitivity function (CSF) of human vision. The CSF describes how sensitive your visual system is to patterns of different spatial frequencies. At normal viewing distances, sensitivity peaks at mid-range frequencies (around 3–5 cycles/degree of visual angle) and drops off at both extremes.

Crucially, spatial frequency in cycles per degree depends on both the image's frequency content and the viewing distance. When you step farther away, the same image detail subtends a smaller angle on your retina, effectively pushing it to a higher cycles-per-degree value. At some point, the fine detail exceeds your contrast sensitivity threshold and becomes invisible — your visual system can no longer resolve it. What remains is only the low-frequency content.

Choosing σ_low and σ_high. These two parameters control the "crossover" between the two images:

  • σ_low (for Image A): A larger σ removes more of A's detail, making it appear only at greater viewing distances. Typical values: 3–7.
  • σ_high (for Image B): A smaller σ preserves more of B's mid-frequency content, making it visible from farther away. A larger σ restricts B to only the finest detail. Typical values: 1–4.
  • The two σ values should be different — usually $\sigma_\text{low} > \sigma_\text{high}$ — to avoid a frequency band where both images are visible, which would create a muddy overlap.

Alignment matters. For the illusion to work well, the two source images should be roughly aligned — same size, similar overall composition (e.g., two faces in the same pose, two animals with similar silhouettes). Misalignment in low-frequency structure creates a confusing double-exposure effect.

Let's reason quantitatively about the hybrid image parameters. The hybrid image is:

$$ H = G_{\sigma_\text{low}} * I_A + (I_B - G_{\sigma_\text{high}} * I_B) $$

In the frequency domain:

$$ \hat{H}(\omega) = \hat{G}{\sigma\text{low}}(\omega) \cdot \hat{I}A(\omega) + \left(1 - \hat{G}{\sigma_\text{high}}(\omega)\right) \cdot \hat{I}_B(\omega) $$

The contribution of Image A is weighted by $\hat{G}{\sigma\text{low}}(\omega) = e^{-2\pi^2 \sigma_\text{low}^2 \omega^2}$, which is significant only for low frequencies.

The contribution of Image B is weighted by $1 - e^{-2\pi^2 \sigma_\text{high}^2 \omega^2}$, which is significant only for high frequencies.

The crossover frequency $\omega_c$ is where both weights are equal:

$$ e^{-2\pi^2 \sigma_\text{low}^2 \omega_c^2} = 1 - e^{-2\pi^2 \sigma_\text{high}^2 \omega_c^2} $$

This equation doesn't have a clean closed-form solution, but we can understand the design principles:

  • If $\sigma_\text{low} \gg \sigma_\text{high}$: the low-pass for A cuts off at a much lower frequency than the high-pass for B kicks in. There's a gap in the middle where neither image contributes much — the hybrid looks cleaner, but some frequency content is lost.
  • If $\sigma_\text{low} \approx \sigma_\text{high}$: the two filters overlap significantly in mid-frequencies, and both images are partially visible — the hybrid looks muddled.
  • A good operating range: $\sigma_\text{low} \approx 2\sigma_\text{high}$, which creates a smooth handoff between the two images with minimal overlap.

Example: With $\sigma_\text{low} = 4$ and $\sigma_\text{high} = 2$:

  • The low-pass (−3 dB) cutoff for A: $\omega \approx \frac{1}{2\pi \times 4} \approx 0.04$ cycles/pixel
  • The high-pass effectively kicks in around: $\omega \approx \frac{1}{2\pi \times 2} \approx 0.08$ cycles/pixel

The gap between 0.04 and 0.08 cycles/pixel is where neither image dominates — this is the transition zone. For a 512-pixel image, these correspond to structures roughly 25 and 12 pixels wide, respectively.


1.4 The Hybrid Image in Practice

Let's put it all together with a complete example. The recipe is:

  1. Load two images of the same size.
  2. Choose σ values for the low-pass and high-pass.
  3. Compute the low-frequency component of Image A and the high-frequency component of Image B.
  4. Add them and clip to valid pixel range.
import cv2
import numpy as np

# Load source images (same size, aligned)
img_a = cv2.imread("image_a.jpg", cv2.IMREAD_GRAYSCALE).astype(np.float64)
img_b = cv2.imread("image_b.jpg", cv2.IMREAD_GRAYSCALE).astype(np.float64)

sigma_low = 4.0
sigma_high = 2.0

# Decompose
low_A = cv2.GaussianBlur(img_a, (0, 0), sigma_low)
high_B = img_b - cv2.GaussianBlur(img_b, (0, 0), sigma_high)

# Combine
hybrid = np.clip(low_A + high_B, 0, 255).astype(np.uint8)

cv2.imwrite("hybrid.jpg", hybrid)

To verify the illusion works, progressively downsample the hybrid image — this simulates increasing viewing distance:

display = hybrid.copy()
for i in range(5):
    h, w = display.shape[:2]
    display = cv2.resize(display, (w // 2, h // 2))
    cv2.imwrite(f"hybrid_scale_{i}.jpg", display)

As the image shrinks, the high-frequency content from Image B disappears, and Image A's low-frequency structure emerges — matching the behaviour shown in the demonstration GIF.

Practical tips for creating good hybrid images:

  • Alignment is crucial. The two images should have similar overall layout. For faces, align the eyes and mouth. For objects, match the silhouette.
  • Start with σ_low = 4–6 and σ_high = 1–3. Adjust based on the image resolution and how dramatic you want the transition to be.
  • The low-frequency image dominates the overall brightness. If the two source images have very different average intensities, the hybrid may look washed out. Consider normalising both images to similar mean/contrast first.
  • Colour hybrids are possible — apply the same decomposition independently to each colour channel. Low-frequency colour from Image A combined with high-frequency detail from Image B can produce especially compelling results.

1.5 Key Takeaways

  • Frequency decomposition is a subtraction. Blur an image to get the low-frequency component; subtract the blur from the original to get the high-frequency component. They sum back perfectly.
  • Low frequency = large-scale structure (shapes, gradients, illumination). High frequency = fine detail (edges, textures, noise).
  • Unsharp masking sharpens by boosting high frequencies: $\text{sharpened} = \text{original} + k \times (\text{original} - \text{blurred})$. The parameter $k$ controls strength; σ controls the scale of detail affected.
  • Hybrid images combine the low frequencies of one image with the high frequencies of another. The result contains two perceptual interpretations: high-frequency content dominates up close, low-frequency content dominates from far away.
  • The viewing-distance effect arises because human contrast sensitivity for high spatial frequencies drops when the image subtends a smaller visual angle — fine detail simply becomes unresolvable.

2. Image Pyramids

Gaussian blur controls what scale of detail you see — small σ preserves fine texture, large σ keeps only broad shapes. But we always had to choose one σ. What if you want to work at all scales simultaneously?

Consider a face detector. A face might occupy 500 pixels in a selfie or 50 pixels in a crowd photo. A filter tuned for the big face will miss the small one, and vice versa. You need a way to represent the same image at many resolutions at once — and that's exactly what an image pyramid does.

The Gaussian pyramid and the Laplacian pyramid decompose an image into a stack of scales that you can analyse, manipulate, and perfectly reconstruct.


2.1 Why Multi-Scale?

A single image contains structure at every scale: broad illumination gradients, medium-scale object boundaries, fine textures, and tiny noise. A fixed-size filter sees only one scale at a time. To find features at all sizes, you need to look at the image at all resolutions.

The image pyramid is the classic solution. Think of it literally: a stack of images, largest at the bottom, smallest at the top. Each level is a smaller, coarser version of the one below. By searching each level, you cover every scale — big objects are found in the small levels (where they're a manageable size), and fine details are found in the large levels.

Key insight: a pyramid converts the problem of "search at all scales" into "search at one scale, on multiple images." That is far more efficient than resizing or retuning the filter separately for every scale you care about.


2.2 The Gaussian Pyramid

The Gaussian pyramid is built by a simple two-step loop: blur, then downsample by 2.

A 5-level Gaussian pyramid displayed side by side, each level labelled with dimensions

Figure code: code/ch04_pyramids.py.

A 5-level Gaussian pyramid. Each level is half the width and height of its predecessor; dimensions are annotated above each panel. Level 0 is the original image.

Starting from the original image (level 0), each successive level is half the width and half the height of the previous one. Level 1 has $\frac{1}{4}$ the pixels of the original, level 2 has $\frac{1}{16}$, and level $k$ has $\frac{1}{4^k}$ the pixels.

The construction in code is a single loop:

import cv2
import numpy as np

def build_gaussian_pyramid(img, levels=5):
    pyr = [img.copy()]
    for _ in range(levels - 1):
        img = cv2.pyrDown(img)
        pyr.append(img)
    return pyr

cv2.pyrDown does both steps internally: it applies a 5×5 Gaussian blur and then removes every other row and column. That's the entire algorithm.

Key takeaway: the Gaussian pyramid is a multi-scale representation. Level 0 is the original; each subsequent level is half the resolution, capturing progressively coarser structure.

Why must we blur before downsampling? This is the single most important detail in pyramid construction — skip the blur, and the result is broken.

When you throw away every other pixel, you're cutting the resolution in half. But the original image may contain detail that oscillates faster than the new, coarser pixel grid can represent. If that high-frequency detail is still present when you downsample, it doesn't simply disappear — it folds back into lower frequencies, creating phantom patterns that weren't in the original. This is called aliasing.

The Gaussian blur before downsampling is an anti-aliasing filter. It removes the high frequencies that would cause trouble, so that what remains can be faithfully represented at the lower resolution. Blur first, then downsample — always.

Think of it this way: downsampling halves the maximum representable frequency (the Nyquist limit). The Gaussian blur ensures no signal energy exists above this new limit before the samples are discarded.

The Nyquist–Shannon sampling theorem states that a bandlimited signal can be perfectly reconstructed from its samples if and only if the sampling rate exceeds twice the signal's highest frequency:

$$ f_s > 2 f_{\max} $$

where $f_s$ is the sampling rate and $f_{\max}$ is the highest frequency present in the signal. The frequency $f_N = f_s / 2$ is the Nyquist frequency — the maximum frequency the sampled signal can represent.

When we downsample an image by a factor of 2, the new sampling rate is half the original. The new Nyquist frequency is therefore half the old one. Any frequency content above this new Nyquist limit violates the sampling theorem.

What happens to those frequencies? They don't vanish — they alias. A frequency $f$ above the Nyquist limit appears as $f_s - f$ in the downsampled signal. Visually, this manifests as moiré patterns, jagged edges, and phantom textures — structures that appear in the downsampled image but don't exist in the original.

The Gaussian blur applied before downsampling acts as a low-pass filter that attenuates frequencies above the new Nyquist limit:

$$ \hat{G}_\sigma(\omega) = e^{-2\pi^2 \sigma^2 \omega^2} $$

For cv2.pyrDown, the built-in 5×5 kernel is designed so that its frequency response is sufficiently small at the Nyquist limit of the half-resolution grid. This ensures the downsampled result is a clean, alias-free representation of the low-frequency content.

Without the blur, downsampling a checkerboard-like pattern (pure high frequency) can produce a uniform grey — the high-frequency signal aliases into DC. The information isn't just lost; it's corrupted into something misleading.


2.3 The Laplacian Pyramid

The Gaussian pyramid tells you what the image looks like at each scale, but it's redundant — adjacent levels share most of their information. The Laplacian pyramid is a cleverer encoding: it stores only the difference between adjacent Gaussian levels. Each Laplacian level captures the detail that was lost when moving from one scale to the next.

Top row: Gaussian pyramid; Bottom row: Laplacian pyramid (difference of adjacent levels). Last level is the residual.

Figure code: code/ch04_pyramids.py.

Top row: Gaussian pyramid levels (progressively blurred). Bottom row: Laplacian (band-pass) levels, each showing the detail lost between consecutive Gaussian levels. The last level is the low-frequency residual.

The construction is:

$$ L_i = G_i - \text{expand}(G_{i+1}) $$

where $G_i$ is Gaussian level $i$, and $\text{expand}(G_{i+1})$ upsamples $G_{i+1}$ back to the size of $G_i$ (using cv2.pyrUp). The difference captures everything that existed in $G_i$ but not in $G_{i+1}$ — the detail at scale $i$.

The last level of the Laplacian pyramid is simply the smallest Gaussian level itself (the residual) — there's no smaller level to subtract from.

def build_laplacian_pyramid(gauss_pyr):
    lap = []
    for i in range(len(gauss_pyr) - 1):
        expanded = cv2.pyrUp(gauss_pyr[i + 1],
                             dstsize=(gauss_pyr[i].shape[1],
                                      gauss_pyr[i].shape[0]))
        diff = gauss_pyr[i].astype(np.float64) - expanded.astype(np.float64)
        lap.append(diff)
    lap.append(gauss_pyr[-1].astype(np.float64))  # residual
    return lap

Notice the cast to float64 — Laplacian levels contain signed values (positive where the fine-scale image was brighter, negative where it was darker), so they can't be stored as uint8.

Key takeaway: Laplacian level $i$ = Gaussian level $i$ minus the upsampled Gaussian level $i+1$. It captures the detail lost between scales. The last level is the low-resolution residual.

The Laplacian pyramid as bandpass decomposition. Each Laplacian level holds a specific band of spatial frequencies. Level 0 contains the highest frequencies (finest detail), level 1 contains the next band, and so on. The residual contains the lowest frequencies (coarsest structure).

This is exactly a bandpass decomposition: the image is split into non-overlapping frequency bands that together account for all the information. No frequency is lost, and no frequency is counted twice. This is why the Laplacian pyramid enables lossless reconstruction — the bands tile the full frequency spectrum.

Compare this to a single low/high frequency split (original minus one low-pass), where there is just one low and one high band. The Laplacian pyramid generalises that idea to many bands at exponentially spaced scales.

Let $G_\sigma$ denote a Gaussian blur with standard deviation $\sigma$, and let $\downarrow_2$ denote downsampling by 2. The Gaussian pyramid levels are:

$$ G_0 = I, \quad G_{k+1} = \downarrow_2 (G_\sigma * G_k) $$

Each Laplacian level is defined as:

$$ L_k = G_k - \uparrow_2(G_{k+1}) $$

where $\uparrow_2$ denotes upsampling (with interpolation via pyrUp).

Consider the frequency-domain interpretation. Each Gaussian level $G_k$ is approximately $I$ convolved with a Gaussian of effective standard deviation $\sigma_k \approx \sigma \sqrt{\sum_{j=0}^{k-1} 4^j}$ (accounting for the cumulative blur across levels, with the factor of 4 from the resolution halving at each step).

The Laplacian level $L_k$ captures the frequency content between the effective cutoff of $G_k$ and the effective cutoff of $G_{k+1}$. In the frequency domain:

$$ \hat{L}k(\omega) \approx \left[\hat{G}{\sigma_k}(\omega) - \hat{G}{\sigma{k+1}}(\omega)\right] \cdot \hat{I}(\omega) $$

The transfer function $\hat{G}{\sigma_k}(\omega) - \hat{G}{\sigma_{k+1}}(\omega)$ is a bandpass filter — it's near zero for both very low frequencies (where both Gaussians pass equally) and very high frequencies (where both Gaussians block). It peaks at an intermediate frequency determined by $\sigma_k$ and $\sigma_{k+1}$.

The key property: these bandpass filters, together with the residual low-pass $\hat{G}_{\sigma_N}$, form a partition of unity over the frequency spectrum:

$$ \sum_{k=0}^{N-1} \left[\hat{G}{\sigma_k}(\omega) - \hat{G}{\sigma_{k+1}}(\omega)\right] + \hat{G}{\sigma_N}(\omega) = \hat{G}{\sigma_0}(\omega) = 1 $$

This is a telescoping sum — all intermediate terms cancel, leaving only the first ($\hat{G}_{\sigma_0} = 1$, the identity) minus the last, plus the last. The sum is exactly 1 at every frequency. No information is lost and none is duplicated. This is why reconstruction is exact (up to numerical precision): summing all the Laplacian levels and the residual recovers every frequency component of the original.

The name "Laplacian" is somewhat historical — the operation is not literally the Laplacian differential operator $\nabla^2$, but a Difference of Gaussians (DoG), which approximates the Laplacian of Gaussian ($\nabla^2 G$). The connection comes from the identity:

$$ \nabla^2 G_\sigma \approx \frac{G_{\sigma} - G_{k\sigma}}{\sigma^2(k-1)} $$

for $k$ close to 1. In the pyramid, the effective ratio between adjacent scales is $k \approx 2$, so each level approximates a scale-normalised Laplacian at that scale.


2.4 Reconstruction: Proving the Decomposition Is Lossless

If the Laplacian pyramid truly captures all the information in the image, we should be able to rebuild the original from it — perfectly. And we can.

The algorithm starts from the residual (the smallest level) and works upward, adding back each Laplacian level:

def reconstruct_from_laplacian(lpyr):
    recon = lpyr[-1].copy()
    for i in range(len(lpyr) - 2, -1, -1):
        recon = cv2.pyrUp(recon,
                          dstsize=(lpyr[i].shape[1], lpyr[i].shape[0]))
        recon = recon + lpyr[i]
    return recon

At each step, we upsample the running reconstruction (expanding it to the next larger size) and add the Laplacian level — which restores exactly the detail that was removed at that scale.

Three columns: Original | Reconstructed from Laplacian pyramid | |Difference| (≈ 0)

Figure code: code/ch04_pyramids.py.

Lossless reconstruction test: original (left), rebuilt from Laplacian pyramid (centre), absolute difference (right, ≈ 0 everywhere). The transform is perfectly invertible.

The figure tells the story: the reconstructed image is visually identical to the original, and the absolute difference is essentially zero everywhere (within floating-point rounding). The Laplacian pyramid is a lossless, invertible transform.

Why does this work? Unrolling one step of the reconstruction:

$$\text{recon}i = \text{expand}(\text{recon}{i+1}) + L_i$$

But $L_i = G_i - \text{expand}(G_{i+1})$ by definition. If $\text{recon}{i+1} = G{i+1}$ (the induction hypothesis), then:

$$\text{recon}i = \text{expand}(G{i+1}) + G_i - \text{expand}(G_{i+1}) = G_i$$

The expand terms cancel perfectly. Starting from $\text{recon}_N = G_N = L_N$ (the residual), the induction carries all the way to $\text{recon}_0 = G_0 = I$. The reconstruction is exact by construction — it's not an approximation; it's algebraic cancellation.


2.5 Applications

The Laplacian pyramid isn't just a theoretical curiosity. It powers some of the most important techniques in computer vision and image processing:

  • Laplacian pyramid blending. Want to seamlessly stitch two images together? Decompose both into Laplacian pyramids, blend each level separately (using a mask that is also pyramided), then reconstruct. The result has smooth transitions at every scale — no visible seam. This is the classic Burt & Adelson (1983) algorithm.

  • Texture synthesis and image editing. Working on one pyramid level at a time lets you manipulate detail at a specific scale without disturbing others — boost fine texture without affecting overall colour, or adjust broad illumination without touching edges.

  • Multi-scale template matching. Searching for an object at a single resolution is slow and brittle. Search the smallest pyramid level first (fast, coarse localisation), then refine at larger levels. This coarse-to-fine strategy is standard in optical flow, stereo matching, and registration.

  • SIFT scale space. The Difference-of-Gaussians (DoG) at the heart of the Laplacian pyramid is the same construction SIFT uses to build a scale space and search for extrema.


2.6 Key Takeaways

  • The Gaussian pyramid is a multi-scale representation: each level is blurred and downsampled by 2, giving half the resolution of the level below.
  • Blur before downsample — always. Skipping the blur causes aliasing: high frequencies fold into low frequencies, creating artifacts.
  • The Laplacian pyramid stores the detail lost between adjacent Gaussian levels. Each level is a bandpass-filtered version of the image.
  • The decomposition is lossless. Starting from the residual and adding Laplacian levels back one by one recovers the original exactly.
  • Pyramids enable multi-scale processing: blending, matching, detection, and the scale spaces used by modern feature detectors.

Appendix: Reproducing All Figures

Every figure in this tutorial is generated from Python code. Download the self-contained package below — unzip, install dependencies, and run one command to regenerate all 8 figures from scratch:

Download code.zip (contains source code + input images, ~1 MB)

unzip code.zip -d code && cd code
pip install -r requirements.txt
python generate.py

To regenerate figures for a single chapter only:

python generate.py 3   # Chapter 3: frequency decomposition, unsharp masking, hybrid images
python generate.py 4   # Chapter 4: Gaussian pyramid, Laplacian pyramid, reconstruction

See code/README.md for the full file listing and details.