---
title: Two-dimensional signals and images
heading: 2D convolution and the 2D DFT, separable filters, edge detection, spatial aliasing and cost
eyebrow: S7 · Lesson 45 · Two-dimensional signals and images
xp: 50
---

::: hook
An image is a two-dimensional sequence x[m, n], and nearly everything from the one-dimensional course carries over: convolution, frequency response, the DFT and its fast algorithm, sampling and aliasing. What changes is the cost, since every operation now runs over millions of pixels, and the structure: many useful 2D filters are separable, the product of a row filter and a column filter, which turns a K × K convolution into two passes of K. Blur, sharpening and edge detection in cameras, displays and vision systems are built on these few ideas.
:::

::: play
- The curves are the multiplications per pixel for filtering with a K × K kernel: directly, $K^2$; separably, 2K; and by 2D FFT on a 1024 × 1024 image, about 84 whatever K is.
- Small kernels are cheapest directly or separably; past about K = 9 an arbitrary kernel is cheaper by FFT, and a separable one stays cheaper, at 2K, until K exceeds 42.
- Gaussian blurs and many edge detectors are separable, which is why they run in real time on video.
:::

```sim plot
view: graph
x: K = 1..101 log
y: c = 1..10000 log
plot: K^2 | label: direct, K²
plot: 2*K | label: separable, 2K
plot: 84 + 0*K | dashed | label: 2D FFT, 1024²
```

::: predict
## A 7 × 7 Gaussian blur runs on 1080p video (1920 × 1080) at 60 frames a second. About how many multiplications per second does it take directly, and separably?

- [ ] 1 million and 100 000
- [x] About 6.1 billion directly, 1.7 billion separably
- [ ] About 60 billion either way
- [ ] The same, since the kernel is the same

::: reveal
The video carries 124.4 million pixels a second. Directly each needs 49 multiplications, 6.1 × 10⁹ a second; the Gaussian is separable, so a 7-tap row pass and a 7-tap column pass need 14, 1.7 × 10⁹. Symmetry halves both again in practice.
:::
:::

::: nameit
## Two-dimensional systems

A 2D LTI system is a 2D convolution, $y[m, n] = \sum_k\sum_lh[k, l]\,x[m - k, n - l]$, with frequency response $H(e^{j\omega_1}, e^{j\omega_2})$ over spatial frequencies in radians per pixel (horizontal and vertical).

- **Separable** kernels, $h[k, l] = h_1[k]h_2[l]$, filter rows then columns: 2K multiplications per pixel instead of $K^2$, and $H = H_1(e^{j\omega_1})H_2(e^{j\omega_2})$.
- The **2D DFT**, $X[k, l] = \sum_m\sum_nx[m, n]e^{-j2\pi(km/M + ln/N)}$, is separable too: 1D FFTs along every row, then every column, about $N^2\log_2N$ complex multiplications for an N × N image. Circular convolution, zero padding and fast convolution all work as in 1D.

## Common kernels

- **Box** and **Gaussian** blurs (lowpass); the Gaussian is separable and has no ringing.
- **Sobel** edge detector: $G_x = \begin{bmatrix}1\\2\\1\end{bmatrix}[-1\ 0\ 1]$ (a vertical smoothing times a horizontal difference) and its transpose $G_y$; the edge strength is $\sqrt{G_x^2 + G_y^2}$.
- **Laplacian** $\begin{bmatrix}0 & 1 & 0\\1 & -4 & 1\\0 & 1 & 0\end{bmatrix}$ responds to curvature; subtracting a fraction of it sharpens (unsharp masking does similarly with a blur).

## Spatial sampling

A sensor samples space at one sample per pixel, so spatial frequencies above 0.5 cycles per pixel alias: a fine stripe pattern at u cycles per pixel appears at |u − round(u)|, producing **moiré**. Cameras put optical low-pass filters in front of the sensor, and shrinking an image by 2 needs a lowpass at 0.25 cycles per pixel first, exactly as decimation does in 1D.
:::

::: example
## A 31 × 31 filter is applied to a 1024 × 1024 image. Compare direct convolution with 2D FFT convolution.

::: solution
1. **Direct.** 961 multiplications per pixel, about $10^9$ in all.
2. **One FFT.** A 1024 × 1024 FFT takes about $1024^2 \times 10$ complex multiplications, 42 million real ones.
3. **The whole convolution.** Forward and inverse plus a pointwise product of 4 per pixel come to about 88 million, eleven times fewer. Zero padding against wraparound adds a little.
4. **The kernel.** The kernel's own FFT is computed once and reused.

**Answer:** about $10^9$ multiplications directly against about 88 million by FFT, eleven times fewer.
:::
:::

