---
title: Image processing lab
heading: The 2D DFT by rows and columns, spatial aliasing, DCT block compression and separable Gaussian blur, in Python
eyebrow: S7 · Lesson 49 · Image processing lab
xp: 60
---

::: hook
Lessons 28 and 45 made claims about images that are easy to state and worth seeing: the 2D DFT is just 1D DFTs along rows and then columns; a pattern finer than half a cycle per pixel shows up somewhere else entirely; an 8 × 8 block of a smooth image survives being cut to a handful of DCT coefficients; and a Gaussian blur filtered as rows then columns is the same as the full 2D convolution. This lab checks each on small arrays.
:::

::: play
- The curve is the spatial frequency a sampled pattern appears at, against its true frequency, both in cycles per pixel: $|u - \text{round}(u)|$.
- Below 0.5 cycles per pixel nothing changes; above it the apparent frequency folds back down, reaching zero at every whole cycle per pixel, where the pattern looks perfectly flat.
- The lab's DFT finds exactly this folded frequency.
:::

```sim plot
view: graph
x: u = 0..2
y: a = 0..0.5
plot: abs(u - round(u)) | label: apparent frequency
```

::: predict
## A stripe pattern at 53/64 cycles per pixel is sampled and analyzed with a 64-point DFT. At what frequency does its peak appear?

- [ ] 53/64 cycles per pixel
- [ ] 0.5 cycles per pixel
- [x] 11/64 cycles per pixel, about 0.17
- [ ] It appears in no bin

::: reveal
53/64 exceeds 0.5, so it aliases to 1 − 53/64 = 11/64. The DFT has no way to know the pattern was finer; once sampled, 11/64 cycles per pixel is what the pixels contain.
:::
:::

::: nameit
## What the lab computes

- **2D DFT**: a 1D DFT of every row, then of every column of the result, compared with the direct double sum $\sum_m\sum_nx[m, n]e^{-j2\pi(km/M + ln/N)}$.
- **Aliasing**: sample cos(2πun) for n = 0 to N − 1 and find the strongest DFT bin among 0 to N/2.
- **Block compression**: the orthonormal 8 × 8 DCT, $X[k, l] = c_kc_l\sum_m\sum_nx[m, n]\cos\frac{\pi k(2m + 1)}{16}\cos\frac{\pi l(2n + 1)}{16}$; keep the k largest coefficients, invert, and measure PSNR.
- **Gaussian blur**: $g[i] \propto e^{-i^2/2\sigma^2}$ normalized to sum 1; the 2D kernel is g ⊗ g.
:::

::: check
kind: python

## Write `dft1(x)` and `dft2(img)`: the 2D DFT of a list of rows, computed as row DFTs then column DFTs.

```python starter
def dft1(x):
    return list(x)

def dft2(img):
    return img
```

```python solution
import cmath, math

def dft1(x):
    N = len(x)
    return [sum(x[n] * cmath.exp(-2j * math.pi * k * n / N) for n in range(N)) for k in range(N)]

def dft2(img):
    rows = [dft1(r) for r in img]
    M, N = len(rows), len(rows[0])
    cols = [dft1([rows[m][n] for m in range(M)]) for n in range(N)]
    return [[cols[n][m] for n in range(N)] for m in range(M)]
```

```python tests
import cmath, math
img = [[1, 2, 3, 4], [2, 0, 1, 5], [7, 1, 0, 2], [3, 3, 3, 1]]
X = dft2(img)
direct = lambda k, l: sum(img[m][n] * cmath.exp(-2j * math.pi * (k * m / 4 + l * n / 4)) for m in range(4) for n in range(4))
assert max(abs(X[k][l] - direct(k, l)) for k in range(4) for l in range(4)) < 1e-12, "Rows then columns equals the double sum."
assert abs(X[0][0] - 38) < 1e-12, "The DC term is the sum of the pixels."
```

::: right
Right. With FFTs in each direction this is the $N^2\log_2N$ algorithm.
:::
:::

::: check
kind: python

## Write `alias_freq(u, N=64)`: sample cos(2πun) for N samples and return the frequency (bin/N, cycles per pixel) of the strongest DFT bin between 0 and N/2.

```python starter
def alias_freq(u, N=64):
    return u
```

```python solution
import cmath, math

def alias_freq(u, N=64):
    x = [math.cos(2 * math.pi * u * n) for n in range(N)]
    X = [abs(sum(x[n] * cmath.exp(-2j * math.pi * k * n / N) for n in range(N))) for k in range(N // 2 + 1)]
    return max(range(N // 2 + 1), key=lambda k: X[k]) / N
```

```python tests
assert alias_freq(53 / 64) == 11 / 64, "53/64 cycles per pixel shows up at 11/64."
assert abs(alias_freq(0.7) - 0.3) <= 1 / 64, "0.7 aliases to 0.3, to the nearest bin."
assert alias_freq(10 / 64) == 10 / 64, "Below Nyquist, nothing changes."
```

