Skip to main content

lib_jsl_dsp/discrete/image/
convolution.rs

1//! 2D convolution and correlation with border handling, the shared basis of the image filters.
2//!
3//! Images are `Array2<f64>` indexed `(row, column)`. Kernels have odd dimensions and are centred
4//! on the output pixel. Pixels outside the image are supplied according to a [`Border`] mode.
5//! Direct (spatial) evaluation is used; for large kernels see
6//! [`fft_convolve_2d`](crate::discrete::fft_convolution::fft_convolve_2d).
7//!
8//! See the book entry [Image filtering](https://jwkunz.github.io/lib_jsl/book/image/filtering.html#convolution-and-border-modes).
9
10use lib_jsl_core::ErrorsJSL;
11use ndarray::Array2;
12
13/// How to supply pixels beyond the image edge.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum Border {
16    /// Outside pixels are 0.
17    Zero,
18    /// The edge pixel is repeated (`a a a | a b c | c c c`).
19    Replicate,
20    /// The image is mirrored about its edge (`c b a | a b c | c b a`).
21    Reflect,
22}
23
24/// Maps a possibly out-of-range index into `0..n` for a border mode (`None` means "zero").
25pub fn border_index(i: isize, n: usize, border: Border) -> Option<usize> {
26    let n_i = n as isize;
27    if (0..n_i).contains(&i) {
28        return Some(i as usize);
29    }
30    match border {
31        Border::Zero => None,
32        Border::Replicate => Some(i.clamp(0, n_i - 1) as usize),
33        Border::Reflect => {
34            let period = 2 * n_i;
35            let m = i.rem_euclid(period);
36            Some(if m < n_i { m as usize } else { (period - 1 - m) as usize })
37        }
38    }
39}
40
41fn check_kernel(kernel: &Array2<f64>) -> Result<(), ErrorsJSL> {
42    let (kr, kc) = kernel.dim();
43    if kr == 0 || kc == 0 || kr % 2 == 0 || kc % 2 == 0 {
44        return Err(ErrorsJSL::InvalidInputRange("Kernel dimensions must be odd and nonzero"));
45    }
46    Ok(())
47}
48
49/// 2D cross-correlation (the kernel is *not* flipped): `out[r, c] = Σ image[r+i, c+j] · kernel[i+hr, j+hc]`.
50pub fn correlate2d(image: &Array2<f64>, kernel: &Array2<f64>, border: Border) -> Result<Array2<f64>, ErrorsJSL> {
51    check_kernel(kernel)?;
52    let (rows, cols) = image.dim();
53    if rows == 0 || cols == 0 {
54        return Err(ErrorsJSL::InvalidInputRange("Image must be non-empty"));
55    }
56    let (kr, kc) = kernel.dim();
57    let (hr, hc) = ((kr / 2) as isize, (kc / 2) as isize);
58    Ok(Array2::from_shape_fn((rows, cols), |(r, c)| {
59        let mut acc = 0.0;
60        for i in 0..kr {
61            let Some(rr) = border_index(r as isize + i as isize - hr, rows, border) else { continue };
62            for j in 0..kc {
63                if let Some(cc) = border_index(c as isize + j as isize - hc, cols, border) {
64                    acc += image[(rr, cc)] * kernel[(i, j)];
65                }
66            }
67        }
68        acc
69    }))
70}
71
72/// 2D convolution (the kernel is flipped in both axes), output the same size as the input.
73pub fn convolve2d(image: &Array2<f64>, kernel: &Array2<f64>, border: Border) -> Result<Array2<f64>, ErrorsJSL> {
74    check_kernel(kernel)?;
75    let (kr, kc) = kernel.dim();
76    let flipped = Array2::from_shape_fn((kr, kc), |(i, j)| kernel[(kr - 1 - i, kc - 1 - j)]);
77    correlate2d(image, &flipped, border)
78}
79
80/// Separable filtering: convolves every row with `row_kernel` and then every column with
81/// `col_kernel` (both odd length, symmetric or not; true convolution).
82pub fn separable_convolve(image: &Array2<f64>, row_kernel: &[f64], col_kernel: &[f64], border: Border) -> Result<Array2<f64>, ErrorsJSL> {
83    if row_kernel.len().is_multiple_of(2) || col_kernel.len().is_multiple_of(2) || row_kernel.is_empty() || col_kernel.is_empty() {
84        return Err(ErrorsJSL::InvalidInputRange("Kernel lengths must be odd and nonzero"));
85    }
86    let (rows, cols) = image.dim();
87    if rows == 0 || cols == 0 {
88        return Err(ErrorsJSL::InvalidInputRange("Image must be non-empty"));
89    }
90    // ANCHOR: separable
91    let (hr, hc) = ((col_kernel.len() / 2) as isize, (row_kernel.len() / 2) as isize);
92    // Horizontal pass: convolution flips the kernel, so tap j pairs with offset (hc - j).
93    let horizontal = Array2::from_shape_fn((rows, cols), |(r, c)| {
94        row_kernel
95            .iter()
96            .enumerate()
97            .filter_map(|(j, k)| border_index(c as isize + hc - j as isize, cols, border).map(|cc| image[(r, cc)] * k))
98            .sum::<f64>()
99    });
100    Ok(Array2::from_shape_fn((rows, cols), |(r, c)| {
101        col_kernel
102            .iter()
103            .enumerate()
104            .filter_map(|(i, k)| border_index(r as isize + hr - i as isize, rows, border).map(|rr| horizontal[(rr, c)] * k))
105            .sum::<f64>()
106    }))
107    // ANCHOR_END: separable
108}
109
110/// A normalised 1D Gaussian kernel with standard deviation `sigma` (in pixels), truncated at
111/// `truncate` standard deviations (4 is conventional) and always of odd length.
112pub fn gaussian_kernel_1d(sigma: f64, truncate: f64) -> Result<Vec<f64>, ErrorsJSL> {
113    if !(sigma > 0.0) || !sigma.is_finite() || !(truncate > 0.0) {
114        return Err(ErrorsJSL::InvalidInputRange("sigma and truncate must be positive and finite"));
115    }
116    let radius = (truncate * sigma).ceil().max(1.0) as isize;
117    let mut k: Vec<f64> = (-radius..=radius).map(|i| (-0.5 * (i as f64 / sigma).powi(2)).exp()).collect();
118    let sum: f64 = k.iter().sum();
119    k.iter_mut().for_each(|v| *v /= sum);
120    Ok(k)
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    fn lcg(seed: &mut u64) -> f64 {
128        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
129        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
130    }
131
132    #[test]
133    fn border_modes_map_indices() {
134        assert_eq!(border_index(-1, 5, Border::Replicate), Some(0));
135        assert_eq!(border_index(7, 5, Border::Replicate), Some(4));
136        assert_eq!(border_index(-1, 5, Border::Reflect), Some(0));
137        assert_eq!(border_index(-2, 5, Border::Reflect), Some(1));
138        assert_eq!(border_index(5, 5, Border::Reflect), Some(4));
139        assert_eq!(border_index(6, 5, Border::Reflect), Some(3));
140        assert_eq!(border_index(-11, 5, Border::Reflect), Some(0), "reflection is periodic with period 2n");
141        assert_eq!(border_index(-6, 5, Border::Reflect), Some(4));
142        assert_eq!(border_index(-1, 5, Border::Zero), None);
143        assert_eq!(border_index(3, 5, Border::Zero), Some(3));
144    }
145
146    #[test]
147    fn identity_and_shift_kernels() {
148        let mut seed = 1;
149        let img = Array2::from_shape_fn((6, 7), |_| lcg(&mut seed));
150        let mut id = Array2::<f64>::zeros((3, 3));
151        id[(1, 1)] = 1.0;
152        assert_eq!(convolve2d(&img, &id, Border::Replicate).unwrap(), img);
153        // A kernel with a one at the top-left: correlation reads the pixel up-left of each output.
154        let mut tl = Array2::<f64>::zeros((3, 3));
155        tl[(0, 0)] = 1.0;
156        let c = correlate2d(&img, &tl, Border::Zero).unwrap();
157        assert_eq!(c[(3, 4)], img[(2, 3)]);
158        assert_eq!(c[(0, 4)], 0.0);
159        // Convolution flips the kernel, so the same kernel reads the pixel down-right.
160        let v = convolve2d(&img, &tl, Border::Zero).unwrap();
161        assert_eq!(v[(3, 4)], img[(4, 5)]);
162    }
163
164    #[test]
165    fn separable_matches_full_two_dimensional_convolution() {
166        let mut seed = 2;
167        let img = Array2::from_shape_fn((9, 11), |_| lcg(&mut seed));
168        let (a, b) = ([0.2, 0.5, 0.3], [0.1, 0.2, 0.4, 0.2, 0.1]);
169        let kernel = Array2::from_shape_fn((3, 5), |(i, j)| a[i] * b[j]);
170        for border in [Border::Zero, Border::Replicate, Border::Reflect] {
171            let direct = convolve2d(&img, &kernel, border).unwrap();
172            let sep = separable_convolve(&img, &b, &a, border).unwrap();
173            assert!(direct.iter().zip(sep.iter()).all(|(x, y)| (x - y).abs() < 1e-12), "{border:?}");
174        }
175    }
176
177    #[test]
178    fn gaussian_kernel_properties() {
179        let k = gaussian_kernel_1d(2.0, 4.0).unwrap();
180        assert_eq!(k.len(), 17);
181        assert!((k.iter().sum::<f64>() - 1.0).abs() < 1e-14);
182        assert!((0..8).all(|i| (k[i] - k[16 - i]).abs() < 1e-15), "symmetric");
183        let var: f64 = k.iter().enumerate().map(|(i, v)| (i as f64 - 8.0).powi(2) * v).sum();
184        assert!((var - 4.0).abs() < 0.01, "variance {var}");
185        assert!(k[8] > k[7] && k[7] > k[6]);
186        assert!(gaussian_kernel_1d(0.0, 4.0).is_err() && gaussian_kernel_1d(1.0, 0.0).is_err());
187        assert_eq!(gaussian_kernel_1d(0.1, 4.0).unwrap().len(), 3, "tiny sigma still gives at least 3 taps");
188    }
189
190    #[test]
191    fn rejects_bad_kernels_and_empty_images() {
192        let img = Array2::<f64>::ones((4, 4));
193        assert!(convolve2d(&img, &Array2::ones((2, 3)), Border::Zero).is_err());
194        assert!(correlate2d(&img, &Array2::ones((0, 3)), Border::Zero).is_err());
195        assert!(correlate2d(&Array2::<f64>::zeros((0, 4)), &Array2::ones((3, 3)), Border::Zero).is_err());
196        assert!(separable_convolve(&img, &[1.0, 1.0], &[1.0], Border::Zero).is_err());
197    }
198}