image/imageops/
sample.rs

1//! Functions and filters for the sampling of pixels.
2
3// See http://cs.brown.edu/courses/cs123/lectures/08_Image_Processing_IV.pdf
4// for some of the theory behind image scaling and convolution
5
6use num_traits::{NumCast, ToPrimitive, Zero};
7use std::f32;
8use std::ops::Mul;
9
10use crate::imageops::filter_1d::{
11    filter_2d_sep_la, filter_2d_sep_la_f32, filter_2d_sep_la_u16, filter_2d_sep_plane,
12    filter_2d_sep_plane_f32, filter_2d_sep_plane_u16, filter_2d_sep_rgb, filter_2d_sep_rgb_f32,
13    filter_2d_sep_rgb_u16, filter_2d_sep_rgba, filter_2d_sep_rgba_f32, filter_2d_sep_rgba_u16,
14    FilterImageSize,
15};
16use crate::images::buffer::{Gray16Image, GrayAlpha16Image, Rgb16Image, Rgba16Image};
17use crate::traits::{Enlargeable, Pixel, Primitive};
18use crate::utils::clamp;
19use crate::{
20    DynamicImage, GenericImage, GenericImageView, GrayAlphaImage, GrayImage, ImageBuffer,
21    Rgb32FImage, RgbImage, Rgba32FImage, RgbaImage,
22};
23
24/// Available Sampling Filters.
25///
26/// ## Examples
27///
28/// To test the different sampling filters on a real example, you can find two
29/// examples called
30/// [`scaledown`](https://github.com/image-rs/image/tree/main/examples/scaledown)
31/// and
32/// [`scaleup`](https://github.com/image-rs/image/tree/main/examples/scaleup)
33/// in the `examples` directory of the crate source code.
34///
35/// Here is a 3.58 MiB
36/// [test image](https://github.com/image-rs/image/blob/main/examples/scaledown/test.jpg)
37/// that has been scaled down to 300x225 px:
38///
39/// <!-- NOTE: To test new test images locally, replace the GitHub path with `../../../docs/` -->
40/// <div style="display: flex; flex-wrap: wrap; align-items: flex-start;">
41///   <div style="margin: 0 8px 8px 0;">
42///     <img src="https://raw.githubusercontent.com/image-rs/image/main/examples/scaledown/scaledown-test-near.png" title="Nearest"><br>
43///     Nearest Neighbor
44///   </div>
45///   <div style="margin: 0 8px 8px 0;">
46///     <img src="https://raw.githubusercontent.com/image-rs/image/main/examples/scaledown/scaledown-test-tri.png" title="Triangle"><br>
47///     Linear: Triangle
48///   </div>
49///   <div style="margin: 0 8px 8px 0;">
50///     <img src="https://raw.githubusercontent.com/image-rs/image/main/examples/scaledown/scaledown-test-cmr.png" title="CatmullRom"><br>
51///     Cubic: Catmull-Rom
52///   </div>
53///   <div style="margin: 0 8px 8px 0;">
54///     <img src="https://raw.githubusercontent.com/image-rs/image/main/examples/scaledown/scaledown-test-gauss.png" title="Gaussian"><br>
55///     Gaussian
56///   </div>
57///   <div style="margin: 0 8px 8px 0;">
58///     <img src="https://raw.githubusercontent.com/image-rs/image/main/examples/scaledown/scaledown-test-lcz2.png" title="Lanczos3"><br>
59///     Lanczos with window 3
60///   </div>
61/// </div>
62///
63/// ## Speed
64///
65/// Time required to create each of the examples above, tested on an Intel
66/// i7-4770 CPU with Rust 1.37 in release mode:
67///
68/// <table style="width: auto;">
69///   <tr>
70///     <th>Nearest</th>
71///     <td>31 ms</td>
72///   </tr>
73///   <tr>
74///     <th>Triangle</th>
75///     <td>414 ms</td>
76///   </tr>
77///   <tr>
78///     <th>CatmullRom</th>
79///     <td>817 ms</td>
80///   </tr>
81///   <tr>
82///     <th>Gaussian</th>
83///     <td>1180 ms</td>
84///   </tr>
85///   <tr>
86///     <th>Lanczos3</th>
87///     <td>1170 ms</td>
88///   </tr>
89/// </table>
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
91#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
92pub enum FilterType {
93    /// Nearest Neighbor
94    Nearest,
95
96    /// Linear Filter
97    Triangle,
98
99    /// Cubic Filter
100    CatmullRom,
101
102    /// Gaussian Filter
103    Gaussian,
104
105    /// Lanczos with window 3
106    Lanczos3,
107}
108
109/// A Representation of a separable filter.
110pub(crate) struct Filter<'a> {
111    /// The filter's filter function.
112    pub(crate) kernel: Box<dyn Fn(f32) -> f32 + 'a>,
113
114    /// The window on which this filter operates.
115    pub(crate) support: f32,
116}
117
118struct FloatNearest(f32);
119
120// to_i64, to_u64, and to_f64 implicitly affect all other lower conversions.
121// Note that to_f64 by default calls to_i64 and thus needs to be overridden.
122impl ToPrimitive for FloatNearest {
123    // to_{i,u}64 is required, to_{i,u}{8,16} are useful.
124    // If a usecase for full 32 bits is found its trivial to add
125    fn to_i8(&self) -> Option<i8> {
126        self.0.round().to_i8()
127    }
128    fn to_i16(&self) -> Option<i16> {
129        self.0.round().to_i16()
130    }
131    fn to_i64(&self) -> Option<i64> {
132        self.0.round().to_i64()
133    }
134    fn to_u8(&self) -> Option<u8> {
135        self.0.round().to_u8()
136    }
137    fn to_u16(&self) -> Option<u16> {
138        self.0.round().to_u16()
139    }
140    fn to_u64(&self) -> Option<u64> {
141        self.0.round().to_u64()
142    }
143    fn to_f64(&self) -> Option<f64> {
144        self.0.to_f64()
145    }
146}
147
148// sinc function: the ideal sampling filter.
149fn sinc(t: f32) -> f32 {
150    let a = t * f32::consts::PI;
151
152    if t == 0.0 {
153        1.0
154    } else {
155        a.sin() / a
156    }
157}
158
159// lanczos kernel function. A windowed sinc function.
160fn lanczos(x: f32, t: f32) -> f32 {
161    if x.abs() < t {
162        sinc(x) * sinc(x / t)
163    } else {
164        0.0
165    }
166}
167
168// Calculate a splice based on the b and c parameters.
169// from authors Mitchell and Netravali.
170fn bc_cubic_spline(x: f32, b: f32, c: f32) -> f32 {
171    let a = x.abs();
172
173    let k = if a < 1.0 {
174        (12.0 - 9.0 * b - 6.0 * c) * a.powi(3)
175            + (-18.0 + 12.0 * b + 6.0 * c) * a.powi(2)
176            + (6.0 - 2.0 * b)
177    } else if a < 2.0 {
178        (-b - 6.0 * c) * a.powi(3)
179            + (6.0 * b + 30.0 * c) * a.powi(2)
180            + (-12.0 * b - 48.0 * c) * a
181            + (8.0 * b + 24.0 * c)
182    } else {
183        0.0
184    };
185
186    k / 6.0
187}
188
189/// The Gaussian Function.
190/// ```r``` is the standard deviation.
191pub(crate) fn gaussian(x: f32, r: f32) -> f32 {
192    ((2.0 * f32::consts::PI).sqrt() * r).recip() * (-x.powi(2) / (2.0 * r.powi(2))).exp()
193}
194
195/// Calculate the lanczos kernel with a window of 3
196pub(crate) fn lanczos3_kernel(x: f32) -> f32 {
197    lanczos(x, 3.0)
198}
199
200/// Calculate the gaussian function with a
201/// standard deviation of 0.5
202pub(crate) fn gaussian_kernel(x: f32) -> f32 {
203    gaussian(x, 0.5)
204}
205
206/// Calculate the Catmull-Rom cubic spline.
207/// Also known as a form of `BiCubic` sampling in two dimensions.
208pub(crate) fn catmullrom_kernel(x: f32) -> f32 {
209    bc_cubic_spline(x, 0.0, 0.5)
210}
211
212/// Calculate the triangle function.
213/// Also known as `BiLinear` sampling in two dimensions.
214pub(crate) fn triangle_kernel(x: f32) -> f32 {
215    if x.abs() < 1.0 {
216        1.0 - x.abs()
217    } else {
218        0.0
219    }
220}
221
222/// Calculate the box kernel.
223/// Only pixels inside the box should be considered, and those
224/// contribute equally.  So this method simply returns 1.
225pub(crate) fn box_kernel(_x: f32) -> f32 {
226    1.0
227}
228
229// Sample the rows of the supplied image using the provided filter.
230// The height of the image remains unchanged.
231// ```new_width``` is the desired width of the new image
232// ```filter``` is the filter to use for sampling.
233// ```image``` is not necessarily Rgba and the order of channels is passed through.
234//
235// Note: if an empty image is passed in, panics unless the image is truly empty.
236fn horizontal_sample<P, S>(
237    image: &Rgba32FImage,
238    new_width: u32,
239    filter: &mut Filter,
240) -> ImageBuffer<P, Vec<S>>
241where
242    P: Pixel<Subpixel = S> + 'static,
243    S: Primitive + 'static,
244{
245    let (width, height) = image.dimensions();
246    // This is protection against a memory usage similar to #2340. See `vertical_sample`.
247    assert!(
248        // Checks the implication: (width == 0) -> (height == 0)
249        width != 0 || height == 0,
250        "Unexpected prior allocation size. This case should have been handled by the caller"
251    );
252
253    let mut out = ImageBuffer::new(new_width, height);
254    out.copy_color_space_from(image);
255    let mut ws = Vec::new();
256
257    let max: f32 = NumCast::from(S::DEFAULT_MAX_VALUE).unwrap();
258    let min: f32 = NumCast::from(S::DEFAULT_MIN_VALUE).unwrap();
259    let ratio = width as f32 / new_width as f32;
260    let sratio = if ratio < 1.0 { 1.0 } else { ratio };
261    let src_support = filter.support * sratio;
262
263    for outx in 0..new_width {
264        // Find the point in the input image corresponding to the centre
265        // of the current pixel in the output image.
266        let inputx = (outx as f32 + 0.5) * ratio;
267
268        // Left and right are slice bounds for the input pixels relevant
269        // to the output pixel we are calculating.  Pixel x is relevant
270        // if and only if (x >= left) && (x < right).
271
272        // Invariant: 0 <= left < right <= width
273
274        let left = (inputx - src_support).floor() as i64;
275        let left = clamp(left, 0, <i64 as From<_>>::from(width) - 1) as u32;
276
277        let right = (inputx + src_support).ceil() as i64;
278        let right = clamp(
279            right,
280            <i64 as From<_>>::from(left) + 1,
281            <i64 as From<_>>::from(width),
282        ) as u32;
283
284        // Go back to left boundary of pixel, to properly compare with i
285        // below, as the kernel treats the centre of a pixel as 0.
286        let inputx = inputx - 0.5;
287
288        ws.clear();
289        let mut sum = 0.0;
290        for i in left..right {
291            let w = (filter.kernel)((i as f32 - inputx) / sratio);
292            ws.push(w);
293            sum += w;
294        }
295        for w in ws.iter_mut() {
296            *w /= sum;
297        }
298
299        for y in 0..height {
300            let mut t = (0.0, 0.0, 0.0, 0.0);
301
302            for (i, w) in ws.iter().enumerate() {
303                let p = image.get_pixel(left + i as u32, y);
304
305                #[allow(deprecated)]
306                let vec = p.channels4();
307
308                t.0 += vec.0 * w;
309                t.1 += vec.1 * w;
310                t.2 += vec.2 * w;
311                t.3 += vec.3 * w;
312            }
313
314            #[allow(deprecated)]
315            let t = Pixel::from_channels(
316                NumCast::from(FloatNearest(clamp(t.0, min, max))).unwrap(),
317                NumCast::from(FloatNearest(clamp(t.1, min, max))).unwrap(),
318                NumCast::from(FloatNearest(clamp(t.2, min, max))).unwrap(),
319                NumCast::from(FloatNearest(clamp(t.3, min, max))).unwrap(),
320            );
321
322            out.put_pixel(outx, y, t);
323        }
324    }
325
326    out
327}
328
329/// Linearly sample from an image using coordinates in [0, 1].
330pub fn sample_bilinear<P: Pixel>(
331    img: &impl GenericImageView<Pixel = P>,
332    u: f32,
333    v: f32,
334) -> Option<P> {
335    if ![u, v].iter().all(|c| (0.0..=1.0).contains(c)) {
336        return None;
337    }
338
339    let (w, h) = img.dimensions();
340    if w == 0 || h == 0 {
341        return None;
342    }
343
344    let ui = w as f32 * u - 0.5;
345    let vi = h as f32 * v - 0.5;
346    interpolate_bilinear(
347        img,
348        ui.max(0.).min((w - 1) as f32),
349        vi.max(0.).min((h - 1) as f32),
350    )
351}
352
353/// Sample from an image using coordinates in [0, 1], taking the nearest coordinate.
354pub fn sample_nearest<P: Pixel>(
355    img: &impl GenericImageView<Pixel = P>,
356    u: f32,
357    v: f32,
358) -> Option<P> {
359    if ![u, v].iter().all(|c| (0.0..=1.0).contains(c)) {
360        return None;
361    }
362
363    let (w, h) = img.dimensions();
364    let ui = w as f32 * u - 0.5;
365    let ui = ui.max(0.).min((w.saturating_sub(1)) as f32);
366
367    let vi = h as f32 * v - 0.5;
368    let vi = vi.max(0.).min((h.saturating_sub(1)) as f32);
369    interpolate_nearest(img, ui, vi)
370}
371
372/// Sample from an image using coordinates in [0, w-1] and [0, h-1], taking the
373/// nearest pixel.
374///
375/// Coordinates outside the image bounds will return `None`, however the
376/// behavior for points within half a pixel of the image bounds may change in
377/// the future.
378pub fn interpolate_nearest<P: Pixel>(
379    img: &impl GenericImageView<Pixel = P>,
380    x: f32,
381    y: f32,
382) -> Option<P> {
383    let (w, h) = img.dimensions();
384    if w == 0 || h == 0 {
385        return None;
386    }
387    if !(0.0..=((w - 1) as f32)).contains(&x) {
388        return None;
389    }
390    if !(0.0..=((h - 1) as f32)).contains(&y) {
391        return None;
392    }
393
394    Some(img.get_pixel(x.round() as u32, y.round() as u32))
395}
396
397/// Linearly sample from an image using coordinates in [0, w-1] and [0, h-1].
398pub fn interpolate_bilinear<P: Pixel>(
399    img: &impl GenericImageView<Pixel = P>,
400    x: f32,
401    y: f32,
402) -> Option<P> {
403    // assumption needed for correctness of pixel creation
404    assert!(P::CHANNEL_COUNT <= 4);
405
406    let (w, h) = img.dimensions();
407    if w == 0 || h == 0 {
408        return None;
409    }
410    if !(0.0..=((w - 1) as f32)).contains(&x) {
411        return None;
412    }
413    if !(0.0..=((h - 1) as f32)).contains(&y) {
414        return None;
415    }
416
417    // keep these as integers, for fewer FLOPs
418    let uf = x.floor() as u32;
419    let vf = y.floor() as u32;
420    let uc = (uf + 1).min(w - 1);
421    let vc = (vf + 1).min(h - 1);
422
423    // clamp coords to the range of the image
424    let mut sxx = [[0.; 4]; 4];
425
426    // do not use Array::map, as it can be slow with high stack usage,
427    // for [[f32; 4]; 4].
428
429    // convert samples to f32
430    // currently rgba is the largest one,
431    // so just store as many items as necessary,
432    // because there's not a simple way to be generic over all of them.
433    let mut compute = |u: u32, v: u32, i| {
434        let s = img.get_pixel(u, v);
435        for (j, c) in s.channels().iter().enumerate() {
436            sxx[j][i] = c.to_f32().unwrap();
437        }
438        s
439    };
440
441    // hacky reuse since cannot construct a generic Pixel
442    let mut out: P = compute(uf, vf, 0);
443    compute(uf, vc, 1);
444    compute(uc, vf, 2);
445    compute(uc, vc, 3);
446
447    // weights, the later two are independent from the first 2 for better vectorization.
448    let ufw = x - uf as f32;
449    let vfw = y - vf as f32;
450    let ucw = (uf + 1) as f32 - x;
451    let vcw = (vf + 1) as f32 - y;
452
453    // https://en.wikipedia.org/wiki/Bilinear_interpolation#Weighted_mean
454    // the distance between pixels is 1 so there is no denominator
455    let wff = ucw * vcw;
456    let wfc = ucw * vfw;
457    let wcf = ufw * vcw;
458    let wcc = ufw * vfw;
459    // was originally assert, but is actually not a cheap computation
460    debug_assert!(f32::abs((wff + wfc + wcf + wcc) - 1.) < 1e-3);
461
462    // hack to see if primitive is an integer or a float
463    let is_float = P::Subpixel::DEFAULT_MAX_VALUE.to_f32().unwrap() == 1.0;
464
465    for (i, c) in out.channels_mut().iter_mut().enumerate() {
466        let v = wff * sxx[i][0] + wfc * sxx[i][1] + wcf * sxx[i][2] + wcc * sxx[i][3];
467        // this rounding may introduce quantization errors,
468        // Specifically what is meant is that many samples may deviate
469        // from the mean value of the originals, but it's not possible to fix that.
470        *c = <P::Subpixel as NumCast>::from(if is_float { v } else { v.round() }).unwrap_or({
471            if v < 0.0 {
472                P::Subpixel::DEFAULT_MIN_VALUE
473            } else {
474                P::Subpixel::DEFAULT_MAX_VALUE
475            }
476        });
477    }
478
479    Some(out)
480}
481
482// Sample the columns of the supplied image using the provided filter.
483// The width of the image remains unchanged.
484// ```new_height``` is the desired height of the new image
485// ```filter``` is the filter to use for sampling.
486// The return value is not necessarily Rgba, the underlying order of channels in ```image``` is
487// preserved.
488//
489// Note: if an empty image is passed in, panics unless the image is truly empty.
490fn vertical_sample<I, P, S>(image: &I, new_height: u32, filter: &mut Filter) -> Rgba32FImage
491where
492    I: GenericImageView<Pixel = P>,
493    P: Pixel<Subpixel = S> + 'static,
494    S: Primitive + 'static,
495{
496    let (width, height) = image.dimensions();
497
498    // This is protection against a regression in memory usage such as #2340. Since the strategy to
499    // deal with it depends on the caller it is a precondition of this function.
500    assert!(
501        // Checks the implication: (height == 0) -> (width == 0)
502        height != 0 || width == 0,
503        "Unexpected prior allocation size. This case should have been handled by the caller"
504    );
505
506    let mut out = ImageBuffer::new(width, new_height);
507    out.copy_color_space_from(&image.buffer_with_dimensions(0, 0));
508    let mut ws = Vec::new();
509
510    let ratio = height as f32 / new_height as f32;
511    let sratio = if ratio < 1.0 { 1.0 } else { ratio };
512    let src_support = filter.support * sratio;
513
514    for outy in 0..new_height {
515        // For an explanation of this algorithm, see the comments
516        // in horizontal_sample.
517        let inputy = (outy as f32 + 0.5) * ratio;
518
519        let left = (inputy - src_support).floor() as i64;
520        let left = clamp(left, 0, <i64 as From<_>>::from(height) - 1) as u32;
521
522        let right = (inputy + src_support).ceil() as i64;
523        let right = clamp(
524            right,
525            <i64 as From<_>>::from(left) + 1,
526            <i64 as From<_>>::from(height),
527        ) as u32;
528
529        let inputy = inputy - 0.5;
530
531        ws.clear();
532        let mut sum = 0.0;
533        for i in left..right {
534            let w = (filter.kernel)((i as f32 - inputy) / sratio);
535            ws.push(w);
536            sum += w;
537        }
538        for w in ws.iter_mut() {
539            *w /= sum;
540        }
541
542        for x in 0..width {
543            let mut t = (0.0, 0.0, 0.0, 0.0);
544
545            for (i, w) in ws.iter().enumerate() {
546                let p = image.get_pixel(x, left + i as u32);
547
548                #[allow(deprecated)]
549                let (k1, k2, k3, k4) = p.channels4();
550                let vec: (f32, f32, f32, f32) = (
551                    NumCast::from(k1).unwrap(),
552                    NumCast::from(k2).unwrap(),
553                    NumCast::from(k3).unwrap(),
554                    NumCast::from(k4).unwrap(),
555                );
556
557                t.0 += vec.0 * w;
558                t.1 += vec.1 * w;
559                t.2 += vec.2 * w;
560                t.3 += vec.3 * w;
561            }
562
563            #[allow(deprecated)]
564            // This is not necessarily Rgba.
565            let t = Pixel::from_channels(t.0, t.1, t.2, t.3);
566
567            out.put_pixel(x, outy, t);
568        }
569    }
570
571    out
572}
573
574/// Local struct for keeping track of pixel sums for fast thumbnail averaging
575struct ThumbnailSum<S: Primitive + Enlargeable>(S::Larger, S::Larger, S::Larger, S::Larger);
576
577impl<S: Primitive + Enlargeable> ThumbnailSum<S> {
578    fn zeroed() -> Self {
579        ThumbnailSum(
580            S::Larger::zero(),
581            S::Larger::zero(),
582            S::Larger::zero(),
583            S::Larger::zero(),
584        )
585    }
586
587    fn sample_val(val: S) -> S::Larger {
588        <S::Larger as NumCast>::from(val).unwrap()
589    }
590
591    fn add_pixel<P: Pixel<Subpixel = S>>(&mut self, pixel: P) {
592        #[allow(deprecated)]
593        let pixel = pixel.channels4();
594        self.0 += Self::sample_val(pixel.0);
595        self.1 += Self::sample_val(pixel.1);
596        self.2 += Self::sample_val(pixel.2);
597        self.3 += Self::sample_val(pixel.3);
598    }
599}
600
601/// Resize the supplied image to the specific dimensions.
602///
603/// For downscaling, this method uses a fast integer algorithm where each source pixel contributes
604/// to exactly one target pixel.  May give aliasing artifacts if new size is close to old size.
605///
606/// In case the current width is smaller than the new width or similar for the height, another
607/// strategy is used instead.  For each pixel in the output, a rectangular region of the input is
608/// determined, just as previously.  But when no input pixel is part of this region, the nearest
609/// pixels are interpolated instead.
610///
611/// For speed reasons, all interpolation is performed linearly over the colour values.  It will not
612/// take the pixel colour spaces into account.
613pub fn thumbnail<I, P, S>(image: &I, new_width: u32, new_height: u32) -> ImageBuffer<P, Vec<S>>
614where
615    I: GenericImageView<Pixel = P>,
616    P: Pixel<Subpixel = S> + 'static,
617    S: Primitive + Enlargeable + 'static,
618{
619    let (width, height) = image.dimensions();
620    let mut out = image.buffer_with_dimensions(new_width, new_height);
621
622    if height == 0 || width == 0 {
623        return out;
624    }
625
626    let x_ratio = width as f32 / new_width as f32;
627    let y_ratio = height as f32 / new_height as f32;
628
629    for outy in 0..new_height {
630        let bottomf = outy as f32 * y_ratio;
631        let topf = bottomf + y_ratio;
632
633        let bottom = clamp(bottomf.ceil() as u32, 0, height - 1);
634        let top = clamp(topf.ceil() as u32, bottom, height);
635
636        for outx in 0..new_width {
637            let leftf = outx as f32 * x_ratio;
638            let rightf = leftf + x_ratio;
639
640            let left = clamp(leftf.ceil() as u32, 0, width - 1);
641            let right = clamp(rightf.ceil() as u32, left, width);
642
643            let avg = if bottom != top && left != right {
644                thumbnail_sample_block(image, left, right, bottom, top)
645            } else if bottom != top {
646                // && left == right
647                // In the first column we have left == 0 and right > ceil(y_scale) > 0 so this
648                // assertion can never trigger.
649                debug_assert!(
650                    left > 0 && right > 0,
651                    "First output column must have corresponding pixels"
652                );
653
654                let fraction_horizontal = (leftf.fract() + rightf.fract()) / 2.;
655                thumbnail_sample_fraction_horizontal(
656                    image,
657                    right - 1,
658                    fraction_horizontal,
659                    bottom,
660                    top,
661                )
662            } else if left != right {
663                // && bottom == top
664                // In the first line we have bottom == 0 and top > ceil(x_scale) > 0 so this
665                // assertion can never trigger.
666                debug_assert!(
667                    bottom > 0 && top > 0,
668                    "First output row must have corresponding pixels"
669                );
670
671                let fraction_vertical = (topf.fract() + bottomf.fract()) / 2.;
672                thumbnail_sample_fraction_vertical(image, left, right, top - 1, fraction_vertical)
673            } else {
674                // bottom == top && left == right
675                let fraction_horizontal = (topf.fract() + bottomf.fract()) / 2.;
676                let fraction_vertical = (leftf.fract() + rightf.fract()) / 2.;
677
678                thumbnail_sample_fraction_both(
679                    image,
680                    right - 1,
681                    fraction_horizontal,
682                    top - 1,
683                    fraction_vertical,
684                )
685            };
686
687            #[allow(deprecated)]
688            let pixel = Pixel::from_channels(avg.0, avg.1, avg.2, avg.3);
689            out.put_pixel(outx, outy, pixel);
690        }
691    }
692
693    out
694}
695
696/// Get a pixel for a thumbnail where the input window encloses at least a full pixel.
697fn thumbnail_sample_block<I, P, S>(
698    image: &I,
699    left: u32,
700    right: u32,
701    bottom: u32,
702    top: u32,
703) -> (S, S, S, S)
704where
705    I: GenericImageView<Pixel = P>,
706    P: Pixel<Subpixel = S>,
707    S: Primitive + Enlargeable,
708{
709    let mut sum = ThumbnailSum::zeroed();
710
711    for y in bottom..top {
712        for x in left..right {
713            let k = image.get_pixel(x, y);
714            sum.add_pixel(k);
715        }
716    }
717
718    let n = <S::Larger as NumCast>::from((right - left) * (top - bottom)).unwrap();
719    let round = <S::Larger as NumCast>::from(n / NumCast::from(2).unwrap()).unwrap();
720    (
721        S::clamp_from((sum.0 + round) / n),
722        S::clamp_from((sum.1 + round) / n),
723        S::clamp_from((sum.2 + round) / n),
724        S::clamp_from((sum.3 + round) / n),
725    )
726}
727
728/// Get a thumbnail pixel where the input window encloses at least a vertical pixel.
729fn thumbnail_sample_fraction_horizontal<I, P, S>(
730    image: &I,
731    left: u32,
732    fraction_horizontal: f32,
733    bottom: u32,
734    top: u32,
735) -> (S, S, S, S)
736where
737    I: GenericImageView<Pixel = P>,
738    P: Pixel<Subpixel = S>,
739    S: Primitive + Enlargeable,
740{
741    let fract = fraction_horizontal;
742
743    let mut sum_left = ThumbnailSum::zeroed();
744    let mut sum_right = ThumbnailSum::zeroed();
745    for x in bottom..top {
746        let k_left = image.get_pixel(left, x);
747        sum_left.add_pixel(k_left);
748
749        let k_right = image.get_pixel(left + 1, x);
750        sum_right.add_pixel(k_right);
751    }
752
753    // Now we approximate: left/n*(1-fract) + right/n*fract
754    let fact_right = fract / ((top - bottom) as f32);
755    let fact_left = (1. - fract) / ((top - bottom) as f32);
756
757    let mix_left_and_right = |leftv: S::Larger, rightv: S::Larger| {
758        <S as NumCast>::from(
759            fact_left * leftv.to_f32().unwrap() + fact_right * rightv.to_f32().unwrap(),
760        )
761        .expect("Average sample value should fit into sample type")
762    };
763
764    (
765        mix_left_and_right(sum_left.0, sum_right.0),
766        mix_left_and_right(sum_left.1, sum_right.1),
767        mix_left_and_right(sum_left.2, sum_right.2),
768        mix_left_and_right(sum_left.3, sum_right.3),
769    )
770}
771
772/// Get a thumbnail pixel where the input window encloses at least a horizontal pixel.
773fn thumbnail_sample_fraction_vertical<I, P, S>(
774    image: &I,
775    left: u32,
776    right: u32,
777    bottom: u32,
778    fraction_vertical: f32,
779) -> (S, S, S, S)
780where
781    I: GenericImageView<Pixel = P>,
782    P: Pixel<Subpixel = S>,
783    S: Primitive + Enlargeable,
784{
785    let fract = fraction_vertical;
786
787    let mut sum_bot = ThumbnailSum::zeroed();
788    let mut sum_top = ThumbnailSum::zeroed();
789    for x in left..right {
790        let k_bot = image.get_pixel(x, bottom);
791        sum_bot.add_pixel(k_bot);
792
793        let k_top = image.get_pixel(x, bottom + 1);
794        sum_top.add_pixel(k_top);
795    }
796
797    // Now we approximate: bot/n*fract + top/n*(1-fract)
798    let fact_top = fract / ((right - left) as f32);
799    let fact_bot = (1. - fract) / ((right - left) as f32);
800
801    let mix_bot_and_top = |botv: S::Larger, topv: S::Larger| {
802        <S as NumCast>::from(fact_bot * botv.to_f32().unwrap() + fact_top * topv.to_f32().unwrap())
803            .expect("Average sample value should fit into sample type")
804    };
805
806    (
807        mix_bot_and_top(sum_bot.0, sum_top.0),
808        mix_bot_and_top(sum_bot.1, sum_top.1),
809        mix_bot_and_top(sum_bot.2, sum_top.2),
810        mix_bot_and_top(sum_bot.3, sum_top.3),
811    )
812}
813
814/// Get a single pixel for a thumbnail where the input window does not enclose any full pixel.
815fn thumbnail_sample_fraction_both<I, P, S>(
816    image: &I,
817    left: u32,
818    fraction_vertical: f32,
819    bottom: u32,
820    fraction_horizontal: f32,
821) -> (S, S, S, S)
822where
823    I: GenericImageView<Pixel = P>,
824    P: Pixel<Subpixel = S>,
825    S: Primitive + Enlargeable,
826{
827    #[allow(deprecated)]
828    let k_bl = image.get_pixel(left, bottom).channels4();
829    #[allow(deprecated)]
830    let k_tl = image.get_pixel(left, bottom + 1).channels4();
831    #[allow(deprecated)]
832    let k_br = image.get_pixel(left + 1, bottom).channels4();
833    #[allow(deprecated)]
834    let k_tr = image.get_pixel(left + 1, bottom + 1).channels4();
835
836    let frac_v = fraction_vertical;
837    let frac_h = fraction_horizontal;
838
839    let fact_tr = frac_v * frac_h;
840    let fact_tl = frac_v * (1. - frac_h);
841    let fact_br = (1. - frac_v) * frac_h;
842    let fact_bl = (1. - frac_v) * (1. - frac_h);
843
844    let mix = |br: S, tr: S, bl: S, tl: S| {
845        <S as NumCast>::from(
846            fact_br * br.to_f32().unwrap()
847                + fact_tr * tr.to_f32().unwrap()
848                + fact_bl * bl.to_f32().unwrap()
849                + fact_tl * tl.to_f32().unwrap(),
850        )
851        .expect("Average sample value should fit into sample type")
852    };
853
854    (
855        mix(k_br.0, k_tr.0, k_bl.0, k_tl.0),
856        mix(k_br.1, k_tr.1, k_bl.1, k_tl.1),
857        mix(k_br.2, k_tr.2, k_bl.2, k_tl.2),
858        mix(k_br.3, k_tr.3, k_bl.3, k_tl.3),
859    )
860}
861
862/// Perform a 3x3 box filter on the supplied image.
863///
864/// # Arguments:
865///
866/// * `image` - source image.
867/// * `kernel` - is an array of the filter weights of length 9.
868///
869/// This method typically assumes that the input is scene-linear light.
870/// If it is not, color distortion may occur.
871pub fn filter3x3<I, P, S>(image: &I, kernel: &[f32]) -> ImageBuffer<P, Vec<S>>
872where
873    I: GenericImageView<Pixel = P>,
874    P: Pixel<Subpixel = S> + 'static,
875    S: Primitive + 'static,
876{
877    // The kernel's input positions relative to the current pixel.
878    let taps: &[(isize, isize)] = &[
879        (-1, -1),
880        (0, -1),
881        (1, -1),
882        (-1, 0),
883        (0, 0),
884        (1, 0),
885        (-1, 1),
886        (0, 1),
887        (1, 1),
888    ];
889
890    let (width, height) = image.dimensions();
891    let mut out = image.buffer_like();
892
893    let max = S::DEFAULT_MAX_VALUE;
894    let max: f32 = NumCast::from(max).unwrap();
895
896    let inverse_sum = match kernel.iter().sum() {
897        0.0 => 1.0,
898        sum => 1.0 / sum,
899    };
900
901    for y in 1..height - 1 {
902        for x in 1..width - 1 {
903            let mut t = (0.0, 0.0, 0.0, 0.0);
904
905            // TODO: There is no need to recalculate the kernel for each pixel.
906            // Only a subtract and addition is needed for pixels after the first
907            // in each row.
908            for (&k, &(a, b)) in kernel.iter().zip(taps.iter()) {
909                let x0 = x as isize + a;
910                let y0 = y as isize + b;
911
912                let p = image.get_pixel(x0 as u32, y0 as u32);
913
914                #[allow(deprecated)]
915                let (k1, k2, k3, k4) = p.channels4();
916
917                let vec: (f32, f32, f32, f32) = (
918                    NumCast::from(k1).unwrap(),
919                    NumCast::from(k2).unwrap(),
920                    NumCast::from(k3).unwrap(),
921                    NumCast::from(k4).unwrap(),
922                );
923
924                t.0 += vec.0 * k;
925                t.1 += vec.1 * k;
926                t.2 += vec.2 * k;
927                t.3 += vec.3 * k;
928            }
929
930            let (t1, t2, t3, t4) = (
931                t.0 * inverse_sum,
932                t.1 * inverse_sum,
933                t.2 * inverse_sum,
934                t.3 * inverse_sum,
935            );
936
937            #[allow(deprecated)]
938            let t = Pixel::from_channels(
939                NumCast::from(clamp(t1, 0.0, max)).unwrap(),
940                NumCast::from(clamp(t2, 0.0, max)).unwrap(),
941                NumCast::from(clamp(t3, 0.0, max)).unwrap(),
942                NumCast::from(clamp(t4, 0.0, max)).unwrap(),
943            );
944
945            out.put_pixel(x, y, t);
946        }
947    }
948
949    out
950}
951
952/// Resize the supplied image to the specified dimensions.
953///
954/// # Arguments:
955///
956/// * `nwidth` - new image width.
957/// * `nheight` - new image height.
958/// * `filter` -  is the sampling filter to use, see [FilterType] for mor information.
959///
960/// This method assumes alpha pre-multiplication for images that contain non-constant alpha.
961///
962/// This method typically assumes that the input is scene-linear light.
963/// If it is not, color distortion may occur.
964pub fn resize<I: GenericImageView>(
965    image: &I,
966    nwidth: u32,
967    nheight: u32,
968    filter: FilterType,
969) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::Subpixel>>
970where
971    I::Pixel: 'static,
972    <I::Pixel as Pixel>::Subpixel: 'static,
973{
974    // Check if there is nothing to sample from.
975    let is_empty = {
976        let (width, height) = image.dimensions();
977        width == 0 || height == 0
978    };
979
980    if is_empty {
981        return image.buffer_with_dimensions(nwidth, nheight);
982    }
983
984    // check if the new dimensions are the same as the old. if they are, make a copy instead of resampling
985    if (nwidth, nheight) == image.dimensions() {
986        let mut tmp = image.buffer_like();
987        tmp.copy_from(image, 0, 0).unwrap();
988        return tmp;
989    }
990
991    let mut method = match filter {
992        FilterType::Nearest => Filter {
993            kernel: Box::new(box_kernel),
994            support: 0.0,
995        },
996        FilterType::Triangle => Filter {
997            kernel: Box::new(triangle_kernel),
998            support: 1.0,
999        },
1000        FilterType::CatmullRom => Filter {
1001            kernel: Box::new(catmullrom_kernel),
1002            support: 2.0,
1003        },
1004        FilterType::Gaussian => Filter {
1005            kernel: Box::new(gaussian_kernel),
1006            support: 3.0,
1007        },
1008        FilterType::Lanczos3 => Filter {
1009            kernel: Box::new(lanczos3_kernel),
1010            support: 3.0,
1011        },
1012    };
1013
1014    // Note: tmp is not necessarily actually Rgba
1015    let tmp: Rgba32FImage = vertical_sample(image, nheight, &mut method);
1016    horizontal_sample(&tmp, nwidth, &mut method)
1017}
1018
1019/// Performs a Gaussian blur on the supplied image.
1020///
1021/// # Arguments
1022///
1023///  - `sigma` - gaussian bell flattening level.
1024///
1025/// Use [`crate::imageops::fast_blur()`] for a faster but less
1026/// accurate version.
1027/// This method assumes alpha pre-multiplication for images that contain non-constant alpha.
1028/// This method typically assumes that the input is scene-linear light.
1029/// If it is not, color distortion may occur.
1030pub fn blur<I: GenericImageView>(
1031    image: &I,
1032    sigma: f32,
1033) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::Subpixel>>
1034where
1035    I::Pixel: 'static,
1036{
1037    gaussian_blur_indirect(
1038        image,
1039        GaussianBlurParameters::new_from_sigma(if sigma == 0.0 { 0.8 } else { sigma }),
1040    )
1041}
1042
1043/// Performs a Gaussian blur on the supplied image.
1044///
1045/// # Arguments
1046///
1047///  - `parameters` - see [GaussianBlurParameters] for more info.
1048///
1049/// This method assumes alpha pre-multiplication for images that contain non-constant alpha.
1050/// This method typically assumes that the input is scene-linear light.
1051/// If it is not, color distortion may occur.
1052pub fn blur_advanced<I: GenericImageView>(
1053    image: &I,
1054    parameters: GaussianBlurParameters,
1055) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::Subpixel>>
1056where
1057    I::Pixel: 'static,
1058{
1059    gaussian_blur_indirect(image, parameters)
1060}
1061
1062fn get_gaussian_kernel_1d(width: usize, sigma: f32) -> Vec<f32> {
1063    let mut sum_norm: f32 = 0f32;
1064    let mut kernel = vec![0f32; width];
1065    let scale = 1f32 / (f32::sqrt(2f32 * f32::consts::PI) * sigma);
1066    let mean = (width / 2) as f32;
1067
1068    for (x, weight) in kernel.iter_mut().enumerate() {
1069        let new_weight = f32::exp(-0.5f32 * f32::powf((x as f32 - mean) / sigma, 2.0f32)) * scale;
1070        *weight = new_weight;
1071        sum_norm += new_weight;
1072    }
1073
1074    if sum_norm != 0f32 {
1075        let sum_scale = 1f32 / sum_norm;
1076        for weight in &mut kernel {
1077            *weight = weight.mul(sum_scale);
1078        }
1079    }
1080
1081    kernel
1082}
1083
1084/// Holds analytical gaussian blur representation
1085#[derive(Copy, Clone, PartialOrd, PartialEq)]
1086pub struct GaussianBlurParameters {
1087    /// X-axis kernel, must be odd
1088    x_axis_kernel_size: u32,
1089    /// X-axis sigma, must > 0, not subnormal, and not NaN
1090    x_axis_sigma: f32,
1091    /// Y-axis kernel, must be odd
1092    y_axis_kernel_size: u32,
1093    /// Y-axis sigma, must > 0, not subnormal, and not NaN
1094    y_axis_sigma: f32,
1095}
1096
1097impl GaussianBlurParameters {
1098    /// Built-in smoothing kernel with size 3.
1099    pub const SMOOTHING_3: GaussianBlurParameters = GaussianBlurParameters {
1100        x_axis_kernel_size: 3,
1101        x_axis_sigma: 0.8,
1102        y_axis_kernel_size: 3,
1103        y_axis_sigma: 0.8,
1104    };
1105
1106    /// Built-in smoothing kernel with size 5.
1107    pub const SMOOTHING_5: GaussianBlurParameters = GaussianBlurParameters {
1108        x_axis_kernel_size: 5,
1109        x_axis_sigma: 1.1,
1110        y_axis_kernel_size: 5,
1111        y_axis_sigma: 1.1,
1112    };
1113
1114    /// Built-in smoothing kernel with size 7.
1115    pub const SMOOTHING_7: GaussianBlurParameters = GaussianBlurParameters {
1116        x_axis_kernel_size: 7,
1117        x_axis_sigma: 1.4,
1118        y_axis_kernel_size: 7,
1119        y_axis_sigma: 1.4,
1120    };
1121
1122    /// Creates a new parameters set from radius only.
1123    pub fn new_from_radius(radius: f32) -> GaussianBlurParameters {
1124        // Previous implementation was allowing passing 0 so we'll allow here also.
1125        assert!(radius >= 0.0);
1126        if radius != 0. {
1127            assert!(
1128                radius.is_normal(),
1129                "Radius do not allow infinities, NaNs or subnormals"
1130            );
1131        }
1132        GaussianBlurParameters::new_from_kernel_size(radius * 2. + 1.)
1133    }
1134
1135    /// Creates a new parameters set from kernel size only.
1136    ///
1137    /// Kernel size will be rounded to nearest odd, and used with fraction
1138    /// to compute accurate required sigma.
1139    pub fn new_from_kernel_size(kernel_size: f32) -> GaussianBlurParameters {
1140        assert!(
1141            kernel_size > 0.,
1142            "Kernel size do not allow infinities, zeros, NaNs or subnormals or negatives"
1143        );
1144        assert!(
1145            kernel_size.is_normal(),
1146            "Kernel size do not allow infinities, zeros, NaNs or subnormals or negatives"
1147        );
1148        let i_kernel_size = GaussianBlurParameters::round_to_nearest_odd(kernel_size);
1149        assert_ne!(i_kernel_size % 2, 0, "Kernel size must be odd");
1150        let v_sigma = GaussianBlurParameters::sigma_size(kernel_size);
1151        GaussianBlurParameters {
1152            x_axis_kernel_size: i_kernel_size,
1153            x_axis_sigma: v_sigma,
1154            y_axis_kernel_size: i_kernel_size,
1155            y_axis_sigma: v_sigma,
1156        }
1157    }
1158
1159    /// Creates a new anisotropic parameter set from kernel sizes
1160    ///
1161    /// Kernel size will be rounded to nearest odd, and used with fraction
1162    /// to compute accurate required sigma.
1163    pub fn new_anisotropic_kernel_size(
1164        x_axis_kernel_size: f32,
1165        y_axis_kernel_size: f32,
1166    ) -> GaussianBlurParameters {
1167        assert!(
1168            x_axis_kernel_size > 0.,
1169            "Kernel size do not allow infinities, zeros, NaNs or subnormals or negatives"
1170        );
1171        assert!(
1172            y_axis_kernel_size.is_normal(),
1173            "Kernel size do not allow infinities, zeros, NaNs or subnormals or negatives"
1174        );
1175        assert!(
1176            y_axis_kernel_size > 0.,
1177            "Kernel size do not allow infinities, zeros, NaNs or subnormals or negatives"
1178        );
1179        assert!(
1180            y_axis_kernel_size.is_normal(),
1181            "Kernel size do not allow infinities, zeros, NaNs or subnormals or negatives"
1182        );
1183        let x_kernel_size = GaussianBlurParameters::round_to_nearest_odd(x_axis_kernel_size);
1184        assert_ne!(x_kernel_size % 2, 0, "Kernel size must be odd");
1185        let y_kernel_size = GaussianBlurParameters::round_to_nearest_odd(y_axis_kernel_size);
1186        assert_ne!(y_kernel_size % 2, 0, "Kernel size must be odd");
1187        let x_sigma = GaussianBlurParameters::sigma_size(x_axis_kernel_size);
1188        let y_sigma = GaussianBlurParameters::sigma_size(y_axis_kernel_size);
1189        GaussianBlurParameters {
1190            x_axis_kernel_size: x_kernel_size,
1191            x_axis_sigma: x_sigma,
1192            y_axis_kernel_size: y_kernel_size,
1193            y_axis_sigma: y_sigma,
1194        }
1195    }
1196
1197    /// Creates a new parameters set from sigma only
1198    pub fn new_from_sigma(sigma: f32) -> GaussianBlurParameters {
1199        assert!(
1200            sigma.is_normal(),
1201            "Sigma cannot be NaN, Infinities, subnormal or zero"
1202        );
1203        assert!(sigma > 0.0, "Sigma must be positive");
1204        let kernel_size = GaussianBlurParameters::kernel_size_from_sigma(sigma);
1205        GaussianBlurParameters {
1206            x_axis_kernel_size: kernel_size,
1207            x_axis_sigma: sigma,
1208            y_axis_kernel_size: kernel_size,
1209            y_axis_sigma: sigma,
1210        }
1211    }
1212
1213    #[inline]
1214    fn round_to_nearest_odd(x: f32) -> u32 {
1215        let n = x.round() as u32;
1216        if n % 2 != 0 {
1217            n
1218        } else {
1219            let lower = n - 1;
1220            let upper = n + 1;
1221
1222            let dist_lower = (x - lower as f32).abs();
1223            let dist_upper = (x - upper as f32).abs();
1224
1225            if dist_lower <= dist_upper {
1226                lower
1227            } else {
1228                upper
1229            }
1230        }
1231    }
1232
1233    fn sigma_size(kernel_size: f32) -> f32 {
1234        let safe_kernel_size = if kernel_size <= 1. { 0.8 } else { kernel_size };
1235        0.3 * ((safe_kernel_size - 1.) * 0.5 - 1.) + 0.8
1236    }
1237
1238    fn kernel_size_from_sigma(sigma: f32) -> u32 {
1239        let possible_size = (((((sigma - 0.8) / 0.3) + 1.) * 2.) + 1.).max(3.) as u32;
1240        if possible_size % 2 == 0 {
1241            return possible_size + 1;
1242        }
1243        possible_size
1244    }
1245}
1246
1247pub(crate) fn gaussian_blur_dyn_image(
1248    image: &DynamicImage,
1249    parameters: GaussianBlurParameters,
1250) -> DynamicImage {
1251    let x_axis_kernel = get_gaussian_kernel_1d(
1252        parameters.x_axis_kernel_size as usize,
1253        parameters.x_axis_sigma,
1254    );
1255
1256    let y_axis_kernel = get_gaussian_kernel_1d(
1257        parameters.y_axis_kernel_size as usize,
1258        parameters.y_axis_sigma,
1259    );
1260
1261    let filter_image_size = FilterImageSize {
1262        width: image.width() as usize,
1263        height: image.height() as usize,
1264    };
1265
1266    let mut target = match image {
1267        DynamicImage::ImageLuma8(img) => {
1268            let mut dest_image = vec![0u8; img.len()];
1269            filter_2d_sep_plane(
1270                img.as_raw(),
1271                &mut dest_image,
1272                filter_image_size,
1273                &x_axis_kernel,
1274                &y_axis_kernel,
1275            )
1276            .unwrap();
1277            DynamicImage::ImageLuma8(
1278                GrayImage::from_raw(img.width(), img.height(), dest_image).unwrap(),
1279            )
1280        }
1281        DynamicImage::ImageLumaA8(img) => {
1282            let mut dest_image = vec![0u8; img.len()];
1283            filter_2d_sep_la(
1284                img.as_raw(),
1285                &mut dest_image,
1286                filter_image_size,
1287                &x_axis_kernel,
1288                &y_axis_kernel,
1289            )
1290            .unwrap();
1291            DynamicImage::ImageLumaA8(
1292                GrayAlphaImage::from_raw(img.width(), img.height(), dest_image).unwrap(),
1293            )
1294        }
1295        DynamicImage::ImageRgb8(img) => {
1296            let mut dest_image = vec![0u8; img.len()];
1297            filter_2d_sep_rgb(
1298                img.as_raw(),
1299                &mut dest_image,
1300                filter_image_size,
1301                &x_axis_kernel,
1302                &y_axis_kernel,
1303            )
1304            .unwrap();
1305            DynamicImage::ImageRgb8(
1306                RgbImage::from_raw(img.width(), img.height(), dest_image).unwrap(),
1307            )
1308        }
1309        DynamicImage::ImageRgba8(img) => {
1310            let mut dest_image = vec![0u8; img.len()];
1311            filter_2d_sep_rgba(
1312                img.as_raw(),
1313                &mut dest_image,
1314                filter_image_size,
1315                &x_axis_kernel,
1316                &y_axis_kernel,
1317            )
1318            .unwrap();
1319            DynamicImage::ImageRgba8(
1320                RgbaImage::from_raw(img.width(), img.height(), dest_image).unwrap(),
1321            )
1322        }
1323        DynamicImage::ImageLuma16(img) => {
1324            let mut dest_image = vec![0u16; img.len()];
1325            filter_2d_sep_plane_u16(
1326                img.as_raw(),
1327                &mut dest_image,
1328                filter_image_size,
1329                &x_axis_kernel,
1330                &y_axis_kernel,
1331            )
1332            .unwrap();
1333            DynamicImage::ImageLuma16(
1334                Gray16Image::from_raw(img.width(), img.height(), dest_image).unwrap(),
1335            )
1336        }
1337        DynamicImage::ImageLumaA16(img) => {
1338            let mut dest_image = vec![0u16; img.len()];
1339            filter_2d_sep_la_u16(
1340                img.as_raw(),
1341                &mut dest_image,
1342                filter_image_size,
1343                &x_axis_kernel,
1344                &y_axis_kernel,
1345            )
1346            .unwrap();
1347            DynamicImage::ImageLumaA16(
1348                GrayAlpha16Image::from_raw(img.width(), img.height(), dest_image).unwrap(),
1349            )
1350        }
1351        DynamicImage::ImageRgb16(img) => {
1352            let mut dest_image = vec![0u16; img.len()];
1353            filter_2d_sep_rgb_u16(
1354                img.as_raw(),
1355                &mut dest_image,
1356                filter_image_size,
1357                &x_axis_kernel,
1358                &y_axis_kernel,
1359            )
1360            .unwrap();
1361            DynamicImage::ImageRgb16(
1362                Rgb16Image::from_raw(img.width(), img.height(), dest_image).unwrap(),
1363            )
1364        }
1365        DynamicImage::ImageRgba16(img) => {
1366            let mut dest_image = vec![0u16; img.len()];
1367            filter_2d_sep_rgba_u16(
1368                img.as_raw(),
1369                &mut dest_image,
1370                filter_image_size,
1371                &x_axis_kernel,
1372                &y_axis_kernel,
1373            )
1374            .unwrap();
1375            DynamicImage::ImageRgba16(
1376                Rgba16Image::from_raw(img.width(), img.height(), dest_image).unwrap(),
1377            )
1378        }
1379        DynamicImage::ImageRgb32F(img) => {
1380            let mut dest_image = vec![0f32; img.len()];
1381            filter_2d_sep_rgb_f32(
1382                img.as_raw(),
1383                &mut dest_image,
1384                filter_image_size,
1385                &x_axis_kernel,
1386                &y_axis_kernel,
1387            )
1388            .unwrap();
1389            DynamicImage::ImageRgb32F(
1390                Rgb32FImage::from_raw(img.width(), img.height(), dest_image).unwrap(),
1391            )
1392        }
1393        DynamicImage::ImageRgba32F(img) => {
1394            let mut dest_image = vec![0f32; img.len()];
1395            filter_2d_sep_rgba_f32(
1396                img.as_raw(),
1397                &mut dest_image,
1398                filter_image_size,
1399                &x_axis_kernel,
1400                &y_axis_kernel,
1401            )
1402            .unwrap();
1403            DynamicImage::ImageRgba32F(
1404                Rgba32FImage::from_raw(img.width(), img.height(), dest_image).unwrap(),
1405            )
1406        }
1407    };
1408
1409    // Must succeed.
1410    let _ = target.set_color_space(image.color_space());
1411    target
1412}
1413
1414fn gaussian_blur_indirect<I: GenericImageView>(
1415    image: &I,
1416    parameters: GaussianBlurParameters,
1417) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::Subpixel>>
1418where
1419    I::Pixel: 'static,
1420{
1421    match I::Pixel::CHANNEL_COUNT {
1422        1 => gaussian_blur_indirect_impl::<I, 1>(image, parameters),
1423        2 => gaussian_blur_indirect_impl::<I, 2>(image, parameters),
1424        3 => gaussian_blur_indirect_impl::<I, 3>(image, parameters),
1425        4 => gaussian_blur_indirect_impl::<I, 4>(image, parameters),
1426        _ => unimplemented!(),
1427    }
1428}
1429
1430fn gaussian_blur_indirect_impl<I: GenericImageView, const CN: usize>(
1431    image: &I,
1432    parameters: GaussianBlurParameters,
1433) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::Subpixel>>
1434where
1435    I::Pixel: 'static,
1436{
1437    let mut transient = vec![0f32; image.width() as usize * image.height() as usize * CN];
1438    for (pixel, dst) in image.pixels().zip(transient.chunks_exact_mut(CN)) {
1439        let px = pixel.2.channels();
1440        match CN {
1441            1 => {
1442                dst[0] = NumCast::from(px[0]).unwrap();
1443            }
1444            2 => {
1445                dst[0] = NumCast::from(px[0]).unwrap();
1446                dst[1] = NumCast::from(px[1]).unwrap();
1447            }
1448            3 => {
1449                dst[0] = NumCast::from(px[0]).unwrap();
1450                dst[1] = NumCast::from(px[1]).unwrap();
1451                dst[2] = NumCast::from(px[2]).unwrap();
1452            }
1453            4 => {
1454                dst[0] = NumCast::from(px[0]).unwrap();
1455                dst[1] = NumCast::from(px[1]).unwrap();
1456                dst[2] = NumCast::from(px[2]).unwrap();
1457                dst[3] = NumCast::from(px[3]).unwrap();
1458            }
1459            _ => unreachable!(),
1460        }
1461    }
1462
1463    let mut transient_dst = vec![0.; image.width() as usize * image.height() as usize * CN];
1464
1465    let x_axis_kernel = get_gaussian_kernel_1d(
1466        parameters.x_axis_kernel_size as usize,
1467        parameters.x_axis_sigma,
1468    );
1469    let y_axis_kernel = get_gaussian_kernel_1d(
1470        parameters.y_axis_kernel_size as usize,
1471        parameters.y_axis_sigma,
1472    );
1473
1474    let filter_image_size = FilterImageSize {
1475        width: image.width() as usize,
1476        height: image.height() as usize,
1477    };
1478
1479    match CN {
1480        1 => {
1481            filter_2d_sep_plane_f32(
1482                &transient,
1483                &mut transient_dst,
1484                filter_image_size,
1485                &x_axis_kernel,
1486                &y_axis_kernel,
1487            )
1488            .unwrap();
1489        }
1490        2 => {
1491            filter_2d_sep_la_f32(
1492                &transient,
1493                &mut transient_dst,
1494                filter_image_size,
1495                &x_axis_kernel,
1496                &y_axis_kernel,
1497            )
1498            .unwrap();
1499        }
1500        3 => {
1501            filter_2d_sep_rgb_f32(
1502                &transient,
1503                &mut transient_dst,
1504                filter_image_size,
1505                &x_axis_kernel,
1506                &y_axis_kernel,
1507            )
1508            .unwrap();
1509        }
1510        4 => {
1511            filter_2d_sep_rgba_f32(
1512                &transient,
1513                &mut transient_dst,
1514                filter_image_size,
1515                &x_axis_kernel,
1516                &y_axis_kernel,
1517            )
1518            .unwrap();
1519        }
1520        _ => unreachable!(),
1521    }
1522
1523    let mut out = image.buffer_like();
1524    for (dst, src) in out.pixels_mut().zip(transient_dst.chunks_exact_mut(CN)) {
1525        match CN {
1526            1 => {
1527                let v0 = NumCast::from(FloatNearest(src[0])).unwrap();
1528                #[allow(deprecated)]
1529                let t = Pixel::from_channels(v0, v0, v0, v0);
1530                *dst = t;
1531            }
1532            2 => {
1533                let v0 = NumCast::from(FloatNearest(src[0])).unwrap();
1534                let v1 = NumCast::from(FloatNearest(src[1])).unwrap();
1535                #[allow(deprecated)]
1536                let t = Pixel::from_channels(v0, v1, v0, v0);
1537                *dst = t;
1538            }
1539            3 => {
1540                let v0 = NumCast::from(FloatNearest(src[0])).unwrap();
1541                let v1 = NumCast::from(FloatNearest(src[1])).unwrap();
1542                let v2 = NumCast::from(FloatNearest(src[2])).unwrap();
1543                #[allow(deprecated)]
1544                let t = Pixel::from_channels(v0, v1, v2, v0);
1545                *dst = t;
1546            }
1547            4 => {
1548                let v0 = NumCast::from(FloatNearest(src[0])).unwrap();
1549                let v1 = NumCast::from(FloatNearest(src[1])).unwrap();
1550                let v2 = NumCast::from(FloatNearest(src[2])).unwrap();
1551                let v3 = NumCast::from(FloatNearest(src[3])).unwrap();
1552                #[allow(deprecated)]
1553                let t = Pixel::from_channels(v0, v1, v2, v3);
1554                *dst = t;
1555            }
1556            _ => unreachable!(),
1557        }
1558    }
1559
1560    out
1561}
1562
1563/// Performs an unsharpen mask on the supplied image.
1564///
1565/// # Arguments:
1566///
1567/// * `sigma` - is the amount to blur the image by.
1568/// * `threshold` - is the threshold for minimal brightness change that will be sharpened.
1569///
1570/// This method typically assumes that the input is scene-linear light.
1571/// If it is not, color distortion may occur.
1572///
1573/// See [Digital unsharp masking](https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking) for more information.
1574pub fn unsharpen<I, P, S>(image: &I, sigma: f32, threshold: i32) -> ImageBuffer<P, Vec<S>>
1575where
1576    I: GenericImageView<Pixel = P>,
1577    P: Pixel<Subpixel = S> + 'static,
1578    S: Primitive + 'static,
1579{
1580    let mut tmp = blur_advanced(image, GaussianBlurParameters::new_from_sigma(sigma));
1581
1582    let max = S::DEFAULT_MAX_VALUE;
1583    let max: i32 = NumCast::from(max).unwrap();
1584    let (width, height) = image.dimensions();
1585
1586    for y in 0..height {
1587        for x in 0..width {
1588            let a = image.get_pixel(x, y);
1589            let b = tmp.get_pixel_mut(x, y);
1590
1591            let p = a.map2(b, |c, d| {
1592                let ic: i32 = NumCast::from(c).unwrap();
1593                let id: i32 = NumCast::from(d).unwrap();
1594
1595                let diff = ic - id;
1596
1597                if diff.abs() > threshold {
1598                    let e = clamp(ic + diff, 0, max); // FIXME what does this do for f32? clamp 0-1 integers??
1599
1600                    NumCast::from(e).unwrap()
1601                } else {
1602                    c
1603                }
1604            });
1605
1606            *b = p;
1607        }
1608    }
1609
1610    tmp
1611}
1612
1613#[cfg(test)]
1614mod tests {
1615    use super::{resize, sample_bilinear, sample_nearest, FilterType};
1616    use crate::{GenericImageView, ImageBuffer, RgbImage};
1617    #[cfg(feature = "benchmarks")]
1618    use test;
1619
1620    #[bench]
1621    #[cfg(all(feature = "benchmarks", feature = "png"))]
1622    fn bench_resize(b: &mut test::Bencher) {
1623        use std::path::Path;
1624        let img = crate::open(Path::new("./examples/fractal.png")).unwrap();
1625        b.iter(|| {
1626            test::black_box(resize(&img, 200, 200, FilterType::Nearest));
1627        });
1628        b.bytes = 800 * 800 * 3 + 200 * 200 * 3;
1629    }
1630
1631    #[test]
1632    #[cfg(feature = "png")]
1633    fn test_resize_same_size() {
1634        use std::path::Path;
1635        let img = crate::open(Path::new("./examples/fractal.png")).unwrap();
1636        let resize = img.resize(img.width(), img.height(), FilterType::Triangle);
1637        assert!(img.pixels().eq(resize.pixels()));
1638    }
1639
1640    #[test]
1641    #[cfg(feature = "png")]
1642    fn test_sample_bilinear() {
1643        use std::path::Path;
1644        let img = crate::open(Path::new("./examples/fractal.png")).unwrap();
1645        assert!(sample_bilinear(&img, 0., 0.).is_some());
1646        assert!(sample_bilinear(&img, 1., 0.).is_some());
1647        assert!(sample_bilinear(&img, 0., 1.).is_some());
1648        assert!(sample_bilinear(&img, 1., 1.).is_some());
1649        assert!(sample_bilinear(&img, 0.5, 0.5).is_some());
1650
1651        assert!(sample_bilinear(&img, 1.2, 0.5).is_none());
1652        assert!(sample_bilinear(&img, 0.5, 1.2).is_none());
1653        assert!(sample_bilinear(&img, 1.2, 1.2).is_none());
1654
1655        assert!(sample_bilinear(&img, -0.1, 0.2).is_none());
1656        assert!(sample_bilinear(&img, 0.2, -0.1).is_none());
1657        assert!(sample_bilinear(&img, -0.1, -0.1).is_none());
1658    }
1659    #[test]
1660    #[cfg(feature = "png")]
1661    fn test_sample_nearest() {
1662        use std::path::Path;
1663        let img = crate::open(Path::new("./examples/fractal.png")).unwrap();
1664        assert!(sample_nearest(&img, 0., 0.).is_some());
1665        assert!(sample_nearest(&img, 1., 0.).is_some());
1666        assert!(sample_nearest(&img, 0., 1.).is_some());
1667        assert!(sample_nearest(&img, 1., 1.).is_some());
1668        assert!(sample_nearest(&img, 0.5, 0.5).is_some());
1669
1670        assert!(sample_nearest(&img, 1.2, 0.5).is_none());
1671        assert!(sample_nearest(&img, 0.5, 1.2).is_none());
1672        assert!(sample_nearest(&img, 1.2, 1.2).is_none());
1673
1674        assert!(sample_nearest(&img, -0.1, 0.2).is_none());
1675        assert!(sample_nearest(&img, 0.2, -0.1).is_none());
1676        assert!(sample_nearest(&img, -0.1, -0.1).is_none());
1677    }
1678    #[test]
1679    fn test_sample_bilinear_correctness() {
1680        use crate::Rgba;
1681        let img = ImageBuffer::from_fn(2, 2, |x, y| match (x, y) {
1682            (0, 0) => Rgba([255, 0, 0, 0]),
1683            (0, 1) => Rgba([0, 255, 0, 0]),
1684            (1, 0) => Rgba([0, 0, 255, 0]),
1685            (1, 1) => Rgba([0, 0, 0, 255]),
1686            _ => panic!(),
1687        });
1688        assert_eq!(sample_bilinear(&img, 0.5, 0.5), Some(Rgba([64; 4])));
1689        assert_eq!(sample_bilinear(&img, 0.0, 0.0), Some(Rgba([255, 0, 0, 0])));
1690        assert_eq!(sample_bilinear(&img, 0.0, 1.0), Some(Rgba([0, 255, 0, 0])));
1691        assert_eq!(sample_bilinear(&img, 1.0, 0.0), Some(Rgba([0, 0, 255, 0])));
1692        assert_eq!(sample_bilinear(&img, 1.0, 1.0), Some(Rgba([0, 0, 0, 255])));
1693
1694        assert_eq!(
1695            sample_bilinear(&img, 0.5, 0.0),
1696            Some(Rgba([128, 0, 128, 0]))
1697        );
1698        assert_eq!(
1699            sample_bilinear(&img, 0.0, 0.5),
1700            Some(Rgba([128, 128, 0, 0]))
1701        );
1702        assert_eq!(
1703            sample_bilinear(&img, 0.5, 1.0),
1704            Some(Rgba([0, 128, 0, 128]))
1705        );
1706        assert_eq!(
1707            sample_bilinear(&img, 1.0, 0.5),
1708            Some(Rgba([0, 0, 128, 128]))
1709        );
1710    }
1711    #[bench]
1712    #[cfg(feature = "benchmarks")]
1713    fn bench_sample_bilinear(b: &mut test::Bencher) {
1714        use crate::Rgba;
1715        let img = ImageBuffer::from_fn(2, 2, |x, y| match (x, y) {
1716            (0, 0) => Rgba([255, 0, 0, 0]),
1717            (0, 1) => Rgba([0, 255, 0, 0]),
1718            (1, 0) => Rgba([0, 0, 255, 0]),
1719            (1, 1) => Rgba([0, 0, 0, 255]),
1720            _ => panic!(),
1721        });
1722        b.iter(|| {
1723            sample_bilinear(&img, test::black_box(0.5), test::black_box(0.5));
1724        });
1725    }
1726    #[test]
1727    fn test_sample_nearest_correctness() {
1728        use crate::Rgba;
1729        let img = ImageBuffer::from_fn(2, 2, |x, y| match (x, y) {
1730            (0, 0) => Rgba([255, 0, 0, 0]),
1731            (0, 1) => Rgba([0, 255, 0, 0]),
1732            (1, 0) => Rgba([0, 0, 255, 0]),
1733            (1, 1) => Rgba([0, 0, 0, 255]),
1734            _ => panic!(),
1735        });
1736
1737        assert_eq!(sample_nearest(&img, 0.0, 0.0), Some(Rgba([255, 0, 0, 0])));
1738        assert_eq!(sample_nearest(&img, 0.0, 1.0), Some(Rgba([0, 255, 0, 0])));
1739        assert_eq!(sample_nearest(&img, 1.0, 0.0), Some(Rgba([0, 0, 255, 0])));
1740        assert_eq!(sample_nearest(&img, 1.0, 1.0), Some(Rgba([0, 0, 0, 255])));
1741
1742        assert_eq!(sample_nearest(&img, 0.5, 0.5), Some(Rgba([0, 0, 0, 255])));
1743        assert_eq!(sample_nearest(&img, 0.5, 0.0), Some(Rgba([0, 0, 255, 0])));
1744        assert_eq!(sample_nearest(&img, 0.0, 0.5), Some(Rgba([0, 255, 0, 0])));
1745        assert_eq!(sample_nearest(&img, 0.5, 1.0), Some(Rgba([0, 0, 0, 255])));
1746        assert_eq!(sample_nearest(&img, 1.0, 0.5), Some(Rgba([0, 0, 0, 255])));
1747    }
1748
1749    #[bench]
1750    #[cfg(all(feature = "benchmarks", feature = "tiff"))]
1751    fn bench_resize_same_size(b: &mut test::Bencher) {
1752        let path = concat!(
1753            env!("CARGO_MANIFEST_DIR"),
1754            "/tests/images/tiff/testsuite/mandrill.tiff"
1755        );
1756        let image = crate::open(path).unwrap();
1757        b.iter(|| {
1758            test::black_box(image.resize(image.width(), image.height(), FilterType::CatmullRom));
1759        });
1760        b.bytes = u64::from(image.width() * image.height() * 3);
1761    }
1762
1763    #[test]
1764    fn test_issue_186() {
1765        let img: RgbImage = ImageBuffer::new(100, 100);
1766        let _ = resize(&img, 50, 50, FilterType::Lanczos3);
1767    }
1768
1769    #[bench]
1770    #[cfg(all(feature = "benchmarks", feature = "tiff"))]
1771    fn bench_thumbnail(b: &mut test::Bencher) {
1772        let path = concat!(
1773            env!("CARGO_MANIFEST_DIR"),
1774            "/tests/images/tiff/testsuite/mandrill.tiff"
1775        );
1776        let image = crate::open(path).unwrap();
1777        b.iter(|| {
1778            test::black_box(image.thumbnail(256, 256));
1779        });
1780        b.bytes = 512 * 512 * 4 + 256 * 256 * 4;
1781    }
1782
1783    #[bench]
1784    #[cfg(all(feature = "benchmarks", feature = "tiff"))]
1785    fn bench_thumbnail_upsize(b: &mut test::Bencher) {
1786        let path = concat!(
1787            env!("CARGO_MANIFEST_DIR"),
1788            "/tests/images/tiff/testsuite/mandrill.tiff"
1789        );
1790        let image = crate::open(path).unwrap().thumbnail(256, 256);
1791        b.iter(|| {
1792            test::black_box(image.thumbnail(512, 512));
1793        });
1794        b.bytes = 512 * 512 * 4 + 256 * 256 * 4;
1795    }
1796
1797    #[bench]
1798    #[cfg(all(feature = "benchmarks", feature = "tiff"))]
1799    fn bench_thumbnail_upsize_irregular(b: &mut test::Bencher) {
1800        let path = concat!(
1801            env!("CARGO_MANIFEST_DIR"),
1802            "/tests/images/tiff/testsuite/mandrill.tiff"
1803        );
1804        let image = crate::open(path).unwrap().thumbnail(193, 193);
1805        b.iter(|| {
1806            test::black_box(image.thumbnail(256, 256));
1807        });
1808        b.bytes = 193 * 193 * 4 + 256 * 256 * 4;
1809    }
1810
1811    #[test]
1812    #[cfg(feature = "png")]
1813    fn resize_transparent_image() {
1814        use super::FilterType::{CatmullRom, Gaussian, Lanczos3, Nearest, Triangle};
1815        use crate::imageops::crop_imm;
1816        use crate::RgbaImage;
1817
1818        fn assert_resize(image: &RgbaImage, filter: FilterType) {
1819            let resized = resize(image, 16, 16, filter);
1820            let cropped = crop_imm(&resized, 5, 5, 6, 6).to_image();
1821            for pixel in cropped.pixels() {
1822                let alpha = pixel.0[3];
1823                assert!(
1824                    alpha != 254 && alpha != 253,
1825                    "alpha value: {alpha}, {filter:?}"
1826                );
1827            }
1828        }
1829
1830        let path = concat!(
1831            env!("CARGO_MANIFEST_DIR"),
1832            "/tests/images/png/transparency/tp1n3p08.png"
1833        );
1834        let img = crate::open(path).unwrap();
1835        let rgba8 = img.as_rgba8().unwrap();
1836        let filters = &[Nearest, Triangle, CatmullRom, Gaussian, Lanczos3];
1837        for filter in filters {
1838            assert_resize(rgba8, *filter);
1839        }
1840    }
1841
1842    #[test]
1843    fn bug_1600() {
1844        let image = crate::RgbaImage::from_raw(629, 627, vec![255; 629 * 627 * 4]).unwrap();
1845        let result = resize(&image, 22, 22, FilterType::Lanczos3);
1846        assert!(result.into_raw().into_iter().any(|c| c != 0));
1847    }
1848
1849    #[test]
1850    fn issue_2340() {
1851        let empty = crate::GrayImage::from_raw(1 << 31, 0, vec![]).unwrap();
1852        // Really we're checking that no overflow / outsized allocation happens here.
1853        let result = resize(&empty, 1, 1, FilterType::Lanczos3);
1854        assert!(result.into_raw().into_iter().all(|c| c == 0));
1855        // With the previous strategy before the regression this would allocate 1TB of memory for a
1856        // temporary during the sampling evaluation.
1857        let result = resize(&empty, 256, 256, FilterType::Lanczos3);
1858        assert!(result.into_raw().into_iter().all(|c| c == 0));
1859    }
1860
1861    #[test]
1862    fn issue_2340_refl() {
1863        // Tests the swapped coordinate version of `issue_2340`.
1864        let empty = crate::GrayImage::from_raw(0, 1 << 31, vec![]).unwrap();
1865        let result = resize(&empty, 1, 1, FilterType::Lanczos3);
1866        assert!(result.into_raw().into_iter().all(|c| c == 0));
1867        let result = resize(&empty, 256, 256, FilterType::Lanczos3);
1868        assert!(result.into_raw().into_iter().all(|c| c == 0));
1869    }
1870}