Skip to main content

lib_jsl_dsp/discrete/image/
fourier.rs

1//! Fourier-domain filters, following `scipy.ndimage`: `fourier_gaussian`, `fourier_uniform`,
2//! `fourier_ellipsoid` and `fourier_shift`.
3//!
4//! By the convolution theorem, convolving an image with a kernel multiplies its discrete Fourier
5//! transform by the kernel's transform. These functions take a spectrum (the output of a 2D FFT,
6//! or of a real FFT along the rows) and multiply it by a transfer function given in closed form:
7//! a Gaussian, a box (sinc), a disc or ellipse (the Airy pattern, `2 J₁(x)/x`), or a phase ramp
8//! (a shift by any fraction of a pixel). The cost is that of the FFTs, whatever the kernel size,
9//! and the convolution is circular: the image is treated as periodic.
10//!
11//! See the book entry [Fourier-domain filters](https://jwkunz.github.io/lib_jsl/book/image/fourier.html).
12
13use lib_jsl_core::ErrorsJSL;
14use lib_jsl_ffts::multidimensional_fft::{fft2, ifft2};
15use lib_jsl_special_functions::bessel_functions_integer::bessel_j_integer;
16use ndarray::Array2;
17use num_complex::Complex;
18
19type C64 = Complex<f64>;
20
21/// What kind of spectrum a Fourier filter receives (SciPy's `n` argument with `axis = -1`).
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Spectrum {
24    /// The full 2D DFT (`n = -1`): frequencies `k/N` for `k < ⌈N/2⌉`, then `(k − N)/N`, on both axes.
25    Full,
26    /// A real FFT along the rows (the last axis) of an image with `columns` columns, so that each
27    /// row holds `columns / 2 + 1` non-negative frequencies `k / columns`; the columns are a full DFT.
28    RealRows { columns: usize },
29}
30
31// ANCHOR: frequencies
32/// The frequencies (cycles per sample) of the rows and columns of a spectrum of shape `dim`.
33pub fn frequencies(dim: (usize, usize), spectrum: Spectrum) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
34    let full = |n: usize| -> Vec<f64> { (0..n).map(|k| if k < n.div_ceil(2) { k as f64 / n as f64 } else { (k as f64 - n as f64) / n as f64 }).collect() };
35    let rows = full(dim.0);
36    let cols = match spectrum {
37        Spectrum::Full => full(dim.1),
38        Spectrum::RealRows { columns } => {
39            if columns / 2 + 1 != dim.1 {
40                return Err(ErrorsJSL::IncompatibleArraySizes((dim.1, columns / 2 + 1)));
41            }
42            (0..dim.1).map(|k| k as f64 / columns as f64).collect()
43        }
44    };
45    Ok((rows, cols))
46}
47// ANCHOR_END: frequencies
48
49/// Multiplies a spectrum by a real or complex transfer function of the two frequencies.
50fn apply(input: &Array2<C64>, spectrum: Spectrum, h: impl Fn(f64, f64) -> C64) -> Result<Array2<C64>, ErrorsJSL> {
51    let (fr, fc) = frequencies(input.dim(), spectrum)?;
52    Ok(Array2::from_shape_fn(input.dim(), |(i, j)| input[(i, j)] * h(fr[i], fc[j])))
53}
54
55// ANCHOR: transfer_functions
56/// Gaussian smoothing with standard deviations `sigma = (rows, columns)` in pixels: multiplies by
57/// `exp(−2π² (σ_r² f_r² + σ_c² f_c²))`, the Fourier transform of the continuous Gaussian.
58pub fn fourier_gaussian(input: &Array2<C64>, sigma: (f64, f64), spectrum: Spectrum) -> Result<Array2<C64>, ErrorsJSL> {
59    let k = -2.0 * std::f64::consts::PI.powi(2);
60    apply(input, spectrum, |fr, fc| C64::new((k * (sigma.0 * sigma.0 * fr * fr + sigma.1 * sigma.1 * fc * fc)).exp(), 0.0))
61}
62
63/// A box (moving average) of `size = (rows, columns)` pixels: multiplies by
64/// `sinc(s_r f_r) sinc(s_c f_c)`, with `sinc(x) = sin(πx)/(πx)`.
65pub fn fourier_uniform(input: &Array2<C64>, size: (f64, f64), spectrum: Spectrum) -> Result<Array2<C64>, ErrorsJSL> {
66    apply(input, spectrum, |fr, fc| C64::new(sinc(size.0 * fr) * sinc(size.1 * fc), 0.0))
67}
68
69/// A uniform ellipse with axes `size = (rows, columns)` pixels (a disc when they are equal):
70/// multiplies by `2 J₁(x)/x` with `x = π √((s_r f_r)² + (s_c f_c)²)`, the Airy pattern.
71pub fn fourier_ellipsoid(input: &Array2<C64>, size: (f64, f64), spectrum: Spectrum) -> Result<Array2<C64>, ErrorsJSL> {
72    apply(input, spectrum, |fr, fc| {
73        let x = std::f64::consts::PI * ((size.0 * fr).powi(2) + (size.1 * fc).powi(2)).sqrt();
74        C64::new(if x == 0.0 { 1.0 } else { 2.0 * bessel_j_integer(1, x) / x }, 0.0)
75    })
76}
77
78/// A shift by `shift = (rows, columns)` pixels, which need not be whole: multiplies by the phase
79/// ramp `exp(−2πi (s_r f_r + s_c f_c))`. Content moves towards larger indices for positive shifts,
80/// wrapping round the edges.
81pub fn fourier_shift(input: &Array2<C64>, shift: (f64, f64), spectrum: Spectrum) -> Result<Array2<C64>, ErrorsJSL> {
82    apply(input, spectrum, |fr, fc| C64::from_polar(1.0, -2.0 * std::f64::consts::PI * (shift.0 * fr + shift.1 * fc)))
83}
84// ANCHOR_END: transfer_functions
85
86fn sinc(x: f64) -> f64 {
87    if x == 0.0 {
88        1.0
89    } else {
90        let px = std::f64::consts::PI * x;
91        px.sin() / px
92    }
93}
94
95/// Filters a real image in the Fourier domain: a 2D FFT, the given filter on the full spectrum,
96/// and the real part of the inverse FFT. For example,
97/// `fourier_filter(&image, |s| fourier_gaussian(s, (2.0, 2.0), Spectrum::Full))`.
98pub fn fourier_filter(image: &Array2<f64>, filter: impl Fn(&Array2<C64>) -> Result<Array2<C64>, ErrorsJSL>) -> Result<Array2<f64>, ErrorsJSL> {
99    let spectrum = fft2(&image.mapv(|v| C64::new(v, 0.0)))?;
100    Ok(ifft2(&filter(&spectrum)?)?.mapv(|z| z.re))
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn frequencies_of_odd_and_even_lengths() {
109        let (r, c) = frequencies((4, 5), Spectrum::Full).unwrap();
110        assert_eq!(r, vec![0.0, 0.25, -0.5, -0.25]);
111        assert_eq!(c, vec![0.0, 0.2, 0.4, -0.4, -0.2]);
112        let (_, c) = frequencies((4, 4), Spectrum::RealRows { columns: 7 }).unwrap();
113        assert_eq!(c, vec![0.0, 1.0 / 7.0, 2.0 / 7.0, 3.0 / 7.0]);
114    }
115
116    #[test]
117    fn a_whole_pixel_shift_rolls_the_image() {
118        let img = Array2::from_shape_fn((6, 8), |(r, c)| (r * 8 + c) as f64);
119        let out = fourier_filter(&img, |s| fourier_shift(s, (2.0, -3.0), Spectrum::Full)).unwrap();
120        for ((r, c), v) in out.indexed_iter() {
121            let want = img[((r + 6 - 2) % 6, (c + 3) % 8)];
122            assert!((v - want).abs() < 1e-10, "({r},{c}) {v} vs {want}");
123        }
124    }
125
126    #[test]
127    fn smoothing_keeps_the_mean() {
128        let img = Array2::from_shape_fn((16, 12), |(r, c)| ((r * 7 + c * 3) % 5) as f64);
129        let mean = img.mean().unwrap();
130        for f in [
131            fourier_gaussian as fn(&Array2<C64>, (f64, f64), Spectrum) -> Result<Array2<C64>, ErrorsJSL>,
132            fourier_uniform,
133            fourier_ellipsoid,
134        ] {
135            let out = fourier_filter(&img, |s| f(s, (2.5, 1.5), Spectrum::Full)).unwrap();
136            assert!((out.mean().unwrap() - mean).abs() < 1e-12);
137        }
138    }
139}