::: example
## A vertical edge: the 3 × 3 neighborhood's left column is 10, middle 50 and right 90. What do the Sobel operators give?

::: solution
1. **$G_x$.** It weights the right column +1, +2, +1 and the left −1, −2, −1:
   $$4 \times 90 - 4 \times 10 = 320$$
2. **$G_y$.** It compares the top and bottom rows, which are equal: 0.
3. **Strength and direction.** The edge strength is 320 and its direction horizontal (across the edge).
4. **Why 1–2–1.** The 1–2–1 weighting smooths along the edge, so the detector is less sensitive to noise than a plain difference.

**Answer:** $G_x$ = 320 and $G_y$ = 0: an edge of strength 320 pointing horizontally, across the edge.
:::
:::

::: example
## A fabric pattern of 0.7 cycles per pixel is photographed without an optical low-pass filter. What pattern appears?

::: solution
1. **Alias.**
   $$|0.7 - 1| = 0.3$$
   cycles per pixel.
2. **What appears.** A coarse stripe pattern that isn't in the fabric at all, the moiré seen on fine shirts on television.
3. **Why it stays.** Once sampled it can't be removed, since 0.3 cycles per pixel is a perfectly valid frequency.

**Answer:** a moiré stripe pattern at 0.3 cycles per pixel.
:::
:::

::: check
kind: parts
given: K = 5 | 9 | 15; W = 1280 | 1920 | 3840; H = 720 | 1080 | 2160; f = 30 | 60

## A separable K = {K} kernel filters {W} × {H} video at {f} frames per second.

::: part
answer: W*H*f*K^2/1e9
unit: G/s
tolerance: 0.5%

### How many billion multiplications a second does direct filtering need?

::: misses
- [any] $K^2$ per pixel.
:::
:::

::: part
answer: W*H*f*2*K/1e9
unit: G/s
tolerance: 0.5%

### And separable filtering?

::: misses
- [any] 2K per pixel.
:::
:::
:::

::: check
kind: parts
given: N = 256 | 1024 | 4096

## An N × N image with N = {N} is transformed by a separable radix-2 2D FFT.

::: part
answer: N^2*log(N)/log(2)
unit: multiplications
tolerance: 0.5%

### About how many complex multiplications does it take?

::: misses
- [N^2*log(N^2)/log(2)] Each of the 2N one-dimensional FFTs costs $\frac N2\log_2N$: $N^2\log_2N$ in total.
- [any] $2N \cdot \frac N2\log_2N$.
:::
:::

::: part
answer: N^2*log(N)/log(2)/N^2
unit: multiplications
tolerance: 0.5%

### How many is that per pixel?

::: misses
- [any] $\log_2N$.
:::
:::
:::

::: check
kind: parts
given: c = 50 | 84 | 120

## An arbitrary kernel can be applied by FFT at about {c} multiplications per pixel.

::: part
answer: sqrt(c)
tolerance: 0.5%

### Above what kernel size K is the FFT cheaper than direct convolution?

::: misses
- [any] Where $K^2 = c$.
:::
:::

::: part
answer: c/2
tolerance: 0.5%

### Above what K is it cheaper than separable filtering?

::: misses
- [any] Where 2K = c.
:::
:::
:::

::: check
kind: parts
given: u = 0.6 | 0.7 | 0.85 | 1.2

## A pattern of {u} cycles per pixel is sampled by a sensor without an optical low-pass filter.

::: part
answer: abs(u - round(u))
tolerance: 0.5%

### At what spatial frequency does it appear, in cycles per pixel?

::: misses
- [u - 0.5] Aliases reflect about multiples of one cycle per pixel: |u − round(u)|.
- [any] $|u - \text{round}(u)|$.
:::
:::
:::

::: check
kind: parts
given: a = 0 | 20; m = 40 | 60; b = 100 | 150

## A 3 × 3 neighborhood has every left-column pixel {a}, middle {m}, right {b}.

::: part
answer: 4*(b - a)
tolerance: 0.5%

### What does the Sobel $G_x$ give?

::: misses
- [b - a] The 1–2–1 column weights sum to 4.
- [any] $(1 + 2 + 1)(b - a)$.
:::
:::

::: part
answer: 0
tolerance: 0

### What does $G_y$ give?

::: misses
- [any] Top and bottom rows are equal.
:::
:::
:::

::: check
kind: parts
given: W = 1024 | 4000; H = 768 | 3000

## A {W} × {H} image is shrunk by 2 in each direction.

::: part
answer: 0.25
tolerance: 0.5%

### Below what spatial frequency, in cycles per original pixel, must the lowpass pass?

