A convolution is a linear operator of the form
In a discrete space, the integral turns into a sum
Convolution appear in temporal and spatial signal and image processing (smoothing, blurring, edge detection), in probability (sums of independent random variables), in polynomial multiplication, in finite difference formulas, and in the solution operators of linear PDEs with constant coefficients.
import timeit
import numpy as np
import scipy.linalg as la
from scipy import ndimage, signal
from scipy.fft import dct, dctn, fft, fft2, fftfreq, fftshift, idct, idctn, ifft, ifft2, irfft, rfft, rfftfreq
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)Discrete convolution¶
Take two finite sequences and , and treat them as zero outside those ranges. Then can only be nonzero for , so the full convolution has length .
Convolution can be computing using np.convolve.
A first example is the moving average. Convolving with replaces each value by the average of neighboring values, which smooths out noise.
t = np.linspace(0, 1, 200)
data = np.cos(2 * np.pi * t) + 0.3 * rng.standard_normal(t.size)
K = 10
g = np.ones(K) / K # moving average over K points
smooth = np.convolve(data, g, mode='same')
plt.figure(figsize=(8, 3))
plt.plot(t, data, '.', ms=3, label='data')
plt.plot(t, smooth, label=f'moving average, $K = {K}$')
plt.xlabel('$t$')
plt.legend()
plt.show()
for mode in ['full', 'same', 'valid']:
print(f"mode = {mode!r:8} output length {np.convolve(data, g, mode=mode).size}")The mode argument says which part of the full convolution to return: 'full' gives all values, 'same' the middle of them, aligned with the input, and 'valid' only the values for which fits entirely inside the data. Near the ends, 'same' averages in the zeros that are assumed outside the data, which is why the smoothed curve droops at both ends. What to assume outside the data is a modeling decision, and we will see other choices (periodic, mirrored) below.
Polynomial multiplication¶
For two polynomials
then the coefficient of in collects the products with , which is . So multiplying polynomials is the same as convolving their coefficients. For example, :
print(np.convolve([1, 2], [3, 4, 5]))Sums of random variables¶
If and are independent random variables with integer values, then
so the distribution of is the convolution of the two distributions. The same holds for continuous random variables: if and have probability density functions and , then has the density .
A fair die has the distribution on landing in . Convolving it with itself gives the triangle for the sum of two dice, and convolving copies gives the distribution of the sum of dice. By the central limit theorem, this approaches a normal distribution with mean and variance (dashed).
die = np.ones(6) / 6 # P(1), ..., P(6)
dist = die
n = 1
fig, axes = plt.subplots(1, 4, figsize=(14, 3))
for ax, n_plot in zip(axes, [1, 2, 3, 10]):
while n < n_plot:
dist = np.convolve(dist, die)
n += 1
values = np.arange(n, 6 * n + 1) # the sum of n dice is between n and 6n
mean, var = 3.5 * n, 35 / 12 * n
s = np.linspace(n, 6 * n, 300)
ax.bar(values, dist, width=0.8)
ax.plot(s, np.exp(-(s - mean)**2 / (2 * var)) / np.sqrt(2 * np.pi * var), 'k--')
ax.set_title('one die' if n == 1 else f'sum of {n} dice')
plt.tight_layout()
plt.show()Toeplitz and circulant matrices¶
Convolution with a fixed is linear in , so it is a matrix-vector product with the entries . These only depend on , so they are constant along each diagonal. A matrix like this is called a Toeplitz matrix:
A Toeplitz matrix is determined by its first column and its first row, which is how scipy.linalg.toeplitz takes it.
c = np.arange(0, -4, -1) # first column
r = np.arange(4) # first row
la.toeplitz(c, r)For the full convolution of a signal of length with a sequence of length , the matrix is an Toeplitz matrix whose columns are shifted copies of . scipy.linalg.convolution_matrix builds it.
g = np.array([1.0, 2.0, 3.0])
f = rng.standard_normal(5)
G = la.convolution_matrix(g, len(f))
print(G)
print(np.allclose(G @ f, np.convolve(g, f)))On a periodic domain, for a signal that repeats with period or for values on a ring of grid points, the shifts wrap around. The circular convolution
is represented by a circulant matrix. This is a Toeplitz matrix with , so each column is the previous one shifted down by one entry, with the last entry wrapping around to the top. scipy.linalg.circulant takes the first column.
c = np.arange(4)
la.circulant(c)Both Toeplitz and circulant matrices have special solve functions in scipy.linalg. solve_toeplitz takes operations instead of the of Gaussian elimination, and solve_circulant takes operations, for reasons we will see shortly.
N = 2000
c = rng.standard_normal(N)
r = rng.standard_normal(N)
A = la.toeplitz(c, r)
x = rng.standard_normal(N)
print("standard solve")
%time y1 = la.solve(A, x)
print("\ntoeplitz solve")
%time y2 = la.solve_toeplitz((c, r), x)
print(f"\nrelative difference {la.norm(y1 - y2) / la.norm(y1):.1e}")A = la.circulant(c)
print("standard solve")
%time y1 = la.solve(A, x)
print("\ncirculant solve")
%time y2 = la.solve_circulant(c, x)
print(f"\nrelative difference {la.norm(y1 - y2) / la.norm(y1):.1e}")The discrete Fourier transform¶
A Fourier transform takes functions back and forth between the time (or space) domain and the frequency domain,
The discrete Fourier transform (DFT) does the same for a signal given as a vector :
The inverse DFT recovers the signal,
The inverse formula writes as a combination of the discrete waves , and says how much of wave the signal contains. Computing the DFT from its definition takes operations, but the fast Fourier transform (FFT) computes it in operations. SciPy provides it as scipy.fft.fft, with the inverse ifft.
Where the factor goes is a convention, and books differ. SciPy (like NumPy and MATLAB) puts it in the inverse, as above. The norm argument changes this: norm='ortho' puts in both directions, which makes the transform unitary, and norm='forward' puts in the forward transform.
Frequencies¶
The wave does not change if is replaced by , so on the grid, frequency is the same as frequency . The coefficients with are best read as the negative frequencies . fftfreq(N, d) returns the frequency of each coefficient in this order, in cycles per unit of if the samples are a distance d apart, and fftshift reorders an array of coefficients so that frequency zero is in the middle.
Here is a signal made of two sines, sampled at 100 points on . With d = 1/N, the frequencies come out as integers: the number of periods in the interval.
N = 100
x = 2 * np.pi * np.arange(N) / N # leave out x = 2 pi, the same point as x = 0
f = np.sin(4 * x) + 0.5 * np.sin(8 * x)
fhat = fft(f)
k = fftfreq(N, d=1/N) # 0, 1, ..., 49, -50, ..., -1
fig, ax = plt.subplots(1, 3, figsize=(14, 3.5))
ax[0].plot(x, f)
ax[0].set_xlabel('$x$')
ax[0].set_title('signal')
ax[1].plot(fftshift(k), fftshift(fhat.real), 'o-', ms=3)
ax[1].set_title(r'real part of $\hat f_k$')
ax[2].plot(fftshift(k), fftshift(fhat.imag), 'o-', ms=3)
ax[2].set_title(r'imaginary part of $\hat f_k$')
for a in ax[1:]:
a.set_xlim(-15, 15)
a.set_ylim(-60, 60)
a.set_xlabel('frequency $k$')
plt.show()The coefficients vanish except at and , and they are purely imaginary: , so . This illustrates a general rule. Taking the complex conjugate of the definition shows that a real signal has
so the real part of is even in and the imaginary part is odd, and the negative frequencies carry no information that the positive ones do not. rfft returns only the coefficients , in about half the time and memory, and irfft inverts it.
ifft returns complex numbers even when the result should be real; their imaginary parts are rounding errors, which we discard with .real.
print("rfft is the first half of fft:", np.allclose(rfft(f), fhat[:N // 2 + 1]))
print("irfft inverts rfft: ", np.allclose(irfft(rfft(f), n=N), f))
print("ifft inverts fft: ", np.allclose(ifft(fhat).real, f))
print("largest imaginary part: ", np.abs(ifft(fhat).imag).max())Leakage¶
The DFT treats the signal as one period of a periodic signal. If the samples do not cover a whole number of periods, the periodic extension jumps where the end of the signal meets the beginning of the next copy, and the coefficients spread out over all frequencies instead of sitting at a few. This is called leakage. Compare with on the same grid:
fig, ax = plt.subplots(1, 2, figsize=(13, 3.5))
for freq in [4, 4.5]:
v = np.cos(freq * x)
ax[0].plot(x, v, label=f'$\\cos {freq}x$')
ax[1].semilogy(fftshift(k), fftshift(np.abs(fft(v))), 'o-', ms=3, label=f'$\\cos {freq}x$')
ax[0].set_xlabel('$x$')
ax[0].set_title('two periods of the periodic extension')
ax[1].set_ylim(1e-15, 1e3)
ax[1].set_xlabel('frequency $k$')
ax[1].set_title(r'$|\hat f_k|$')
for a in ax:
a.legend()
plt.show()Away from , the coefficients of are zero up to rounding errors, while those of , whose periodic extension jumps from -1 back to 1 at , decay only like . This slow decay is the signature of a jump. The discrete cosine transform at the end of this section avoids the jump. When analyzing measured signals, one often multiplies by a window that goes smoothly to zero at both ends before taking the FFT (see scipy.signal.windows), which trades a little resolution in frequency for much less leakage.
Example: finding frequencies in noisy data¶
The Fourier transform can reveal structure that is hard to see in raw data. Suppose we record one second of a signal at 1000 samples per second, made of a 50 Hz and a 120 Hz oscillation buried in noise. With the sample spacing d = 1/fs, rfftfreq gives the frequencies in Hz.
fs = 1000 # samples per second
t = np.arange(fs) / fs # one second
y = 0.7 * np.sin(2 * np.pi * 50 * t) + np.sin(2 * np.pi * 120 * t) + 2 * rng.standard_normal(fs)
freqs = rfftfreq(fs, d=1 / fs)
power = np.abs(rfft(y))**2 / fs
fig, ax = plt.subplots(1, 2, figsize=(13, 3.5))
ax[0].plot(t[:200], y[:200])
ax[0].set_xlabel('time (s)')
ax[0].set_title('the first 0.2 seconds of the signal')
ax[1].plot(freqs, power)
ax[1].set_xlabel('frequency (Hz)')
ax[1].set_title(r'power spectrum $|\hat y_k|^2 / N$')
plt.show()In the frequency domain, the noise spreads its energy evenly over all frequencies, while each oscillation puts all of its energy into a single frequency, so the two peaks stand far above the noise. That the DFT preserves energy, up to the factor , is Parseval’s theorem,
print(np.sum(y**2), np.sum(np.abs(fft(y))**2) / fs)The convolution theorem¶
Fourier transforms have many useful properties. The most important one for computation is the convolution theorem, where the Fourier transform of a convolution of two functions and is the product of their individual Fourier transforms:
In the discrete setting, circular convolution becomes pointwise multiplication in the frequency domain:
To see why, write , so that , and note that only depends on . Substituting ,
with all sums over . Exponentials turn shifts into multiplication: : This is how to relate Fourier transform to convolution.
Linear convolution with the FFT¶
The cost of the convolution grows like and that of the FFT like , so for large the FFT speeds up convolutions.
The convolution theorem is about circular convolution. To compute the ordinary (linear) convolution of of length and of length , pad both with zeros to a length . Then the circular convolution of the padded vectors never wraps around onto a nonzero entry, and its first entries are the linear convolution. Without padding, the end of the result wraps around and is added to the beginning.
f = rng.standard_normal(50)
g = np.exp(-np.linspace(-3, 3, 31)**2) # a Gaussian bump
full = np.convolve(f, g) # length 50 + 31 - 1 = 80
L = len(f) + len(g) - 1
padded = irfft(rfft(f, L) * rfft(g, L), L) # rfft(f, L) pads f with zeros to length L
plt.figure(figsize=(8, 3))
plt.plot(full, lw=6, alpha=0.5, label='np.convolve')
plt.plot(padded, label='FFT, padded to length 80')
plt.legend()
plt.show()
print("padded FFT vs np.convolve:", np.max(np.abs(padded - full)))scipy.signal.fftconvolve does the padding for you, and scipy.signal.convolve chooses between the direct sum and the FFT using an estimate of which is faster. The direct sum takes operations and the FFT , so the FFT wins unless one of the two sequences is short:
f = rng.standard_normal(100_000)
for K in [5, 50, 500, 5000]:
g = rng.standard_normal(K)
t_direct = min(timeit.repeat(lambda: np.convolve(f, g), number=3, repeat=3)) / 3
t_fft = min(timeit.repeat(lambda: signal.fftconvolve(f, g), number=3, repeat=3)) / 3
print(f"K = {K:5d}: direct {1e3 * t_direct:6.2f} ms, FFT {1e3 * t_fft:5.2f} ms, "
f"signal.convolve picks {signal.choose_conv_method(f, g)!r}")Filtering¶
Multiplying by a function of the frequency is called filtering. By the convolution theorem, every filter is a (circular) convolution, and every convolution is a filter.
A low-pass filter keeps the low frequencies and removes the high ones, which smooths the signal. A Gaussian is a good choice: convolving with the normalized Gaussian of width multiplies the coefficient of the wave by , which is again a Gaussian, with no oscillating tail. This is also what the heat equation does to its initial data; see Spectral Methods.
Here we smooth a noisy periodic signal. In the frequency domain the signal sits at a few low frequencies, while the noise is spread evenly over all of them, and the filter removes the noise at high frequencies.
N = 512
x = 2 * np.pi * np.arange(N) / N
clean = np.sin(x) + 0.5 * np.cos(3 * x)
noisy = clean + 0.3 * rng.standard_normal(N)
sigma = 0.1 # width of the Gaussian, in units of x
k = fftfreq(N, d=1 / N) # integer wavenumbers: waves e^{ikx}
gauss_hat = np.exp(-(sigma * k)**2 / 2)
smoothed = ifft(gauss_hat * fft(noisy)).real
fig, ax = plt.subplots(1, 2, figsize=(13, 3.5))
ax[0].semilogy(fftshift(k), fftshift(np.abs(fft(noisy))), '.', ms=3, label='noisy signal')
ax[0].semilogy(fftshift(k), fftshift(np.abs(gauss_hat * fft(noisy))), '.', ms=3, label='filtered')
ax[0].set_ylim(1e-3, 1e3)
ax[0].set_xlabel('wavenumber $k$')
ax[0].set_title(r'$|\hat f_k|$')
ax[0].legend()
ax[1].plot(x, noisy, '.', ms=2, color='0.7', label='noisy')
ax[1].plot(x, smoothed, label='filtered')
ax[1].plot(x, clean, 'k--', lw=1, label='clean')
ax[1].set_xlabel('$x$')
ax[1].legend()
plt.show()The same result comes from convolving with the Gaussian directly in . scipy.ndimage.gaussian_filter1d does that, with mode='wrap' for a periodic signal and the width given in grid points:
h = 2 * np.pi / N
direct = ndimage.gaussian_filter1d(noisy, sigma / h, mode='wrap', truncate=8.0)
print(np.max(np.abs(direct - smoothed)))Deconvolution and ill-conditioning¶
Undoing a convolution is harder. Suppose we measure a blurred signal , where the blur is known (it might be the response of a measuring instrument), and want to recover . The circulant solve gives . But a blur is a low-pass filter, so is tiny at high frequencies, and dividing by it multiplies the noise there by a huge factor. The condition number measures exactly this amplification.
N = 256
n = np.arange(N)
x_true = (1.0 * ((n >= 40) & (n < 90)) + 0.7 * ((n >= 130) & (n < 140))
+ np.maximum(0, 1 - np.abs(n - 200) / 20))
width = 2.0 # of the blur, in grid points
dist = np.minimum(n, N - n) # distance from 0 around the ring
c = np.exp(-dist**2 / (2 * width**2))
c /= c.sum() # first column of the blurring matrix
c_hat = fft(c)
print(f"condition number of the blur: {np.abs(c_hat).max() / np.abs(c_hat).min():.1e}")
b = ifft(c_hat * fft(x_true)).real # c (*) x_true, circular convolution
b += 5e-3 * rng.standard_normal(N) # measurement noise
x_naive = ifft(fft(b) / c_hat).real
print(f"largest entry of the naive solution: {np.abs(x_naive).max():.1e}")The noise is only 10-3, but the naive solution is useless. The fix is to give up on the frequencies that the blur has destroyed. Tikhonov regularization chooses the that minimizes
for a parameter . By Parseval’s theorem this splits into a separate scalar problem for each frequency, with the solution
Where this is the naive , and where it is close to zero instead of huge. (In signal processing this is a form of the Wiener filter.)
def deconvolve_tikhonov(c, b, alpha):
"""
the x that minimizes ||c (*) x - b||^2 + alpha ||x||^2, where (*) is circular convolution
"""
c_hat = fft(c)
return ifft(np.conj(c_hat) * fft(b) / (np.abs(c_hat)**2 + alpha)).real
print(f"blurred data: rms error {np.sqrt(np.mean((b - x_true)**2)):.3f}\n")
for alpha in [1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7]:
err = np.sqrt(np.mean((deconvolve_tikhonov(c, b, alpha) - x_true)**2))
print(f"alpha = {alpha:.0e}: rms error {err:.3f}")fig, ax = plt.subplots(1, 3, figsize=(15, 3.5))
ax[0].plot(n, x_true, 'k--', lw=1, label='true')
ax[0].plot(n, b, label='blurred, with noise')
ax[0].set_title('measurement')
ax[1].plot(n, x_naive)
ax[1].set_title('naive deconvolution')
ax[2].plot(n, x_true, 'k--', lw=1, label='true')
ax[2].plot(n, deconvolve_tikhonov(c, b, 1e-2), label=r'Tikhonov, $\alpha = 10^{-3}$')
ax[2].set_title('regularized deconvolution')
for a in ax[[0, 2]]:
a.set_ylim(-0.2, 1.45)
a.legend(loc='upper center', ncol=2, fontsize=8)
plt.show()A large blurs the answer and a small one lets the noise back in. In between, around , the error is about a third smaller than that of the blurred data, and the edges are much sharper. The price is the Gibbs phenomenon.
No choice of recovers the true signal exactly, since the information at the frequencies where is below the noise level is gone. This is typical of inverse problems, and the same ideas used in image deblurring, seismic imaging, and medical imaging.
Higher dimensions¶
Everything above works in more dimensions, one dimension at a time. The DFT of an array is the DFT of every column followed by the DFT of every row, which SciPy provides as fft2 and ifft2 (and fftn for any number of dimensions). For an image, the time complexity is . Circular convolution of images becomes pointwise multiplication of their 2-dimensional DFTs.
For general image processing, you may find it useful to install scikit-image
(pycourse) conda install scikit-imagewhich also includes some standard test images.
import skimage
img = skimage.data.camera().astype(float)
print(img.shape)
plt.imshow(img, cmap=plt.cm.gray)
plt.show()Blurring¶
A Gaussian blur convolves the image with a 2-dimensional Gaussian, which is the same as multiplying its DFT by a Gaussian. scipy.ndimage.gaussian_filter computes the convolution directly, with a choice of what to assume outside the image. The FFT computes it with periodic boundaries, mode='wrap', so the top edge of the image is blurred into the bottom edge, and the left edge into the right.
sigma = 6.0 # width in pixels
ky = 2 * np.pi * fftfreq(img.shape[0])[:, None] # angular frequencies, per pixel
kx = 2 * np.pi * fftfreq(img.shape[1])[None, :]
blur_fft = ifft2(np.exp(-sigma**2 * (kx**2 + ky**2) / 2) * fft2(img)).real
blur_wrap = ndimage.gaussian_filter(img, sigma, mode='wrap', truncate=8.0)
print("FFT vs gaussian_filter(mode='wrap'):", np.max(np.abs(blur_fft - blur_wrap)))
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(blur_fft, cmap=plt.cm.gray)
ax[0].set_title('periodic boundary (FFT)')
ax[1].imshow(ndimage.gaussian_filter(img, sigma), cmap=plt.cm.gray)
ax[1].set_title("mirrored boundary (mode='reflect')")
plt.show()Stencils are convolutions¶
A finite difference formula is a convolution with a small kernel, called a stencil. For example, the five-point Laplacian from Boundary Value Problems,
is the convolution with the kernel below, divided by . On a periodic grid its matrix is therefore diagonalized by the 2-dimensional DFT, and the Poisson equation can be solved with a few FFTs, as in Spectral Methods.
In image processing, kernels like this one detect edges, since they are large where the brightness changes quickly. The Sobel kernel approximates by a centered difference, averaged over three rows; its transpose does the same for .
laplace_kernel = np.array([[0, 1, 0],
[1, -4, 1],
[0, 1, 0]])
lap = ndimage.convolve(img, laplace_kernel)
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(img, cmap=plt.cm.gray,)
ax[0].set_title('original image')
ax[1].imshow(np.abs(lap), cmap=plt.cm.gray, vmax=np.percentile(np.abs(lap), 99))
ax[1].set_title('five-point Laplacian')
plt.show()sobel_kernel = np.array([[1, 0, -1],
[2, 0, -2],
[1, 0, -1]])
grad_x = ndimage.convolve(img, sobel_kernel)
grad_y = ndimage.convolve(img, sobel_kernel.T)
grad = np.sqrt(grad_x**2 + grad_y**2)
fig, ax = plt.subplots(1, 3, figsize=(15, 5))
ax[0].imshow(np.abs(grad_x), cmap=plt.cm.gray, vmax=np.percentile(np.abs(grad_y), 99))
ax[0].set_title('sobel x')
ax[1].imshow(np.abs(grad_y), cmap=plt.cm.gray, vmax=np.percentile(np.abs(grad_y), 99))
ax[1].set_title('sobel y')
ax[2].imshow(np.abs(grad), cmap=plt.cm.gray, vmax=np.percentile(np.abs(grad), 99))
ax[2].set_title('gradient')
plt.show()Local convolutions¶
In image processing, you will often encounter local convolutions with only a small patch of weights is nonzero. One example is that many camera lenses cause a slight blur which mixes light from nearby sources. In deep learning, these local convolutions have been very effective in image processing tasks. The simplest explanation of why learning parameters for a convolution is a good idea in this situation is that convolutions are translation invariant, allowing the neural net to learn regardless of where a target appears on an image.
In this case, we typically think of convolutions as patches which slide over a 2-dimensional image. Applying the convolution with for-loops to an image takes operations, which beats the of the FFT when is small. GPUs are also very good at this sort of operation.
from numba import njit
@njit
def apply_convolution_2d(img, c):
"""
slide the k1 x k2 patch c over img, at every position where it fits inside the image
"""
m, n = img.shape
k1, k2 = c.shape
img2 = np.zeros((m - k1 + 1, n - k2 + 1))
for i in range(m - k1 + 1):
for j in range(n - k2 + 1):
for i1 in range(k1):
for j1 in range(k2):
img2[i, j] += img[i + i1, j + j1] * c[i1, j1]
return img2c = np.ones((10, 10)) / 100 # local averaging operator
apply_convolution_2d(img, c) # the first call compiles the function
%time img2 = apply_convolution_2d(img, c)
plt.imshow(img2, cmap=plt.cm.gray)
plt.show()Strictly speaking, this loop computes a cross-correlation, , rather than a convolution, which would use , the patch flipped in both directions. The two agree for symmetric patches like this one. SciPy has both:
c = rng.standard_normal((5, 5)) # not symmetric
corr = apply_convolution_2d(img, c)
print(np.allclose(corr, signal.correlate2d(img, c, mode='valid')))
print(np.allclose(corr, signal.convolve2d(img, c[::-1, ::-1], mode='valid')))Discrete Cosine Transform (DCT)¶
One of the potential annoyances with Fourier transforms is that even with real-valued signals they produce complex output. If you want to stick to real output with a similar interpretation, you can use the Discrete Cosine Transform (DCT) or Discrete Sine Transform (DST). Both are implemented in SciPy.
The DCT has a second, more important advantage. The DFT treats a signal as periodic, so unless happens to be close to , the periodic extension jumps. As we saw under spectral leakage, the coefficients then decay only like . The DCT instead extends the signal by its mirror image, , which is even and has no jump. An even signal is a sum of cosines, and the DCT coefficients are the DFT of the mirrored signal, up to a phase factor:
N = 64
f = rng.standard_normal(N)
mirrored = np.concatenate([f, f[::-1]])
k = np.arange(N)
print(np.allclose(dct(f), np.exp(-1j * np.pi * k / (2 * N)) * fft(mirrored)[:N]))The mirrored signal is continuous where the two copies meet, so for a smooth signal its coefficients decay like instead of , and truncating them does far less damage. Here are both transforms of a smooth function that is not periodic, on , and the reconstructions from the 17 lowest frequencies of each ( for the DFT and for the DCT, so the same number of real numbers):
N = 256
s = (np.arange(N) + 0.5) / N # N points in (0, 1)
f = np.exp(s) + np.sin(4*s) # smooth, but f(0) != f(1)
f_fft = fft(f)
f_dct = dct(f)
K = 8
low_fft = ifft(np.where(np.abs(fftfreq(N, d=1 / N)) <= K, f_fft, 0)).real
low_dct = idct(np.where(np.arange(N) <= 2 * K, f_dct, 0))
fig, ax = plt.subplots(1, 2, figsize=(13, 4))
k = np.arange(1, N // 2)
ax[0].loglog(k, np.abs(f_fft[1:N // 2]) / N, '.', label='DFT')
ax[0].loglog(k, np.abs(f_dct[1:N // 2]) / (2 * N), '.', label='DCT')
for p in [1, 2]:
ax[0].loglog(k, 0.3 / k**p, 'k:', lw=1)
ax[0].text(k[-1] * 1.1, 0.3 / k[-1]**p, f'$k^{{-{p}}}$', va='center')
ax[0].set_xlabel('$k$')
ax[0].set_title('size of the coefficients (scaled)')
ax[0].legend()
ax[1].plot(s, f, 'k--', lw=1, label='$f$')
ax[1].plot(s, low_fft, label=f'DFT, $|k| \\leq {K}$')
ax[1].plot(s, low_dct, label=f'DCT, $k \\leq {2 * K}$')
ax[1].set_xlabel('$s$')
ax[1].legend()
plt.show()
print(f"max error: DFT {np.max(np.abs(low_fft - f)):.1e}, DCT {np.max(np.abs(low_dct - f)):.1e}")The truncated DFT oscillates and overshoots near both ends (the Gibbs phenomenon), while the truncated DCT does not oscillate. This is why compression uses the DCT rather than the DFT, most famously in JPEG images.
Image compression¶
The DCT can also be used for a simple method of image compression - you can simply remove the high frequency components of an image and retain most of the large structure while losing some detail. dctn and idctn transform along every axis of an array.
ihat = dctn(img)
plt.imshow(np.log(np.abs(ihat)))
plt.colorbar()
plt.title('log |DCT coefficients|')
plt.show()Most of the large coefficients are at low frequencies, in the top left corner. Now, we’ll cut out the highest-frequency DCT coefficients. Inverting just the top left block of coefficients gives an image of half the size:
m, n = ihat.shape
ihat2 = ihat[:m//2, :n//2]
img2 = idctn(ihat2)
plt.imshow(img2, cmap=plt.cm.gray)
plt.show()Alternatively, we can make the image the original size by just setting the high-frequency DCT coefficients to 0.
ihat2 = np.zeros_like(ihat)
ihat2[:m//2, :n//2] = ihat[:m//2, :n//2]
img2 = idctn(ihat2)
plt.imshow(img2, cmap=plt.cm.gray)
plt.show()Now, let’s really compress the image, keeping only 1% of the coefficients...
ihat2 = np.zeros_like(ihat)
ihat2[:m//10, :n//10] = ihat[:m//10, :n//10]
img2 = idctn(ihat2)
plt.imshow(img2, cmap=plt.cm.gray)
plt.show()Keeping the lowest frequencies is not the best choice. The DCT is an orthogonal transformation, so by Parseval’s theorem the error in the image equals the error in the coefficients. The best way to keep a given number of coefficients is then to keep the largest ones, wherever they are. Here is the relative error of both strategies against the fraction of coefficients kept:
ihat = dctn(img, norm='ortho')
threshold = np.sort(np.abs(ihat).ravel())[::-1] # threshold[j - 1]: the j-th largest |coefficient|
def compress(ihat, fraction, largest):
"""
keep the given fraction of the DCT coefficients ihat, either the largest ones
or a square block of the lowest frequencies, and transform back
"""
keep = int(fraction * ihat.size)
kept = np.zeros_like(ihat)
if largest:
mask = np.abs(ihat) >= threshold[keep - 1]
kept[mask] = ihat[mask]
else:
side = int(np.sqrt(keep))
kept[:side, :side] = ihat[:side, :side]
return idctn(kept, norm='ortho')
fractions = [0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.25]
plt.figure(figsize=(6, 4))
for largest, label in [(False, 'lowest frequencies'), (True, 'largest coefficients')]:
errors = [la.norm(compress(ihat, frac, largest) - img) / la.norm(img) for frac in fractions]
plt.loglog(fractions, errors, 'o-', label=label)
plt.xlabel('fraction of coefficients kept')
plt.ylabel('relative error')
plt.legend()
plt.show()
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
for a, largest, label in [(ax[0], False, 'lowest frequencies'), (ax[1], True, 'largest coefficients')]:
a.imshow(compress(ihat, 0.02, largest), cmap=plt.cm.gray)
a.set_title(f'2% of the coefficients: {label}')
plt.show()Storing the largest coefficients also means storing where they are, so the real saving is smaller than the fraction suggests, but this is the core idea of transform coding. JPEG applies the DCT to blocks of the image, rounds the coefficients more coarsely at high frequencies, where the eye is less sensitive, and then encodes the many resulting zeros compactly.
Exercise¶
Create a plot that demonstrates the asymptotic scaling of the FFT is .
## Your code here