Fourier-domain filters
| Problem | Smooth an image with a Gaussian, box or disc kernel of any size at a fixed cost, or shift it by a fraction of a pixel, by multiplying its Fourier transform |
| Devised by | The convolution theorem (Fourier analysis, 19th century); fast convolution by the FFT: Thomas Stockham (1966); the closed-form transfer functions used here are those of scipy.ndimage |
| Accuracy | Agrees with scipy.ndimage to on full and real spectra; a phase-ramp shift of a smooth, periodic image is exact to rounding |
| Cost | Two 2D FFTs and one multiplication per frequency: for pixels, independent of the kernel size |
| Read first | Convolution and correlation, Rank filters, derivative filters and geometric transforms |
| API | fourier_gaussian, fourier_uniform, fourier_ellipsoid, fourier_shift, fourier_filter, frequencies, Spectrum |
Overview
A convolution in space is a multiplication in frequency. Smoothing an image with a kernel costs operations per pixel directly, or if the kernel is separable; through the fast Fourier transform it costs the same per pixel for any kernel. For large kernels that is a large saving, and for some operations the frequency domain is simply the natural place to work: a shift by half a pixel, for instance, is a pure phase change.
The four filters here, following scipy.ndimage, take a spectrum (the 2D FFT of an image) and multiply it by a transfer
function known in closed form:
fourier_gaussian: a Gaussian of standard deviations ;fourier_uniform: a box (moving average) of size ;fourier_ellipsoid: a uniform disc or ellipse with axes ;fourier_shift: a translation by pixels, not necessarily whole.
The price of working with the DFT is that convolution becomes circular: the image is treated as one tile of a periodic pattern, so features near one edge bleed into the opposite edge.
Where it is used
Doing the filtering in the Fourier domain makes large kernels cheap.
- Large blurs. A Gaussian of any width costs the same, useful for background estimation in microscopy and for the scale-space of feature detectors.
- Subpixel shifts. Aligning frames by a fraction of a pixel in astronomy (stacking exposures), video stabilisation and image registration.
- Deconvolution and restoration. Fourier-domain filters are the setting in which blur is undone.
History
The convolution theorem is as old as Fourier analysis itself, but it became a practical computing tool only with the fast Fourier
transform of James Cooley and John Tukey (1965). Thomas Stockham (1966) showed within a year that “high-speed convolution” by the FFT beats
direct convolution for all but short kernels, and image processing adopted it for large blurs, deconvolution and correlation. The
transfer functions here are the Fourier transforms of the continuous kernels (a Gaussian, a box and a disc, whose transform is the Airy
pattern of optics); their use in this form, applied to an existing spectrum, follows scipy.ndimage, whose fourier_* functions date
from Peter Verveer’s original numarray image library (around 2002).
The idea
Frequencies of the DFT
The 2D DFT of an image has the same shape. Entry belongs to the frequency in cycles per pixel, where along each axis the first half of the indices are non-negative frequencies and the rest negative ones:
For a real image it is common to store only half of the spectrum along one axis, from a real FFT: the rows then hold the
frequencies for . Spectrum::Full and Spectrum::RealRows { columns } select between the two layouts
(SciPy’s argument n). A filter multiplies each entry by its transfer function ; filtering a real image with a real,
symmetric gives a real result.
The transfer functions
Each filter uses the Fourier transform of the continuous kernel, evaluated at the DFT frequencies.
Gaussian. The Fourier transform of is , again a Gaussian, so
A wider Gaussian in space is a narrower one in frequency: smoothing removes high frequencies.
Box. A box of width has transform , and the 2D box is a product, so . The sinc changes sign: some frequencies come out inverted, which is why a box blur turns fine stripes into stripes of opposite contrast.
Disc and ellipse. A uniform disc of diameter has the transform , with the Bessel function of the first kind and ; this is the Airy pattern that a circular lens produces from a point. An ellipse is a disc with its axes scaled, which gives
Shift. Moving a signal by multiplies its transform by , so
The magnitude is 1 at every frequency: nothing is smoothed, only delayed.
Figure 17.20. Smoothing in the Fourier domain.
All three kernels blur the disc and the square similarly, but the box (whose sinc changes sign) leaves the stripes with reversed contrast, and every filter treats the image as periodic: the bright right edge and the dark left edge bleed into each other.
Fourier against spatial filtering
The spatial Gaussian filter of the previous entry samples the Gaussian and truncates it at ; the Fourier filter uses the exact transform of the untruncated continuous Gaussian. With wrap-around boundaries the two compute nearly the same thing:
Table 17.8. Spatial against Fourier Gaussian smoothing of a 256 × 256 image: difference and time.
| σ (256 × 256 image) | largest difference, spatial against Fourier | spatial (separable, wrap) | Fourier (FFT, filter, inverse FFT) |
|---|---|---|---|
| 0.5 | 1.4e-1 | 2.0 ms | 2.2 ms |
| 1 | 1.4e-3 | 3.6 ms | 2.3 ms |
| 2 | 9.6e-6 | 6.7 ms | 2.3 ms |
| 4 | 1.0e-5 | 14.1 ms | 2.3 ms |
| 8 | 7.5e-6 | 27.0 ms | 2.3 ms |
| 16 | 4.2e-6 | 53.9 ms | 2.7 ms |
For they agree to , the size of the truncated Gaussian tail. For small they differ a lot, because the continuous Gaussian is not band-limited: its transform does not vanish at the Nyquist frequency, so sampling it in space and evaluating it in frequency are different discretisations. The spatial cost grows with ; the Fourier cost does not. Where the two cross depends on the machine and the image size, but beyond a few pixels the Fourier filter is always the cheaper.
Shifting by a fraction of a pixel
For a band-limited, periodic signal the phase ramp is the exact shift: the shifted samples are those of the shifted continuous signal. For anything else it is the shift of the band-limited periodic interpolant, which rings near discontinuities, and the ringing spreads across the whole period:
Figure 17.21. Shifting by half a pixel.
Table 17.9. Largest error when shifting each signal alone by half a pixel.
| signal (shift by 0.5 pixel) | phase ramp: largest error | cubic spline: largest error |
|---|---|---|
| smooth bump (σ = 3 pixels) | 1.4e-11 | 1.0e-4 |
| step | 5.1e-1 | 5.0e-1 |
On the smooth bump the phase ramp is exact to , far better than the cubic spline. At the step both are wrong by half the step, because no sampled signal can say where inside a pixel a jump lies; the phase ramp adds Gibbs ringing that, in the figure, reaches all the way to the bump.
Algorithm
Frequencies of an spectrum: along the rows, for and otherwise; along the columns the same with , or for for a real FFT of rows of length .
Filter: multiply every entry by :
| filter | |
|---|---|
| Gaussian | |
| box | |
| ellipse | with , and 1 at |
| shift |
fourier_filter, for a real image: FFT, apply the filter to the full spectrum, inverse FFT, keep the real part.
Implementation
/// Gaussian smoothing with standard deviations `sigma = (rows, columns)` in pixels: multiplies by
/// `exp(−2π² (σ_r² f_r² + σ_c² f_c²))`, the Fourier transform of the continuous Gaussian.
pub fn fourier_gaussian(input: &Array2<C64>, sigma: (f64, f64), spectrum: Spectrum) -> Result<Array2<C64>, ErrorsJSL> {
let k = -2.0 * std::f64::consts::PI.powi(2);
apply(input, spectrum, |fr, fc| C64::new((k * (sigma.0 * sigma.0 * fr * fr + sigma.1 * sigma.1 * fc * fc)).exp(), 0.0))
}
/// A box (moving average) of `size = (rows, columns)` pixels: multiplies by
/// `sinc(s_r f_r) sinc(s_c f_c)`, with `sinc(x) = sin(πx)/(πx)`.
pub fn fourier_uniform(input: &Array2<C64>, size: (f64, f64), spectrum: Spectrum) -> Result<Array2<C64>, ErrorsJSL> {
apply(input, spectrum, |fr, fc| C64::new(sinc(size.0 * fr) * sinc(size.1 * fc), 0.0))
}
/// A uniform ellipse with axes `size = (rows, columns)` pixels (a disc when they are equal):
/// multiplies by `2 J₁(x)/x` with `x = π √((s_r f_r)² + (s_c f_c)²)`, the Airy pattern.
pub fn fourier_ellipsoid(input: &Array2<C64>, size: (f64, f64), spectrum: Spectrum) -> Result<Array2<C64>, ErrorsJSL> {
apply(input, spectrum, |fr, fc| {
let x = std::f64::consts::PI * ((size.0 * fr).powi(2) + (size.1 * fc).powi(2)).sqrt();
C64::new(if x == 0.0 { 1.0 } else { 2.0 * bessel_j_integer(1, x) / x }, 0.0)
})
}
/// A shift by `shift = (rows, columns)` pixels, which need not be whole: multiplies by the phase
/// ramp `exp(−2πi (s_r f_r + s_c f_c))`. Content moves towards larger indices for positive shifts,
/// wrapping round the edges.
pub fn fourier_shift(input: &Array2<C64>, shift: (f64, f64), spectrum: Spectrum) -> Result<Array2<C64>, ErrorsJSL> {
apply(input, spectrum, |fr, fc| C64::from_polar(1.0, -2.0 * std::f64::consts::PI * (shift.0 * fr + shift.1 * fc)))
}
- The filters take and return complex spectra, as SciPy’s do;
fourier_filterwraps the FFTs for a real image. Spectrum::RealRows { columns }handles spectra from a real FFT along each row (SciPy’snwithaxis=-1); the other axis is treated as a full spectrum, as in SciPy, whether or not it has been transformed.- comes from the special-functions crate.
In practice
Every filter is compared with scipy.ndimage on full spectra and on real-FFT rows (see the
chapter’s reference table); the largest difference is .
Strengths
- The cost is independent of the kernel size: large blurs are as cheap as small ones.
- The transfer functions are exact transforms of the continuous kernels, with no truncation.
- Sub-pixel shifts of smooth images are exact, and several filters can be combined by multiplying their transfer functions once.
Weaknesses
- Convolution is circular: edges wrap around. Pad the image (by reflection, or with its mean) before filtering to avoid it.
- For small kernels the spatial filter is faster, and for the two discretisations differ noticeably.
- Phase shifts ring at sharp edges, and the ringing is not local.
- The FFT works in floating point on the whole image, so memory grows with the image, not the kernel.
Exercises
- Show that the Fourier transform of is , and deduce that two Gaussian blurs of and make one of .
- Find the frequencies at which a box of width 7 inverts the contrast of a pattern, and check them on stripes of period 5 and 3 pixels.
- Show that shifting by a whole number of pixels with
fourier_shiftreproducesnumpy.rollexactly, for any image. - Pad an image by reflection to twice its size, smooth it with
fourier_gaussian, and crop. Compare the edges with the unpadded result and with the spatial filter inReflectmode. - Combine a Gaussian blur and a shift into one transfer function, and verify that the result equals applying them one after the other.
Hints and answers
- Complete the square in . Products of the transforms add the exponents: .
- for (and to ). Stripes of period 5 have (inverted, gain ); period 3 has (not inverted, gain ).
- With an integer, at is , the DFT shift theorem for a circular shift of samples.
- The reflected padding makes the image continuous across its edges, so the wrap-around disappears and the result matches the spatial
filter in
Reflectmode to the size of the Gaussian tail. - Transfer functions of a cascade multiply; multiplication is commutative, so the order does not matter, and one pass with the product gives the same spectrum to rounding.
Further reading
- T. G. Stockham, “High-speed convolution and correlation”, Proceedings of the AFIPS Spring Joint Computer Conference 28 (1966) 229–233.
- R. N. Bracewell, The Fourier Transform and Its Applications, 3rd ed., McGraw-Hill, 2000.
- R. C. Gonzalez and R. E. Woods, Digital Image Processing, 4th ed., Pearson, 2018, chapter 4 (filtering in the frequency domain).