::: right
Right. The DFT reports the pixels' content faithfully; the error happened at sampling.
:::
:::

::: check
kind: python

## Write `dct2(b)`, `idct2(X)` (orthonormal, N × N) and `psnr_keep(b, k)`: keep the k largest-magnitude DCT coefficients of block b, invert, and return the PSNR against b with a 255 peak.

```python starter
def dct2(b):
    return b

def idct2(X):
    return X

def psnr_keep(b, k):
    return 0.0
```

```python solution
import math

def _c(k, N):
    return math.sqrt(1 / N) if k == 0 else math.sqrt(2 / N)

def dct2(b):
    N = len(b)
    return [[_c(k, N) * _c(l, N) * sum(b[m][n] * math.cos(math.pi * k * (2 * m + 1) / (2 * N)) * math.cos(math.pi * l * (2 * n + 1) / (2 * N))
             for m in range(N) for n in range(N)) for l in range(N)] for k in range(N)]

def idct2(X):
    N = len(X)
    return [[sum(_c(k, N) * _c(l, N) * X[k][l] * math.cos(math.pi * k * (2 * m + 1) / (2 * N)) * math.cos(math.pi * l * (2 * n + 1) / (2 * N))
             for k in range(N) for l in range(N)) for n in range(N)] for m in range(N)]

def psnr_keep(b, k):
    N = len(b)
    X = dct2(b)
    big = sorted(((abs(X[i][j]), i, j) for i in range(N) for j in range(N)), reverse=True)[:k]
    Y = [[0.0] * N for _ in range(N)]
    for _, i, j in big:
        Y[i][j] = X[i][j]
    R = idct2(Y)
    mse = sum((R[i][j] - b[i][j]) ** 2 for i in range(N) for j in range(N)) / (N * N)
    return 10 * math.log10(255 ** 2 / mse)
```

```python tests
blk = [[100 + 10 * m + 5 * n + 0.5 * m * n for n in range(8)] for m in range(8)]
assert abs(psnr_keep(blk, 3) - 35.51) < 0.01, "Three coefficients: 35.5 dB."
assert abs(psnr_keep(blk, 6) - 47.53) < 0.01, "Six: 47.5 dB."
X = dct2(blk)
assert max(abs(u - v) for r1, r2 in zip(idct2(X), blk) for u, v in zip(r1, r2)) < 1e-9, "The inverse recovers the block."
```

::: right
Right. A smooth block lives in its low-frequency corner; quantization tables exploit exactly that.
:::
:::

::: check
kind: python

## Write `gauss(K, sigma)`: a normalized 1D Gaussian of odd length K, `conv2d(img, ker)` ("valid" 2D convolution) and `blur_sep(img, g)`: rows then columns with g.

```python starter
def gauss(K, sigma):
    return [1.0 / K] * K

def conv2d(img, ker):
    return img

def blur_sep(img, g):
    return img
```

```python solution
import math

def gauss(K, sigma):
    c = (K - 1) // 2
    g = [math.exp(-(i - c) ** 2 / (2 * sigma ** 2)) for i in range(K)]
    s = sum(g)
    return [v / s for v in g]

def conv2d(img, ker):
    K, L = len(ker), len(ker[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(len(img[0]) - L + 1)] for m in range(len(img) - K + 1)]

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

```python tests
import random
g = gauss(5, 1.0)
assert abs(sum(g) - 1) < 1e-12 and abs(g[2] - 0.4026) < 1e-4, "Normalized, with 0.403 at the center."
r = random.Random(9)
img = [[r.randint(0, 255) for _ in range(12)] for _ in range(12)]
a = conv2d(img, [[u * v for v in g] for u in g])
b = blur_sep(img, g)
assert max(abs(u - v) for r1, r2 in zip(a, b) for u, v in zip(r1, r2)) < 1e-9, "Separable blur equals the 2D convolution."
flat = [[50] * 9 for _ in range(9)]
assert all(abs(v - 50) < 1e-9 for row in blur_sep(flat, g) for v in row), "A flat image stays flat."
```

::: right
Right. The 5 × 5 blur costs 25 multiplications per pixel directly and 10 separably.
:::
:::

::: explain
## Why can a smooth image block be rebuilt well from just a few DCT coefficients?

::: model
The DCT expresses the block as a weighted sum of two-dimensional cosine patterns of increasing frequency. A block whose brightness varies smoothly, as most regions of natural images do, is closely matched by a few low-frequency patterns: a constant, gentle gradients in each direction and a slight curvature. The coefficients of the high-frequency patterns, which describe fine detail and sharp edges, are small or zero. Keeping only the few large coefficients and discarding the rest therefore changes the pixels very little, which is what lets a compressor spend its bits on the coefficients that matter.
:::
:::
