TExcelTAD
Home › Fourier Analysis & Signals › Filtering Images

Filtering Images

Blurring, sharpening and edge detection are 2-D convolutions, and by the convolution theorem each is a multiplication of the image's spectrum by a 2-D frequency response. Low-pass filters blur, high-pass filters keep edges, and the choice of kernel shape decides whether the result rings. This lesson filters a small synthetic image both ways.

Blur: low-pass

A Gaussian kernel is the standard blur: its transform is again a Gaussian, so it attenuates high frequencies smoothly, without ringing. An "ideal" filter that cuts the spectrum sharply at a radius rings around edges (the 2-D Gibbs phenomenon).

python · try it yourself
import numpy as np

M = 64
img = np.zeros((M, M))
img[16:48, 16:48] = 1.0                                   # a white square on black

ky = np.fft.fftfreq(M)[:, None]
kx = np.fft.fftfreq(M)[None, :]
radius = np.hypot(kx, ky)                                  # in cycles per pixel

def apply(H):
    return np.real(np.fft.ifft2(np.fft.fft2(img) * H))

ideal = apply((radius < 0.08).astype(float))
sigma = 1.5                                                # Gaussian blur with sigma 1.5 pixels
gauss = apply(np.exp(-2 * (np.pi * sigma * radius) ** 2))

row = 32
print("original row:   ", np.round(img[row, 10:22], 2).tolist())
print("ideal low-pass: ", np.round(ideal[row, 10:22], 2).tolist())
print("Gaussian blur:  ", np.round(gauss[row, 10:22], 2).tolist())
print(f"overshoot: ideal {ideal.max():.3f}, Gaussian {gauss.max():.3f}; undershoot: ideal {ideal.min():.3f}, Gaussian {round(float(gauss.min()), 3) + 0.0:.3f}")
original row:    [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
ideal low-pass:  [-0.08, -0.07, -0.01, 0.09, 0.24, 0.43, 0.62, 0.81, 0.96, 1.06, 1.12, 1.13]
Gaussian blur:   [0.0, 0.0, 0.01, 0.04, 0.15, 0.37, 0.63, 0.85, 0.96, 0.99, 1.0, 1.0]
overshoot: ideal 1.173, Gaussian 1.000; undershoot: ideal -0.121, Gaussian 0.000

The ideal filter overshoots above 1 and below 0 near the edge (ringing); the Gaussian blur rises smoothly and stays within [0,1][0, 1].

Edges: high-pass and derivatives

Edge detectors approximate derivatives, which multiply the spectrum by 2πiu2\pi i u: they amplify high frequencies. The Sobel kernel combines a derivative in one direction with smoothing in the other:

python · try it yourself
import numpy as np

img = np.zeros((10, 10))
img[3:7, 3:7] = 1.0
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])

def conv2_same(image, k):                                  # direct 2-D convolution, zero padding
    kh, kw = k.shape
    pad = np.pad(image, ((kh // 2,), (kw // 2,)))
    flipped = k[::-1, ::-1]
    out = np.zeros_like(image)
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            out[i, j] = np.sum(pad[i:i + kh, j:j + kw] * flipped)
    return out

gx = conv2_same(img, sobel_x)
print("row 5 of the image:   ", img[5].astype(int).tolist())
print("row 5 of Sobel x:     ", (gx[5] + 0.0).astype(int).tolist())

H = np.fft.fft2(sobel_x, (64, 64))
print("Sobel x gain at frequency 0: ", round(abs(H[0, 0]), 4), "  at (0, 16):", round(abs(H[0, 16]), 4), "  at (0, 32):", round(abs(H[0, 32]), 4))
row 5 of the image:    [0, 0, 0, 1, 1, 1, 1, 0, 0, 0]
row 5 of Sobel x:      [0, 0, -4, -4, 0, 0, 4, 4, 0, 0]
Sobel x gain at frequency 0:  0.0   at (0, 16): 8.0   at (0, 32): 0.0

The response is large at the left and right edges of the square (with opposite signs) and zero in flat regions; in frequency, the Sobel filter has zero gain at DC and is largest at mid frequencies.

Unsharp masking

Sharpening adds back a scaled high-pass: sharp=img+λ(img−blur(img))\text{sharp} = \text{img} + \lambda(\text{img} - \text{blur}(\text{img})). In frequency, the response is 1+λ(1−G)1 + \lambda(1 - G), which boosts high frequencies by up to 1+λ1 + \lambda. The name comes from darkroom photography, where a blurred ("unsharp") negative was used as a mask.

In software

  • scipy.ndimage.gaussian_filter, sobel, convolve; OpenCV GaussianBlur, filter2D (switches to DFT for large kernels); Pillow ImageFilter.UnsharpMask.
  • Separable kernels (Gaussian, box) are applied as two 1-D passes: O(k)O(k) instead of O(k2)O(k^2) per pixel.

Exercises

Exercise 1: Gaussian in frequency

A Gaussian blur with standard deviation σ\sigma pixels has frequency response e−2π2σ2f2e^{-2\pi^2\sigma^2 f^2}. At what frequency does its gain fall to 1/2 for σ=2\sigma = 2?

Answer

About 0.094 cycles per pixel.

Solution

2π2⋅4⋅f2=ln⁡22\pi^2 \cdot 4 \cdot f^2 = \ln 2 gives f=ln⁡2/(8π2)≈0.0937f = \sqrt{\ln 2/(8\pi^2)} \approx 0.0937, so details smaller than about 10 pixels per cycle are halved or worse.

Exercise 2: Why no ringing?

Why does the Gaussian blur never overshoot, while the ideal low-pass does?

Answer

The Gaussian kernel is nonnegative, so the output is a weighted average of the input.

Solution

A kernel with nonnegative weights summing to 1 produces outputs between the minimum and maximum of the input. The ideal low-pass kernel is a 2-D sinc-like function with negative lobes, which create overshoots.

Exercise 3: Unsharp masking gain (code)

For a Gaussian blur with σ=1.5\sigma = 1.5 pixels and λ=1\lambda = 1, compute the sharpening gain 1+λ(1−G(f))1 + \lambda(1 - G(f)) at f=0,0.05,0.1,0.25,0.5f = 0, 0.05, 0.1, 0.25, 0.5 cycles per pixel.

Answer

About 1.0, 1.10, 1.36, 1.94, 2.0.

Solution
python · try it yourself
import numpy as np
sigma, lam = 1.5, 1.0
for f in (0, 0.05, 0.1, 0.25, 0.5):
    G = np.exp(-2 * (np.pi * sigma * f) ** 2)
    print(f, round(1 + lam * (1 - G), 2))
0 1.0
0.05 1.11
0.1 1.36
0.25 1.94
0.5 2.0

Test yourself

Blurring an image corresponds in frequency to…

  1. boosting high frequencies
  2. attenuating high frequencies
  3. shifting the spectrum
  4. taking the phase

Why does a sharp cutoff in the frequency domain make images ring?

  1. the FFT is inaccurate
  2. its kernel is sinc-like, with negative lobes (the Gibbs phenomenon)
  3. images are periodic
  4. it removes DC

Edge detectors such as Sobel act as…

  1. low-pass filters
  2. derivative (high-pass) filters
  3. notch filters
  4. all-pass filters