Skip to main content

lib_jsl_dsp/discrete/image/
geometric.rs

1//! Geometric transforms with B-spline interpolation, following `scipy.ndimage`: `spline_filter`,
2//! `map_coordinates`, `affine_transform`, `shift`, `zoom` and `rotate`.
3//!
4//! Every geometric transform has the same core: for each output pixel, compute where it comes from
5//! in the input (generally between pixels) and interpolate there. Interpolation of order `k` fits a
6//! piecewise polynomial of degree `k` that is `k − 1` times differentiable: order 0 takes the
7//! nearest pixel, order 1 is bilinear, and order 3 (the default) is the cubic B-spline. For orders
8//! above 1 the spline must *pass through* the pixels, which requires solving for its coefficients
9//! first: the **prefilter**, a pair of recursive filters per pole, run along each axis.
10//!
11//! See the book entry [Rank filters, derivative filters and geometric transforms](https://jwkunz.github.io/lib_jsl/book/image/rank-geometric.html).
12
13use lib_jsl_core::ErrorsJSL;
14use ndarray::Array2;
15
16use super::boundary::Mode;
17
18/// The poles of the B-spline prefilter of each order (Unser, Aldroubi and Eden; as in SciPy).
19fn poles(order: usize) -> Vec<f64> {
20    match order {
21        2 => vec![8f64.sqrt() - 3.0],
22        3 => vec![3f64.sqrt() - 2.0],
23        4 => vec![
24            (664.0 - 438976f64.sqrt()).sqrt() + 304f64.sqrt() - 19.0,
25            (664.0 + 438976f64.sqrt()).sqrt() - 304f64.sqrt() - 19.0,
26        ],
27        5 => vec![
28            (67.5 - 4436.25f64.sqrt()).sqrt() + 26.25f64.sqrt() - 6.5,
29            (67.5 + 4436.25f64.sqrt()).sqrt() - 26.25f64.sqrt() - 6.5,
30        ],
31        _ => vec![],
32    }
33}
34
35/// The boundary condition of the prefilter recursion.
36#[derive(Clone, Copy, PartialEq)]
37enum Ext {
38    /// Whole-sample symmetry, `c b | a b c | b a`.
39    Mirror,
40    /// Half-sample symmetry, `b a | a b c | c b`.
41    Reflect,
42    /// Periodic.
43    Wrap,
44}
45
46// ANCHOR: prefilter
47/// Converts one line of samples into B-spline coefficients in place: an overall gain, then for
48/// each pole `z` a causal recursion `c[i] += z c[i − 1]` and an anti-causal one
49/// `c[i] = z (c[i + 1] − c[i])`, each started from the infinite sum that the boundary symmetry
50/// implies (SciPy's `spline_filter1d`).
51fn prefilter_line(c: &mut [f64], order: usize, ext: Ext) {
52    let n = c.len();
53    if order < 2 || n < 2 {
54        return;
55    }
56    let zs = poles(order);
57    let gain: f64 = zs.iter().map(|&z| (1.0 - z) * (1.0 - 1.0 / z)).product();
58    c.iter_mut().for_each(|v| *v *= gain);
59    for &z in &zs {
60        // Causal initial value.
61        match ext {
62            Ext::Mirror => {
63                let zn1 = z.powi(n as i32 - 1);
64                let mut zi = z;
65                let mut c0 = c[0] + zn1 * c[n - 1];
66                for i in 1..n - 1 {
67                    c0 += zi * (c[i] + zn1 * c[n - 1 - i]);
68                    zi *= z;
69                }
70                c[0] = c0 / (1.0 - zn1 * zn1);
71            }
72            Ext::Reflect => {
73                let zn = z.powi(n as i32);
74                let first = c[0];
75                let mut zi = z;
76                let mut c0 = c[0] + zn * c[n - 1];
77                for i in 1..n {
78                    c0 += zi * (c[i] + zn * c[n - 1 - i]);
79                    zi *= z;
80                }
81                c[0] = c0 * z / (1.0 - zn * zn) + first;
82            }
83            Ext::Wrap => {
84                let mut zi = z;
85                let mut c0 = c[0];
86                for i in 1..n {
87                    c0 += zi * c[n - i];
88                    zi *= z;
89                }
90                c[0] = c0 / (1.0 - zi);
91            }
92        }
93        for i in 1..n {
94            c[i] += z * c[i - 1];
95        }
96        // Anti-causal initial value.
97        match ext {
98            Ext::Mirror => c[n - 1] = (z * c[n - 2] + c[n - 1]) * z / (z * z - 1.0),
99            Ext::Reflect => c[n - 1] *= z / (z - 1.0),
100            Ext::Wrap => {
101                let mut zi = z;
102                let mut cn = c[n - 1];
103                for &v in &c[..n - 1] {
104                    cn += zi * v;
105                    zi *= z;
106                }
107                c[n - 1] = cn * z / (zi - 1.0);
108            }
109        }
110        for i in (0..n - 1).rev() {
111            c[i] = z * (c[i + 1] - c[i]);
112        }
113    }
114}
115// ANCHOR_END: prefilter
116
117fn ext_of(mode: Mode) -> Ext {
118    match mode {
119        Mode::Reflect => Ext::Reflect,
120        Mode::Wrap => Ext::Wrap,
121        _ => Ext::Mirror,
122    }
123}
124
125/// Edge padding applied before prefiltering in `Nearest` mode, as SciPy does (its recursion has no
126/// exact boundary condition for that mode).
127const NEAREST_PAD: usize = 12;
128
129/// B-spline coefficients of `image` for interpolation of the given order (SciPy's `spline_filter`
130/// with the boundary condition that `mode` implies). Returns the coefficients and the padding
131/// added at each side.
132pub fn spline_filter(image: &Array2<f64>, order: usize, mode: Mode) -> Result<(Array2<f64>, usize), ErrorsJSL> {
133    if order > 5 {
134        return Err(ErrorsJSL::InvalidInputRange("spline order must be at most 5"));
135    }
136    let pad = if matches!(mode, Mode::Nearest) && order > 1 { NEAREST_PAD } else { 0 };
137    let (rows, cols) = image.dim();
138    let mut c = Array2::from_shape_fn((rows + 2 * pad, cols + 2 * pad), |(r, k)| {
139        let rr = (r as isize - pad as isize).clamp(0, rows as isize - 1) as usize;
140        let kk = (k as isize - pad as isize).clamp(0, cols as isize - 1) as usize;
141        image[(rr, kk)]
142    });
143    let ext = ext_of(mode);
144    for mut col in c.columns_mut() {
145        let mut line = col.to_vec();
146        prefilter_line(&mut line, order, ext);
147        col.iter_mut().zip(line).for_each(|(d, v)| *d = v);
148    }
149    for mut row in c.rows_mut() {
150        let mut line = row.to_vec();
151        prefilter_line(&mut line, order, ext);
152        row.iter_mut().zip(line).for_each(|(d, v)| *d = v);
153    }
154    Ok((c, pad))
155}
156
157/// The centred B-spline of degree `k` at `x`, `β_k(x)`.
158fn bspline(k: usize, x: f64) -> f64 {
159    let ax = x.abs();
160    match k {
161        0 => {
162            if ax < 0.5 { 1.0 } else { 0.0 }
163        }
164        1 => (1.0 - ax).max(0.0),
165        2 => {
166            if ax < 0.5 { 0.75 - ax * ax } else if ax < 1.5 { 0.5 * (1.5 - ax).powi(2) } else { 0.0 }
167        }
168        3 => {
169            if ax < 1.0 { 2.0 / 3.0 - ax * ax + 0.5 * ax.powi(3) } else if ax < 2.0 { (2.0 - ax).powi(3) / 6.0 } else { 0.0 }
170        }
171        4 => {
172            if ax < 0.5 {
173                let t = ax * ax;
174                t * (t * 0.25 - 0.625) + 115.0 / 192.0
175            } else if ax < 1.5 {
176                ax * (ax * (ax * (5.0 / 6.0 - ax / 6.0) - 1.25) + 5.0 / 24.0) + 55.0 / 96.0
177            } else if ax < 2.5 {
178                (2.5 - ax).powi(4) / 24.0
179            } else {
180                0.0
181            }
182        }
183        _ => {
184            if ax < 1.0 {
185                let t = ax * ax;
186                t * (t * (0.25 - ax / 12.0) - 0.5) + 0.55
187            } else if ax < 2.0 {
188                ax * (ax * (ax * (ax * (ax / 24.0 - 0.375) + 1.25) - 1.75) + 0.625) + 0.425
189            } else if ax < 3.0 {
190                (3.0 - ax).powi(5) / 120.0
191            } else {
192                0.0
193            }
194        }
195    }
196}
197
198/// The index of a coefficient, extended beyond `0..n` by the mode's symmetry.
199fn coeff_index(i: isize, n: usize, mode: Mode) -> usize {
200    let ni = n as isize;
201    if (0..ni).contains(&i) {
202        return i as usize;
203    }
204    if n == 1 {
205        return 0;
206    }
207    match mode {
208        Mode::Wrap => i.rem_euclid(ni) as usize,
209        Mode::Reflect => {
210            let m = i.rem_euclid(2 * ni);
211            (if m < ni { m } else { 2 * ni - 1 - m }) as usize
212        }
213        Mode::Nearest => i.clamp(0, ni - 1) as usize,
214        _ => {
215            let p = 2 * ni - 2;
216            let m = i.rem_euclid(p);
217            (if m < ni { m } else { p - m }) as usize
218        }
219    }
220}
221
222/// Interpolation weights and first index along one axis for a coordinate `x`.
223fn weights(x: f64, order: usize) -> (isize, Vec<f64>) {
224    if order == 0 {
225        // Nearest pixel, with halves rounded up as in SciPy.
226        return ((x + 0.5).floor() as isize, vec![1.0]);
227    }
228    let start = if order % 2 == 1 { x.floor() as isize - (order / 2) as isize } else { (x + 0.5).floor() as isize - (order / 2) as isize };
229    let w = (0..=order).map(|j| bspline(order, x - (start + j as isize) as f64)).collect();
230    (start, w)
231}
232
233// ANCHOR: map_coordinates
234/// Interpolates `image` at arbitrary points `(row, column)` (SciPy's `map_coordinates`), with
235/// spline order 0 to 5. Coefficients from [`spline_filter`] are combined with B-spline weights over
236/// the `(k + 1) × (k + 1)` neighbourhood of each point. In `Constant` mode, points outside the
237/// image (beyond `−0.5 … n − 0.5`… precisely, outside `[0, n − 1]`) take the constant, as in SciPy.
238pub fn map_coordinates(image: &Array2<f64>, points: &[(f64, f64)], order: usize, mode: Mode) -> Result<Vec<f64>, ErrorsJSL> {
239    if image.is_empty() {
240        return Err(ErrorsJSL::InvalidInputRange("image must be non-empty"));
241    }
242    let (coeffs, pad) = spline_filter(image, order, mode)?;
243    let (rows, cols) = image.dim();
244    let (cr, cc) = coeffs.dim();
245    Ok(points
246        .iter()
247        .map(|&(r, c)| {
248            if let Mode::Constant(k) = mode {
249                // SciPy treats coordinates within a small tolerance of the edge as inside.
250                let tol = 1e-12;
251                if r < -tol || c < -tol || r > rows as f64 - 1.0 + tol || c > cols as f64 - 1.0 + tol {
252                    return k;
253                }
254            }
255            let (r, c) = (r + pad as f64, c + pad as f64);
256            let (sr, wr) = weights(r, order);
257            let (sc, wc) = weights(c, order);
258            let mut v = 0.0;
259            for (i, a) in wr.iter().enumerate() {
260                if *a == 0.0 {
261                    continue;
262                }
263                let ri = coeff_index(sr + i as isize, cr, mode);
264                for (j, b) in wc.iter().enumerate() {
265                    v += a * b * coeffs[(ri, coeff_index(sc + j as isize, cc, mode))];
266                }
267            }
268            v
269        })
270        .collect())
271}
272// ANCHOR_END: map_coordinates
273
274// ANCHOR: affine_transform
275/// The affine transform (SciPy's `affine_transform`): output pixel `o` takes the input value at
276/// `matrix · o + offset`, interpolated. Note the direction: the matrix maps *output* coordinates to
277/// *input* coordinates, so to rotate an image by `θ` the matrix is the rotation by `−θ`.
278pub fn affine_transform(image: &Array2<f64>, matrix: [[f64; 2]; 2], offset: (f64, f64), output_shape: (usize, usize), order: usize, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
279    let (h, w) = output_shape;
280    let points: Vec<(f64, f64)> = (0..h * w)
281        .map(|k| {
282            let (r, c) = ((k / w) as f64, (k % w) as f64);
283            (matrix[0][0] * r + matrix[0][1] * c + offset.0, matrix[1][0] * r + matrix[1][1] * c + offset.1)
284        })
285        .collect();
286    let v = map_coordinates(image, &points, order, mode)?;
287    Array2::from_shape_vec((h, w), v).map_err(|_| ErrorsJSL::RuntimeError("shape mismatch"))
288}
289// ANCHOR_END: affine_transform
290
291/// Shifts the image by `(rows, columns)` pixels: output `o` takes input `o − shift`.
292pub fn shift(image: &Array2<f64>, by: (f64, f64), order: usize, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
293    affine_transform(image, [[1.0, 0.0], [0.0, 1.0]], (-by.0, -by.1), image.dim(), order, mode)
294}
295
296/// Resizes the image by factors `(rows, columns)` (SciPy's `zoom` with `grid_mode=False`): the
297/// output has `round(n · factor)` pixels along each axis, and its first and last pixels sample the
298/// input's first and last pixels exactly.
299pub fn zoom(image: &Array2<f64>, factor: (f64, f64), order: usize, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
300    let (rows, cols) = image.dim();
301    let out = ((rows as f64 * factor.0).round() as usize, (cols as f64 * factor.1).round() as usize);
302    if out.0 == 0 || out.1 == 0 {
303        return Err(ErrorsJSL::InvalidInputRange("the zoomed image would be empty"));
304    }
305    let step = |n: usize, m: usize| if m > 1 { (n as f64 - 1.0) / (m as f64 - 1.0) } else { 0.0 };
306    affine_transform(image, [[step(rows, out.0), 0.0], [0.0, step(cols, out.1)]], (0.0, 0.0), out, order, mode)
307}
308
309// ANCHOR: rotate
310/// Rotates the image by `angle` degrees about its centre (SciPy's `rotate`, axes `(1, 0)`): a
311/// positive angle turns the content anticlockwise on the screen. With `reshape` the output grows
312/// to hold the whole rotated image.
313pub fn rotate(image: &Array2<f64>, angle: f64, reshape: bool, order: usize, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
314    let (rows, cols) = image.dim();
315    let (s, c) = angle.to_radians().sin_cos();
316    let m = [[c, s], [-s, c]];
317    let out = if reshape {
318        let corners = [(0.0, 0.0), (0.0, cols as f64), (rows as f64, 0.0), (rows as f64, cols as f64)];
319        let tr: Vec<(f64, f64)> = corners.iter().map(|&(y, x)| (m[0][0] * y + m[0][1] * x, m[1][0] * y + m[1][1] * x)).collect();
320        let span = |f: fn(&(f64, f64)) -> f64| {
321            let v: Vec<f64> = tr.iter().map(f).collect();
322            v.iter().cloned().fold(f64::NEG_INFINITY, f64::max) - v.iter().cloned().fold(f64::INFINITY, f64::min)
323        };
324        ((span(|p| p.0) + 0.5) as usize, (span(|p| p.1) + 0.5) as usize)
325    } else {
326        (rows, cols)
327    };
328    let oc = ((out.0 as f64 - 1.0) / 2.0, (out.1 as f64 - 1.0) / 2.0);
329    let ic = ((rows as f64 - 1.0) / 2.0, (cols as f64 - 1.0) / 2.0);
330    let offset = (ic.0 - (m[0][0] * oc.0 + m[0][1] * oc.1), ic.1 - (m[1][0] * oc.0 + m[1][1] * oc.1));
331    affine_transform(image, m, offset, out, order, mode)
332}
333// ANCHOR_END: rotate
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338
339    #[test]
340    fn splines_interpolate_the_samples() {
341        let img = Array2::from_shape_fn((6, 7), |(r, c)| ((r * 7 + c) as f64).sin());
342        for order in 0..=5 {
343            for mode in [Mode::Mirror, Mode::Reflect, Mode::Nearest, Mode::Wrap, Mode::Constant(0.0)] {
344                let pts: Vec<(f64, f64)> = (0..6).flat_map(|r| (0..7).map(move |c| (r as f64, c as f64))).collect();
345                let v = map_coordinates(&img, &pts, order, mode).unwrap();
346                for (k, &(r, c)) in pts.iter().enumerate() {
347                    assert!((v[k] - img[(r as usize, c as usize)]).abs() < 1e-10, "order {order} {mode:?} at ({r},{c}): {}", v[k]);
348                }
349            }
350        }
351    }
352
353    #[test]
354    fn cubic_splines_reproduce_quadratics_in_the_interior() {
355        let f = |r: f64, c: f64| 0.3 * r * r - 0.2 * r * c + c;
356        let img = Array2::from_shape_fn((30, 30), |(r, c)| f(r as f64, c as f64));
357        let v = map_coordinates(&img, &[(14.3, 15.7)], 3, Mode::Mirror).unwrap();
358        assert!((v[0] - f(14.3, 15.7)).abs() < 1e-6, "{} vs {}", v[0], f(14.3, 15.7));
359    }
360
361    #[test]
362    fn a_quarter_turn_permutes_the_pixels() {
363        let img = Array2::from_shape_fn((4, 6), |(r, c)| (r * 6 + c) as f64);
364        let r = rotate(&img, 90.0, true, 1, Mode::Constant(0.0)).unwrap();
365        assert_eq!(r.dim(), (6, 4));
366        // Anticlockwise: the top-right input pixel becomes the top-left output pixel.
367        assert!((r[(0, 0)] - img[(0, 5)]).abs() < 1e-9, "{}", r[(0, 0)]);
368    }
369}