image/imageops/
mod.rs

1//! Image Processing Functions
2use std::cmp;
3
4use crate::image::{GenericImage, GenericImageView, SubImage};
5use crate::traits::{Lerp, Pixel, Primitive};
6
7pub use self::sample::FilterType;
8
9pub use self::sample::FilterType::{CatmullRom, Gaussian, Lanczos3, Nearest, Triangle};
10
11/// Affine transformations
12pub use self::affine::{
13    flip_horizontal, flip_horizontal_in, flip_horizontal_in_place, flip_vertical, flip_vertical_in,
14    flip_vertical_in_place, rotate180, rotate180_in, rotate180_in_place, rotate270, rotate270_in,
15    rotate90, rotate90_in,
16};
17
18/// Image sampling
19pub use self::sample::{
20    blur, filter3x3, interpolate_bilinear, interpolate_nearest, resize, sample_bilinear,
21    sample_nearest, thumbnail, unsharpen,
22};
23
24/// Color operations
25pub use self::colorops::{
26    brighten, contrast, dither, grayscale, grayscale_alpha, grayscale_with_type,
27    grayscale_with_type_alpha, huerotate, index_colors, invert, BiLevel, ColorMap,
28};
29
30mod affine;
31// Public only because of Rust bug:
32// https://github.com/rust-lang/rust/issues/18241
33pub mod colorops;
34mod fast_blur;
35mod sample;
36
37pub use fast_blur::fast_blur;
38
39/// Return a mutable view into an image
40/// The coordinates set the position of the top left corner of the crop.
41pub fn crop<I: GenericImageView>(
42    image: &mut I,
43    x: u32,
44    y: u32,
45    width: u32,
46    height: u32,
47) -> SubImage<&mut I> {
48    let (x, y, width, height) = crop_dimms(image, x, y, width, height);
49    SubImage::new(image, x, y, width, height)
50}
51
52/// Return an immutable view into an image
53/// The coordinates set the position of the top left corner of the crop.
54pub fn crop_imm<I: GenericImageView>(
55    image: &I,
56    x: u32,
57    y: u32,
58    width: u32,
59    height: u32,
60) -> SubImage<&I> {
61    let (x, y, width, height) = crop_dimms(image, x, y, width, height);
62    SubImage::new(image, x, y, width, height)
63}
64
65fn crop_dimms<I: GenericImageView>(
66    image: &I,
67    x: u32,
68    y: u32,
69    width: u32,
70    height: u32,
71) -> (u32, u32, u32, u32) {
72    let (iwidth, iheight) = image.dimensions();
73
74    let x = cmp::min(x, iwidth);
75    let y = cmp::min(y, iheight);
76
77    let height = cmp::min(height, iheight - y);
78    let width = cmp::min(width, iwidth - x);
79
80    (x, y, width, height)
81}
82
83/// Calculate the region that can be copied from top to bottom.
84///
85/// Given image size of bottom and top image, and a point at which we want to place the top image
86/// onto the bottom image, how large can we be? Have to wary of the following issues:
87/// * Top might be larger than bottom
88/// * Overflows in the computation
89/// * Coordinates could be completely out of bounds
90///
91/// The main idea is to make use of inequalities provided by the nature of `saturating_add` and
92/// `saturating_sub`. These intrinsically validate that all resulting coordinates will be in bounds
93/// for both images.
94///
95/// We want that all these coordinate accesses are safe:
96/// 1. `bottom.get_pixel(x + [0..x_range), y + [0..y_range))`
97/// 2. `top.get_pixel([0..x_range), [0..y_range))`
98///
99/// Proof that the function provides the necessary bounds for width. Note that all unaugmented math
100/// operations are to be read in standard arithmetic, not integer arithmetic. Since no direct
101/// integer arithmetic occurs in the implementation, this is unambiguous.
102///
103/// ```text
104/// Three short notes/lemmata:
105/// - Iff `(a - b) <= 0` then `a.saturating_sub(b) = 0`
106/// - Iff `(a - b) >= 0` then `a.saturating_sub(b) = a - b`
107/// - If  `a <= c` then `a.saturating_sub(b) <= c.saturating_sub(b)`
108///
109/// 1.1 We show that if `bottom_width <= x`, then `x_range = 0` therefore `x + [0..x_range)` is empty.
110///
111/// x_range
112///  = (top_width.saturating_add(x).min(bottom_width)).saturating_sub(x)
113/// <= bottom_width.saturating_sub(x)
114///
115/// bottom_width <= x
116/// <==> bottom_width - x <= 0
117/// <==> bottom_width.saturating_sub(x) = 0
118///  ==> x_range <= 0
119///  ==> x_range  = 0
120///
121/// 1.2 If `x < bottom_width` then `x + x_range < bottom_width`
122///
123/// x + x_range
124/// <= x + bottom_width.saturating_sub(x)
125///  = x + (bottom_width - x)
126///  = bottom_width
127///
128/// 2. We show that `x_range <= top_width`
129///
130/// x_range
131///  = (top_width.saturating_add(x).min(bottom_width)).saturating_sub(x)
132/// <= top_width.saturating_add(x).saturating_sub(x)
133/// <= (top_wdith + x).saturating_sub(x)
134///  = top_width (due to `top_width >= 0` and `x >= 0`)
135/// ```
136///
137/// Proof is the same for height.
138#[must_use]
139pub fn overlay_bounds(
140    (bottom_width, bottom_height): (u32, u32),
141    (top_width, top_height): (u32, u32),
142    x: u32,
143    y: u32,
144) -> (u32, u32) {
145    let x_range = top_width
146        .saturating_add(x) // Calculate max coordinate
147        .min(bottom_width) // Restrict to lower width
148        .saturating_sub(x); // Determinate length from start `x`
149    let y_range = top_height
150        .saturating_add(y)
151        .min(bottom_height)
152        .saturating_sub(y);
153    (x_range, y_range)
154}
155
156/// Calculate the region that can be copied from top to bottom.
157///
158/// Given image size of bottom and top image, and a point at which we want to place the top image
159/// onto the bottom image, how large can we be? Have to wary of the following issues:
160/// * Top might be larger than bottom
161/// * Overflows in the computation
162/// * Coordinates could be completely out of bounds
163///
164/// The returned value is of the form:
165///
166/// `(origin_bottom_x, origin_bottom_y, origin_top_x, origin_top_y, x_range, y_range)`
167///
168/// The main idea is to do computations on i64's and then clamp to image dimensions.
169/// In particular, we want to ensure that all these coordinate accesses are safe:
170/// 1. `bottom.get_pixel(origin_bottom_x + [0..x_range), origin_bottom_y + [0..y_range))`
171/// 2. `top.get_pixel(origin_top_y + [0..x_range), origin_top_y + [0..y_range))`
172///
173fn overlay_bounds_ext(
174    (bottom_width, bottom_height): (u32, u32),
175    (top_width, top_height): (u32, u32),
176    x: i64,
177    y: i64,
178) -> (u32, u32, u32, u32, u32, u32) {
179    // Return a predictable value if the two images don't overlap at all.
180    if x > i64::from(bottom_width)
181        || y > i64::from(bottom_height)
182        || x.saturating_add(i64::from(top_width)) <= 0
183        || y.saturating_add(i64::from(top_height)) <= 0
184    {
185        return (0, 0, 0, 0, 0, 0);
186    }
187
188    // Find the maximum x and y coordinates in terms of the bottom image.
189    let max_x = x.saturating_add(i64::from(top_width));
190    let max_y = y.saturating_add(i64::from(top_height));
191
192    // Clip the origin and maximum coordinates to the bounds of the bottom image.
193    // Casting to a u32 is safe because both 0 and `bottom_{width,height}` fit
194    // into 32-bits.
195    let max_inbounds_x = max_x.clamp(0, i64::from(bottom_width)) as u32;
196    let max_inbounds_y = max_y.clamp(0, i64::from(bottom_height)) as u32;
197    let origin_bottom_x = x.clamp(0, i64::from(bottom_width)) as u32;
198    let origin_bottom_y = y.clamp(0, i64::from(bottom_height)) as u32;
199
200    // The range is the difference between the maximum inbounds coordinates and
201    // the clipped origin. Unchecked subtraction is safe here because both are
202    // always positive and `max_inbounds_{x,y}` >= `origin_{x,y}` due to
203    // `top_{width,height}` being >= 0.
204    let x_range = max_inbounds_x - origin_bottom_x;
205    let y_range = max_inbounds_y - origin_bottom_y;
206
207    // If x (or y) is negative, then the origin of the top image is shifted by -x (or -y).
208    let origin_top_x = x.saturating_mul(-1).clamp(0, i64::from(top_width)) as u32;
209    let origin_top_y = y.saturating_mul(-1).clamp(0, i64::from(top_height)) as u32;
210
211    (
212        origin_bottom_x,
213        origin_bottom_y,
214        origin_top_x,
215        origin_top_y,
216        x_range,
217        y_range,
218    )
219}
220
221/// Overlay an image at a given coordinate (x, y)
222pub fn overlay<I, J>(bottom: &mut I, top: &J, x: i64, y: i64)
223where
224    I: GenericImage,
225    J: GenericImageView<Pixel = I::Pixel>,
226{
227    let bottom_dims = bottom.dimensions();
228    let top_dims = top.dimensions();
229
230    // Crop our top image if we're going out of bounds
231    let (origin_bottom_x, origin_bottom_y, origin_top_x, origin_top_y, range_width, range_height) =
232        overlay_bounds_ext(bottom_dims, top_dims, x, y);
233
234    for y in 0..range_height {
235        for x in 0..range_width {
236            let p = top.get_pixel(origin_top_x + x, origin_top_y + y);
237            let mut bottom_pixel = bottom.get_pixel(origin_bottom_x + x, origin_bottom_y + y);
238            bottom_pixel.blend(&p);
239
240            bottom.put_pixel(origin_bottom_x + x, origin_bottom_y + y, bottom_pixel);
241        }
242    }
243}
244
245/// Tile an image by repeating it multiple times
246///
247/// # Examples
248/// ```no_run
249/// use image::{RgbaImage};
250///
251/// let mut img = RgbaImage::new(1920, 1080);
252/// let tile = image::open("tile.png").unwrap();
253///
254/// image::imageops::tile(&mut img, &tile);
255/// img.save("tiled_wallpaper.png").unwrap();
256/// ```
257pub fn tile<I, J>(bottom: &mut I, top: &J)
258where
259    I: GenericImage,
260    J: GenericImageView<Pixel = I::Pixel>,
261{
262    for x in (0..bottom.width()).step_by(top.width() as usize) {
263        for y in (0..bottom.height()).step_by(top.height() as usize) {
264            overlay(bottom, top, i64::from(x), i64::from(y));
265        }
266    }
267}
268
269/// Fill the image with a linear vertical gradient
270///
271/// This function assumes a linear color space.
272///
273/// # Examples
274/// ```no_run
275/// use image::{Rgba, RgbaImage, Pixel};
276///
277/// let mut img = RgbaImage::new(100, 100);
278/// let start = Rgba::from_slice(&[0, 128, 0, 0]);
279/// let end = Rgba::from_slice(&[255, 255, 255, 255]);
280///
281/// image::imageops::vertical_gradient(&mut img, start, end);
282/// img.save("vertical_gradient.png").unwrap();
283pub fn vertical_gradient<S, P, I>(img: &mut I, start: &P, stop: &P)
284where
285    I: GenericImage<Pixel = P>,
286    P: Pixel<Subpixel = S> + 'static,
287    S: Primitive + Lerp + 'static,
288{
289    for y in 0..img.height() {
290        let pixel = start.map2(stop, |a, b| {
291            let y = <S::Ratio as num_traits::NumCast>::from(y).unwrap();
292            let height = <S::Ratio as num_traits::NumCast>::from(img.height() - 1).unwrap();
293            S::lerp(a, b, y / height)
294        });
295
296        for x in 0..img.width() {
297            img.put_pixel(x, y, pixel);
298        }
299    }
300}
301
302/// Fill the image with a linear horizontal gradient
303///
304/// This function assumes a linear color space.
305///
306/// # Examples
307/// ```no_run
308/// use image::{Rgba, RgbaImage, Pixel};
309///
310/// let mut img = RgbaImage::new(100, 100);
311/// let start = Rgba::from_slice(&[0, 128, 0, 0]);
312/// let end = Rgba::from_slice(&[255, 255, 255, 255]);
313///
314/// image::imageops::horizontal_gradient(&mut img, start, end);
315/// img.save("horizontal_gradient.png").unwrap();
316pub fn horizontal_gradient<S, P, I>(img: &mut I, start: &P, stop: &P)
317where
318    I: GenericImage<Pixel = P>,
319    P: Pixel<Subpixel = S> + 'static,
320    S: Primitive + Lerp + 'static,
321{
322    for x in 0..img.width() {
323        let pixel = start.map2(stop, |a, b| {
324            let x = <S::Ratio as num_traits::NumCast>::from(x).unwrap();
325            let width = <S::Ratio as num_traits::NumCast>::from(img.width() - 1).unwrap();
326            S::lerp(a, b, x / width)
327        });
328
329        for y in 0..img.height() {
330            img.put_pixel(x, y, pixel);
331        }
332    }
333}
334
335/// Replace the contents of an image at a given coordinate (x, y)
336pub fn replace<I, J>(bottom: &mut I, top: &J, x: i64, y: i64)
337where
338    I: GenericImage,
339    J: GenericImageView<Pixel = I::Pixel>,
340{
341    let bottom_dims = bottom.dimensions();
342    let top_dims = top.dimensions();
343
344    // Crop our top image if we're going out of bounds
345    let (origin_bottom_x, origin_bottom_y, origin_top_x, origin_top_y, range_width, range_height) =
346        overlay_bounds_ext(bottom_dims, top_dims, x, y);
347
348    for y in 0..range_height {
349        for x in 0..range_width {
350            let p = top.get_pixel(origin_top_x + x, origin_top_y + y);
351            bottom.put_pixel(origin_bottom_x + x, origin_bottom_y + y, p);
352        }
353    }
354}
355
356#[cfg(test)]
357mod tests {
358
359    use super::*;
360    use crate::color::Rgb;
361    use crate::GrayAlphaImage;
362    use crate::GrayImage;
363    use crate::ImageBuffer;
364    use crate::RgbImage;
365    use crate::RgbaImage;
366
367    #[test]
368    fn test_overlay_bounds_ext() {
369        assert_eq!(
370            overlay_bounds_ext((10, 10), (10, 10), 0, 0),
371            (0, 0, 0, 0, 10, 10)
372        );
373        assert_eq!(
374            overlay_bounds_ext((10, 10), (10, 10), 1, 0),
375            (1, 0, 0, 0, 9, 10)
376        );
377        assert_eq!(
378            overlay_bounds_ext((10, 10), (10, 10), 0, 11),
379            (0, 0, 0, 0, 0, 0)
380        );
381        assert_eq!(
382            overlay_bounds_ext((10, 10), (10, 10), -1, 0),
383            (0, 0, 1, 0, 9, 10)
384        );
385        assert_eq!(
386            overlay_bounds_ext((10, 10), (10, 10), -10, 0),
387            (0, 0, 0, 0, 0, 0)
388        );
389        assert_eq!(
390            overlay_bounds_ext((10, 10), (10, 10), 1i64 << 50, 0),
391            (0, 0, 0, 0, 0, 0)
392        );
393        assert_eq!(
394            overlay_bounds_ext((10, 10), (10, 10), -(1i64 << 50), 0),
395            (0, 0, 0, 0, 0, 0)
396        );
397        assert_eq!(
398            overlay_bounds_ext((10, 10), (u32::MAX, 10), 10 - i64::from(u32::MAX), 0),
399            (0, 0, u32::MAX - 10, 0, 10, 10)
400        );
401    }
402
403    #[test]
404    /// Test that images written into other images works
405    fn test_image_in_image() {
406        let mut target = ImageBuffer::new(32, 32);
407        let source = ImageBuffer::from_pixel(16, 16, Rgb([255u8, 0, 0]));
408        overlay(&mut target, &source, 0, 0);
409        assert!(*target.get_pixel(0, 0) == Rgb([255u8, 0, 0]));
410        assert!(*target.get_pixel(15, 0) == Rgb([255u8, 0, 0]));
411        assert!(*target.get_pixel(16, 0) == Rgb([0u8, 0, 0]));
412        assert!(*target.get_pixel(0, 15) == Rgb([255u8, 0, 0]));
413        assert!(*target.get_pixel(0, 16) == Rgb([0u8, 0, 0]));
414    }
415
416    #[test]
417    /// Test that images written outside of a frame doesn't blow up
418    fn test_image_in_image_outside_of_bounds() {
419        let mut target = ImageBuffer::new(32, 32);
420        let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
421        overlay(&mut target, &source, 1, 1);
422        assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
423        assert!(*target.get_pixel(1, 1) == Rgb([255u8, 0, 0]));
424        assert!(*target.get_pixel(31, 31) == Rgb([255u8, 0, 0]));
425    }
426
427    #[test]
428    /// Test that images written to coordinates out of the frame doesn't blow up
429    /// (issue came up in #848)
430    fn test_image_outside_image_no_wrap_around() {
431        let mut target = ImageBuffer::new(32, 32);
432        let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
433        overlay(&mut target, &source, 33, 33);
434        assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
435        assert!(*target.get_pixel(1, 1) == Rgb([0, 0, 0]));
436        assert!(*target.get_pixel(31, 31) == Rgb([0, 0, 0]));
437    }
438
439    #[test]
440    /// Test that images written to coordinates with overflow works
441    fn test_image_coordinate_overflow() {
442        let mut target = ImageBuffer::new(16, 16);
443        let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
444        // Overflows to 'sane' coordinates but top is larger than bot.
445        overlay(
446            &mut target,
447            &source,
448            i64::from(u32::MAX - 31),
449            i64::from(u32::MAX - 31),
450        );
451        assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
452        assert!(*target.get_pixel(1, 1) == Rgb([0, 0, 0]));
453        assert!(*target.get_pixel(15, 15) == Rgb([0, 0, 0]));
454    }
455
456    use super::{horizontal_gradient, vertical_gradient};
457
458    #[test]
459    /// Test that horizontal gradients are correctly generated
460    fn test_image_horizontal_gradient_limits() {
461        let mut img = ImageBuffer::new(100, 1);
462
463        let start = Rgb([0u8, 128, 0]);
464        let end = Rgb([255u8, 255, 255]);
465
466        horizontal_gradient(&mut img, &start, &end);
467
468        assert_eq!(img.get_pixel(0, 0), &start);
469        assert_eq!(img.get_pixel(img.width() - 1, 0), &end);
470    }
471
472    #[test]
473    /// Test that vertical gradients are correctly generated
474    fn test_image_vertical_gradient_limits() {
475        let mut img = ImageBuffer::new(1, 100);
476
477        let start = Rgb([0u8, 128, 0]);
478        let end = Rgb([255u8, 255, 255]);
479
480        vertical_gradient(&mut img, &start, &end);
481
482        assert_eq!(img.get_pixel(0, 0), &start);
483        assert_eq!(img.get_pixel(0, img.height() - 1), &end);
484    }
485
486    #[test]
487    /// Test blur doesn't panic when passed 0.0
488    fn test_blur_zero() {
489        let image = RgbaImage::new(50, 50);
490        let _ = blur(&image, 0.0);
491    }
492
493    #[test]
494    /// Test fast blur doesn't panic when passed 0.0
495    fn test_fast_blur_zero() {
496        let image = RgbaImage::new(50, 50);
497        let _ = fast_blur(&image, 0.0);
498    }
499
500    #[test]
501    /// Test fast blur doesn't panic when passed negative numbers
502    fn test_fast_blur_negative() {
503        let image = RgbaImage::new(50, 50);
504        let _ = fast_blur(&image, -1.0);
505    }
506
507    #[test]
508    /// Test fast blur doesn't panic when sigma produces boxes larger than the image
509    fn test_fast_large_sigma() {
510        let image = RgbaImage::new(1, 1);
511        let _ = fast_blur(&image, 50.0);
512    }
513
514    #[test]
515    /// Test blur doesn't panic when passed an empty image (any direction)
516    fn test_fast_blur_empty() {
517        let image = RgbaImage::new(0, 0);
518        let _ = fast_blur(&image, 1.0);
519        let image = RgbaImage::new(20, 0);
520        let _ = fast_blur(&image, 1.0);
521        let image = RgbaImage::new(0, 20);
522        let _ = fast_blur(&image, 1.0);
523    }
524
525    #[test]
526    /// Test fast blur works with 3 channels
527    fn test_fast_blur_3_channels() {
528        let image = RgbImage::new(50, 50);
529        let _ = fast_blur(&image, 1.0);
530    }
531
532    #[test]
533    /// Test fast blur works with 2 channels
534    fn test_fast_blur_2_channels() {
535        let image = GrayAlphaImage::new(50, 50);
536        let _ = fast_blur(&image, 1.0);
537    }
538
539    #[test]
540    /// Test fast blur works with 1 channel
541    fn test_fast_blur_1_channels() {
542        let image = GrayImage::new(50, 50);
543        let _ = fast_blur(&image, 1.0);
544    }
545
546    #[test]
547    #[cfg(feature = "tiff")]
548    fn fast_blur_approximates_gaussian_blur_well() {
549        let path = concat!(
550            env!("CARGO_MANIFEST_DIR"),
551            "/tests/images/tiff/testsuite/rgb-3c-16b.tiff"
552        );
553        let image = crate::open(path).unwrap();
554        let image_blurred_gauss = image.blur(50.0).to_rgb8();
555        let image_blurred_gauss_samples = image_blurred_gauss.as_flat_samples();
556        let image_blurred_gauss_bytes = image_blurred_gauss_samples.as_slice();
557        let image_blurred_fast = image.fast_blur(50.0).to_rgb8();
558        let image_blurred_fast_samples = image_blurred_fast.as_flat_samples();
559        let image_blurred_fast_bytes = image_blurred_fast_samples.as_slice();
560
561        let error = image_blurred_gauss_bytes
562            .iter()
563            .zip(image_blurred_fast_bytes.iter())
564            .map(|(a, b)| ((*a as f32 - *b as f32) / (*a as f32)))
565            .sum::<f32>()
566            / (image_blurred_gauss_bytes.len() as f32);
567        assert!(error < 0.05);
568    }
569}