::: misses
- [0.5] That's the original's Nyquist; the new one is half of it.
- [any] Half the original Nyquist frequency.
:::
:::

::: part
answer: W*H/4
unit: pixels
tolerance: 0.5%

### How many pixels does the result have?

::: misses
- [any] A quarter.
:::
:::
:::

::: check
kind: choice

## Why can a Gaussian blur be run on 4K video in real time when an arbitrary 15 × 15 filter struggles?

- [ ] Gaussians have fewer nonzero taps
- [x] A Gaussian kernel is separable, the outer product of a 1D Gaussian with itself, so it filters rows then columns at 2K = 30 multiplications per pixel instead of K² = 225
- [ ] Gaussians need no multiplications
- [ ] Video hardware only supports Gaussians

::: misses
- [1] A sampled Gaussian has every tap nonzero; separability is what saves the work.
- [3] Each pass still multiplies.
- [4] Hardware runs arbitrary kernels; they're just more expensive.
:::
:::

::: check
kind: derivation
vars: K = 1..101, N = 2..10000, f = 1..1000

## A K × K kernel filters N × N images at f images per second.

::: step
answer: K^2*N^2*f

### How many multiplications a second does direct filtering need?
:::

::: step
answer: 2*K*N^2*f

### If the kernel is separable?
:::

::: step
answer: K/2

### By what factor is separable filtering cheaper?
:::

::: right
Right. The saving grows with K: a 31 × 31 separable blur is 15.5 times cheaper.
:::
:::

::: check
kind: python

## Write `conv2d(img, ker)`: the "valid" 2D convolution (no padding; output smaller by K − 1 each way) of nested lists, and `separable(img, col, row)`: the same result for the kernel col ⊗ row computed as a row pass then a column pass.

```python starter
def conv2d(img, ker):
    return img

def separable(img, col, row):
    return img
```

```python solution
def conv2d(img, ker):
    K, L = len(ker), len(ker[0])
    M, N = len(img), len(img[0])
    return [[sum(ker[k][l] * img[m + K - 1 - k][n + L - 1 - l] for k in range(K) for l in range(L))
             for n in range(N - L + 1)] for m in range(M - K + 1)]

def separable(img, col, row):
    L, K = len(row), len(col)
    rows = [[sum(row[l] * r[n + L - 1 - l] for l in range(L)) for n in range(len(r) - L + 1)] for r in img]
    M = len(rows)
    return [[sum(col[k] * rows[m + K - 1 - k][n] for k in range(K)) for n in range(len(rows[0]))] for m in range(M - K + 1)]
```

```python tests
import random
r = random.Random(4)
img = [[r.randint(0, 255) for _ in range(12)] for _ in range(10)]
col, row = [1, 2, 1], [-1, 0, 1]
ker = [[c * w for w in row] for c in col]
assert conv2d(img, ker) == separable(img, col, row), "Sobel as one 3 × 3 pass equals a row pass then a column pass."
edge = [[10, 50, 90]] * 3
g = conv2d(edge, ker)
assert abs(g[0][0]) == 320, "The worked example: a vertical edge gives |Gx| = 320."
```

::: right
Right. Convolution flips the kernel, so the sign of $G_x$ depends on convention; the magnitude doesn't.
:::
:::

::: explain
## Why does a camera need an optical low-pass filter in front of its sensor, rather than fixing aliasing in software afterward?

::: model
The sensor samples the image at one value per pixel, and any detail finer than half a cycle per pixel folds back to a lower spatial frequency in the samples. Once that has happened, the false coarse pattern is indistinguishable from real image content at that frequency, so no processing of the samples can tell which is which or remove it. The only cure is to remove the too-fine detail before sampling, which in a camera means slightly blurring the light reaching the sensor, exactly as an analog anti-aliasing filter precedes an ADC. Cameras with very high pixel counts sometimes omit it, accepting occasional moiré for extra sharpness.
:::
:::

::: practice
::: check
given: K = 3 | 5 | 7 | 11 | 15 | 21
answer: K/2
tolerance: 0.5%

## How much cheaper is separable filtering for K = {K}?

::: misses
- [any] $K^2/2K$.
:::
:::

::: check
given: u = 0.55 | 0.6 | 0.7 | 0.8 | 0.9 | 1.2 | 1.65
answer: abs(u - round(u))
tolerance: 0.5%

## Alias of {u} cycles per pixel?

::: misses
- [any] |u − round(u)|.
:::
:::

::: check
given: a = 5 | 30; b = 80 | 200
answer: 4*(b - a)
tolerance: 0.5%

## Sobel Gx across a vertical edge from {a} to {b}?

::: misses
- [any] 4(b − a).
:::
:::
:::
