Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Convolutions and Fourier Transforms

Open in Colab

A convolution is a linear operator of the form

(f∗g)(t)=∫Rf(τ) g(t−τ) dτ.(f \ast g)(t) = \int_{\mathbb R} f(\tau)\, g(t - \tau)\, \mathrm d\tau.

In a discrete space, the integral turns into a sum

(f∗g)n=∑mfm gn−m.(f \ast g)_n = \sum_m f_m\, g_{n - m}.

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.

Discrete convolution

Take two finite sequences f0,…,fM−1f_0, \dots, f_{M-1} and g0,…,gK−1g_0, \dots, g_{K-1}, and treat them as zero outside those ranges. Then (f∗g)n=∑mfmgn−m(f \ast g)_n = \sum_m f_m g_{n-m} can only be nonzero for n=0,…,M+K−2n = 0, \dots, M + K - 2, so the full convolution has length M+K−1M + K - 1.

Convolution can be computing using np.convolve.

A first example is the moving average. Convolving with g=(1,1,…,1)/Kg = (1, 1, \dots, 1)/K replaces each value by the average of KK neighboring values, which smooths out noise.

The mode argument says which part of the full convolution to return: 'full' gives all M+K−1M + K - 1 values, 'same' the middle MM of them, aligned with the input, and 'valid' only the M−K+1M - K + 1 values for which gg 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

p(x)=∑mfmxm,q(x)=∑jgjxj,p(x) = \sum_m f_m x^m, \quad q(x) = \sum_j g_j x^j,

then the coefficient of xnx^n in p(x)q(x)p(x) q(x) collects the products fmgjf_m g_j with m+j=nm + j = n, which is ∑mfmgn−m=(f∗g)n\sum_m f_m g_{n - m} = (f \ast g)_n. So multiplying polynomials is the same as convolving their coefficients. For example, (1+2x)(3+4x+5x2)=3+10x+13x2+10x3(1 + 2x)(3 + 4x + 5x^2) = 3 + 10x + 13x^2 + 10x^3:

Sums of random variables

If XX and YY are independent random variables with integer values, then

P(X+Y=n)=∑mP(X=m) P(Y=n−m),P(X + Y = n) = \sum_m P(X = m)\, P(Y = n - m),

so the distribution of X+YX + Y is the convolution of the two distributions. The same holds for continuous random variables: if XX and YY have probability density functions ff and gg, then X+YX + Y has the density f∗gf \ast g.

A fair die has the distribution (1/6,1/6,1/6,1/6,1/6,1/6)(1/6, 1/6, 1/6, 1/6, 1/6, 1/6) on landing in {1,…,6}\{1, \dots, 6\}. Convolving it with itself gives the triangle for the sum of two dice, and convolving nn copies gives the distribution of the sum of nn dice. By the central limit theorem, this approaches a normal distribution with mean 3.5n3.5n and variance 3512n\frac{35}{12}n (dashed).

Toeplitz and circulant matrices

Convolution with a fixed gg is linear in ff, so it is a matrix-vector product y=Gfy = Gf with the entries Gnm=gn−mG_{nm} = g_{n-m}. These only depend on n−mn - m, so they are constant along each diagonal. A matrix like this is called a Toeplitz matrix:

G=[g0g−1g−2…g1g0g−1…g2g1g0…⋮⋱]G = \begin{bmatrix} g_0 & g_{-1} & g_{-2} & \dots\\ g_1 & g_0 & g_{-1} &\dots\\ g_2 & g_1 & g_0 & \dots\\ \vdots & & &\ddots \end{bmatrix}

A Toeplitz matrix is determined by its first column and its first row, which is how scipy.linalg.toeplitz takes it.

For the full convolution of a signal of length MM with a sequence gg of length KK, the matrix is an (M+K−1)×M(M + K - 1) \times M Toeplitz matrix whose columns are shifted copies of gg. scipy.linalg.convolution_matrix builds it.

On a periodic domain, for a signal that repeats with period NN or for values on a ring of NN grid points, the shifts wrap around. The circular convolution

(f⊛g)n=∑m=0N−1fm g(n−m) mod N(f \circledast g)_n = \sum_{m=0}^{N-1} f_m\, g_{(n - m) \bmod N}

is represented by a circulant matrix. This is a Toeplitz matrix with g−i=gN−ig_{-i} = g_{N-i}, 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.

Both Toeplitz and circulant matrices have special solve functions in scipy.linalg. solve_toeplitz takes O(N2)O(N^2) operations instead of the O(N3)O(N^3) of Gaussian elimination, and solve_circulant takes O(Nlog⁡N)O(N \log N) operations, for reasons we will see shortly.

The discrete Fourier transform

A Fourier transform takes functions back and forth between the time (or space) domain and the frequency domain,

f^(ξ)=∫−∞∞f(x) e−2πixξ dx.\hat{f}(\xi) = \int_{-\infty}^\infty f(x)\, e^{-2\pi i x \xi}\, dx.

The discrete Fourier transform (DFT) does the same for a signal given as a vector f0,…,fN−1f_0, \dots, f_{N-1}:

f^k=∑n=0N−1fn e−2πikn/N,k=0,…,N−1.\hat f_k = \sum_{n=0}^{N-1} f_n\, e^{-2\pi i k n / N}, \qquad k = 0, \dots, N - 1.

The inverse DFT recovers the signal,

fn=1N∑k=0N−1f^k e2πikn/N.f_n = \frac{1}{N} \sum_{k=0}^{N-1} \hat f_k\, e^{2\pi i k n / N}.

The inverse formula writes ff as a combination of the NN discrete waves e2πikn/Ne^{2\pi i k n/N}, and f^k\hat f_k says how much of wave kk the signal contains. Computing the DFT from its definition takes O(N2)O(N^2) operations, but the fast Fourier transform (FFT) computes it in O(Nlog⁡N)O(N\log N) operations. SciPy provides it as scipy.fft.fft, with the inverse ifft.

Where the factor 1/N1/N 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 1/N1/\sqrt N in both directions, which makes the transform unitary, and norm='forward' puts 1/N1/N in the forward transform.

Frequencies

The wave e2πikn/Ne^{2\pi i k n/N} does not change if kk is replaced by k−Nk - N, so on the grid, frequency kk is the same as frequency k−Nk - N. The coefficients with k>N/2k > N/2 are best read as the negative frequencies k−Nk - N. fftfreq(N, d) returns the frequency of each coefficient in this order, in cycles per unit of xx 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 [0,2π)[0, 2\pi). With d = 1/N, the frequencies come out as integers: the number of periods in the interval.

The coefficients vanish except at k=±4k = \pm 4 and k=±8k = \pm 8, and they are purely imaginary: sin⁡4x=(e4ix−e−4ix)/2i\sin 4x = (e^{4ix} - e^{-4ix})/2i, so f^±4=∓iN/2=∓50i\hat f_{\pm 4} = \mp iN/2 = \mp 50i. This illustrates a general rule. Taking the complex conjugate of the definition shows that a real signal has

f^−k=f^k‾,\hat f_{-k} = \overline{\hat f_k},

so the real part of f^\hat f is even in kk and the imaginary part is odd, and the negative frequencies carry no information that the positive ones do not. rfft returns only the coefficients k=0,…,N/2k = 0, \dots, N/2, 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.

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 cos⁡4x\cos 4x with cos⁡4.5x\cos 4.5x on the same grid:

Away from k=±4k = \pm 4, the coefficients of cos⁡4x\cos 4x are zero up to rounding errors, while those of cos⁡4.5x\cos 4.5x, whose periodic extension jumps from -1 back to 1 at x=2πx = 2\pi, decay only like 1/∣k∣1/|k|. 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.

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 NN, is Parseval’s theorem,

∑n=0N−1∣fn∣2=1N∑k=0N−1∣f^k∣2.\sum_{n=0}^{N-1} |f_n|^2 = \frac{1}{N} \sum_{k=0}^{N-1} |\hat f_k|^2.

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 f(t)f(t) and g(t)g(t) is the product of their individual Fourier transforms:

f∗g^(k)=f^(k)g^(k).\widehat{ f * g}(k) = \hat f(k) \hat g(k).

In the discrete setting, circular convolution becomes pointwise multiplication in the frequency domain:

h=f⊛g⟺h^k=f^k g^k.h = f \circledast g \quad \Longleftrightarrow \quad \hat h_k = \hat f_k\, \hat g_k.

To see why, write ω=e−2πi/N\omega = e^{-2\pi i/N}, so that f^k=∑nfnωkn\hat f_k = \sum_n f_n \omega^{kn}, and note that ωkn\omega^{kn} only depends on n mod Nn \bmod N. Substituting n=m+jn = m + j,

h^k=∑n∑mfm g(n−m) mod N ωkn=∑mfm ωkm∑jgj ωkj=f^k g^k,\hat h_k = \sum_{n} \sum_{m} f_m\, g_{(n - m) \bmod N}\, \omega^{kn} = \sum_{m} f_m\, \omega^{km} \sum_{j} g_j\, \omega^{kj} = \hat f_k\, \hat g_k,

with all sums over 0,…,N−10, \dots, N - 1. Exponentials turn shifts into multiplication: ωk(m+j)=ωkmωkj\omega^{k(m + j)} = \omega^{km}\omega^{kj}: This is how to relate Fourier transform to convolution.

Linear convolution with the FFT

The cost of the convolution grows like N2N^2 and that of the FFT like Nlog⁡NN \log N, so for large NN the FFT speeds up convolutions.

The convolution theorem is about circular convolution. To compute the ordinary (linear) convolution of ff of length MM and gg of length KK, pad both with zeros to a length L≥M+K−1L \ge M + K - 1. Then the circular convolution of the padded vectors never wraps around onto a nonzero entry, and its first M+K−1M + K - 1 entries are the linear convolution. Without padding, the end of the result wraps around and is added to the beginning.

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 O(MK)O(MK) operations and the FFT O((M+K)log⁡(M+K))O((M + K)\log(M + K)), so the FFT wins unless one of the two sequences is short:

