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).
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 .
Edges: high-pass and derivatives
Edge detectors approximate derivatives, which multiply the spectrum by : they amplify high frequencies. The Sobel kernel combines a derivative in one direction with smoothing in the other:
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: . In frequency, the response is , which boosts high frequencies by up to . The name comes from darkroom photography, where a blurred ("unsharp") negative was used as a mask.
In software
scipy.ndimage.gaussian_filter,sobel,convolve; OpenCVGaussianBlur,filter2D(switches to DFT for large kernels); PillowImageFilter.UnsharpMask.- Separable kernels (Gaussian, box) are applied as two 1-D passes: instead of per pixel.
Exercises
Exercise 1: Gaussian in frequency
A Gaussian blur with standard deviation pixels has frequency response . At what frequency does its gain fall to 1/2 for ?
Answer
About 0.094 cycles per pixel.
Solution
gives , 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 pixels and , compute the sharpening gain at cycles per pixel.
Answer
About 1.0, 1.10, 1.36, 1.94, 2.0.
Solution
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…
- boosting high frequencies
- attenuating high frequencies
- shifting the spectrum
- taking the phase
Why does a sharp cutoff in the frequency domain make images ring?
- the FFT is inaccurate
- its kernel is sinc-like, with negative lobes (the Gibbs phenomenon)
- images are periodic
- it removes DC
Edge detectors such as Sobel act as…
- low-pass filters
- derivative (high-pass) filters
- notch filters
- all-pass filters