Filtering

Multiplying f^\hat f 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 σ\sigma multiplies the coefficient of the wave eikxe^{ikx} by e−σ2k2/2e^{-\sigma^2 k^2/2}, 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.

The same result comes from convolving with the Gaussian directly in xx. scipy.ndimage.gaussian_filter1d does that, with mode='wrap' for a periodic signal and the width given in grid points:

Deconvolution and ill-conditioning

Undoing a convolution is harder. Suppose we measure a blurred signal b=c⊛x+noiseb = c \circledast x + \text{noise}, where the blur cc is known (it might be the response of a measuring instrument), and want to recover xx. The circulant solve gives x^k=b^k/c^k\hat x_k = \hat b_k / \hat c_k. But a blur is a low-pass filter, so c^k\hat c_k is tiny at high frequencies, and dividing by it multiplies the noise there by a huge factor. The condition number max⁡k∣c^k∣/min⁡k∣c^k∣\max_k |\hat c_k| / \min_k |\hat c_k| measures exactly this amplification.

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 xx that minimizes

∥c⊛x−b∥2+α∥x∥2\|c \circledast x - b\|^2 + \alpha \|x\|^2

for a parameter α>0\alpha > 0. By Parseval’s theorem this splits into a separate scalar problem for each frequency, with the solution

x^k=c^k‾ b^k∣c^k∣2+α.\hat x_k = \frac{\overline{\hat c_k}\, \hat b_k}{|\hat c_k|^2 + \alpha}.

Where ∣c^k∣2≫α|\hat c_k|^2 \gg \alpha this is the naive b^k/c^k\hat b_k / \hat c_k, and where ∣c^k∣2≪α|\hat c_k|^2 \ll \alpha it is close to zero instead of huge. (In signal processing this is a form of the Wiener filter.)

A large α\alpha blurs the answer and a small one lets the noise back in. In between, around α=10−2\alpha = 10^{-2}, 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 α\alpha recovers the true signal exactly, since the information at the frequencies where ∣c^k∣|\hat c_k| 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 m×nm \times n 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 m×nm \times n image, the time complexity is O(mnlog⁡(mn))O(mn \log(mn)). 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-image

which also includes some standard test images.

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.

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,

(Δhu)ij=ui−1,j+ui+1,j+ui,j−1+ui,j+1−4uijh2,(\Delta_h u)_{ij} = \frac{u_{i-1,j} + u_{i+1,j} + u_{i,j-1} + u_{i,j+1} - 4u_{ij}}{h^2},

is the convolution with the 3×33 \times 3 kernel below, divided by h2h^2. 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 ∂/∂x\partial/\partial x by a centered difference, averaged over three rows; its transpose does the same for ∂/∂y\partial/\partial y.

Local convolutions

In image processing, you will often encounter local convolutions with only a small k×kk \times k 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 k×kk\times k patches which slide over a 2-dimensional image. Applying the convolution with for-loops to an m×nm\times n image takes O(k2mn)O(k^2 mn) operations, which beats the O(mnlog⁡(mn))O(mn \log(mn)) of the FFT when kk is small. GPUs are also very good at this sort of operation.

Strictly speaking, this loop computes a cross-correlation, ∑i1,j1imgi+i1,j+j1 ci1,j1\sum_{i_1, j_1} \text{img}_{i + i_1, j + j_1}\, c_{i_1, j_1}, rather than a convolution, which would use c−i1,−j1c_{-i_1, -j_1}, the patch flipped in both directions. The two agree for symmetric patches like this one. SciPy has both:

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 fN−1f_{N-1} happens to be close to f0f_0, the periodic extension jumps. As we saw under spectral leakage, the coefficients then decay only like 1/k1/k. The DCT instead extends the signal by its mirror image, f0,…,fN−1,fN−1,…,f0f_0, \dots, f_{N-1}, f_{N-1}, \dots, f_0, 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:

dct⁡(f)k=e−iπk/2N fft⁡(f0,…,fN−1,fN−1,…,f0)k,k=0,…,N−1.\operatorname{dct}(f)_k = e^{-i\pi k/2N}\, \operatorname{fft}(f_0, \dots, f_{N-1}, f_{N-1}, \dots, f_0)_k, \qquad k = 0, \dots, N - 1.

The mirrored signal is continuous where the two copies meet, so for a smooth signal its coefficients decay like 1/k21/k^2 instead of 1/k1/k, and truncating them does far less damage. Here are both transforms of a smooth function that is not periodic, f(s)=es+sin⁡4sf(s) = e^s + \sin 4s on [0,1][0, 1], and the reconstructions from the 17 lowest frequencies of each (∣k∣≤8|k| \le 8 for the DFT and k≤16k \le 16 for the DCT, so the same number of real numbers):

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.

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 m/2×n/2m/2 \times n/2 block of coefficients gives an image of half the size:

Alternatively, we can make the image the original size by just setting the high-frequency DCT coefficients to 0.

Now, let’s really compress the image, keeping only 1% of the coefficients...

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:

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 8×88 \times 8 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 O(Nlog⁡N)O(N \log N).