From a990de90fe41456a23e58bd087d2f107d321f3a1 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Fri, 19 Jul 2024 16:37:58 +0400 Subject: Deleted vendor folder --- vendor/image/src/imageops/affine.rs | 410 ----------- vendor/image/src/imageops/colorops.rs | 646 ----------------- vendor/image/src/imageops/mod.rs | 485 ------------- vendor/image/src/imageops/sample.rs | 1228 --------------------------------- 4 files changed, 2769 deletions(-) delete mode 100644 vendor/image/src/imageops/affine.rs delete mode 100644 vendor/image/src/imageops/colorops.rs delete mode 100644 vendor/image/src/imageops/mod.rs delete mode 100644 vendor/image/src/imageops/sample.rs (limited to 'vendor/image/src/imageops') diff --git a/vendor/image/src/imageops/affine.rs b/vendor/image/src/imageops/affine.rs deleted file mode 100644 index 548381c..0000000 --- a/vendor/image/src/imageops/affine.rs +++ /dev/null @@ -1,410 +0,0 @@ -//! Functions for performing affine transformations. - -use crate::error::{ImageError, ParameterError, ParameterErrorKind}; -use crate::image::{GenericImage, GenericImageView}; -use crate::traits::Pixel; -use crate::ImageBuffer; - -/// Rotate an image 90 degrees clockwise. -pub fn rotate90( - image: &I, -) -> ImageBuffer::Subpixel>> -where - I::Pixel: 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(height, width); - let _ = rotate90_in(image, &mut out); - out -} - -/// Rotate an image 180 degrees clockwise. -pub fn rotate180( - image: &I, -) -> ImageBuffer::Subpixel>> -where - I::Pixel: 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, height); - let _ = rotate180_in(image, &mut out); - out -} - -/// Rotate an image 270 degrees clockwise. -pub fn rotate270( - image: &I, -) -> ImageBuffer::Subpixel>> -where - I::Pixel: 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(height, width); - let _ = rotate270_in(image, &mut out); - out -} - -/// Rotate an image 90 degrees clockwise and put the result into the destination [`ImageBuffer`]. -pub fn rotate90_in( - image: &I, - destination: &mut ImageBuffer, -) -> crate::ImageResult<()> -where - I: GenericImageView, - I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, -{ - let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); - if w0 != h1 || h0 != w1 { - return Err(ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::DimensionMismatch, - ))); - } - - for y in 0..h0 { - for x in 0..w0 { - let p = image.get_pixel(x, y); - destination.put_pixel(h0 - y - 1, x, p); - } - } - Ok(()) -} - -/// Rotate an image 180 degrees clockwise and put the result into the destination [`ImageBuffer`]. -pub fn rotate180_in( - image: &I, - destination: &mut ImageBuffer, -) -> crate::ImageResult<()> -where - I: GenericImageView, - I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, -{ - let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); - if w0 != w1 || h0 != h1 { - return Err(ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::DimensionMismatch, - ))); - } - - for y in 0..h0 { - for x in 0..w0 { - let p = image.get_pixel(x, y); - destination.put_pixel(w0 - x - 1, h0 - y - 1, p); - } - } - Ok(()) -} - -/// Rotate an image 270 degrees clockwise and put the result into the destination [`ImageBuffer`]. -pub fn rotate270_in( - image: &I, - destination: &mut ImageBuffer, -) -> crate::ImageResult<()> -where - I: GenericImageView, - I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, -{ - let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); - if w0 != h1 || h0 != w1 { - return Err(ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::DimensionMismatch, - ))); - } - - for y in 0..h0 { - for x in 0..w0 { - let p = image.get_pixel(x, y); - destination.put_pixel(y, w0 - x - 1, p); - } - } - Ok(()) -} - -/// Flip an image horizontally -pub fn flip_horizontal( - image: &I, -) -> ImageBuffer::Subpixel>> -where - I::Pixel: 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, height); - let _ = flip_horizontal_in(image, &mut out); - out -} - -/// Flip an image vertically -pub fn flip_vertical( - image: &I, -) -> ImageBuffer::Subpixel>> -where - I::Pixel: 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, height); - let _ = flip_vertical_in(image, &mut out); - out -} - -/// Flip an image horizontally and put the result into the destination [`ImageBuffer`]. -pub fn flip_horizontal_in( - image: &I, - destination: &mut ImageBuffer, -) -> crate::ImageResult<()> -where - I: GenericImageView, - I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, -{ - let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); - if w0 != w1 || h0 != h1 { - return Err(ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::DimensionMismatch, - ))); - } - - for y in 0..h0 { - for x in 0..w0 { - let p = image.get_pixel(x, y); - destination.put_pixel(w0 - x - 1, y, p); - } - } - Ok(()) -} - -/// Flip an image vertically and put the result into the destination [`ImageBuffer`]. -pub fn flip_vertical_in( - image: &I, - destination: &mut ImageBuffer, -) -> crate::ImageResult<()> -where - I: GenericImageView, - I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, -{ - let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); - if w0 != w1 || h0 != h1 { - return Err(ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::DimensionMismatch, - ))); - } - - for y in 0..h0 { - for x in 0..w0 { - let p = image.get_pixel(x, y); - destination.put_pixel(x, h0 - 1 - y, p); - } - } - Ok(()) -} - -/// Rotate an image 180 degrees clockwise in place. -pub fn rotate180_in_place(image: &mut I) { - let (width, height) = image.dimensions(); - - for y in 0..height / 2 { - for x in 0..width { - let p = image.get_pixel(x, y); - - let x2 = width - x - 1; - let y2 = height - y - 1; - - let p2 = image.get_pixel(x2, y2); - image.put_pixel(x, y, p2); - image.put_pixel(x2, y2, p); - } - } - - if height % 2 != 0 { - let middle = height / 2; - - for x in 0..width / 2 { - let p = image.get_pixel(x, middle); - let x2 = width - x - 1; - - let p2 = image.get_pixel(x2, middle); - image.put_pixel(x, middle, p2); - image.put_pixel(x2, middle, p); - } - } -} - -/// Flip an image horizontally in place. -pub fn flip_horizontal_in_place(image: &mut I) { - let (width, height) = image.dimensions(); - - for y in 0..height { - for x in 0..width / 2 { - let x2 = width - x - 1; - let p2 = image.get_pixel(x2, y); - let p = image.get_pixel(x, y); - image.put_pixel(x2, y, p); - image.put_pixel(x, y, p2); - } - } -} - -/// Flip an image vertically in place. -pub fn flip_vertical_in_place(image: &mut I) { - let (width, height) = image.dimensions(); - - for y in 0..height / 2 { - for x in 0..width { - let y2 = height - y - 1; - let p2 = image.get_pixel(x, y2); - let p = image.get_pixel(x, y); - image.put_pixel(x, y2, p); - image.put_pixel(x, y, p2); - } - } -} - -#[cfg(test)] -mod test { - use super::{ - flip_horizontal, flip_horizontal_in_place, flip_vertical, flip_vertical_in_place, - rotate180, rotate180_in_place, rotate270, rotate90, - }; - use crate::image::GenericImage; - use crate::traits::Pixel; - use crate::{GrayImage, ImageBuffer}; - - macro_rules! assert_pixels_eq { - ($actual:expr, $expected:expr) => {{ - let actual_dim = $actual.dimensions(); - let expected_dim = $expected.dimensions(); - - if actual_dim != expected_dim { - panic!( - "dimensions do not match. \ - actual: {:?}, expected: {:?}", - actual_dim, expected_dim - ) - } - - let diffs = pixel_diffs($actual, $expected); - - if !diffs.is_empty() { - let mut err = "".to_string(); - - let diff_messages = diffs - .iter() - .take(5) - .map(|d| format!("\nactual: {:?}, expected {:?} ", d.0, d.1)) - .collect::>() - .join(""); - - err.push_str(&diff_messages); - panic!("pixels do not match. {:?}", err) - } - }}; - } - - #[test] - fn test_rotate90() { - let image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(2, 3, vec![10u8, 00u8, 11u8, 01u8, 12u8, 02u8]).unwrap(); - - assert_pixels_eq!(&rotate90(&image), &expected); - } - - #[test] - fn test_rotate180() { - let image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![12u8, 11u8, 10u8, 02u8, 01u8, 00u8]).unwrap(); - - assert_pixels_eq!(&rotate180(&image), &expected); - } - - #[test] - fn test_rotate270() { - let image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(2, 3, vec![02u8, 12u8, 01u8, 11u8, 00u8, 10u8]).unwrap(); - - assert_pixels_eq!(&rotate270(&image), &expected); - } - - #[test] - fn test_rotate180_in_place() { - let mut image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![12u8, 11u8, 10u8, 02u8, 01u8, 00u8]).unwrap(); - - rotate180_in_place(&mut image); - - assert_pixels_eq!(&image, &expected); - } - - #[test] - fn test_flip_horizontal() { - let image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![02u8, 01u8, 00u8, 12u8, 11u8, 10u8]).unwrap(); - - assert_pixels_eq!(&flip_horizontal(&image), &expected); - } - - #[test] - fn test_flip_vertical() { - let image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![10u8, 11u8, 12u8, 00u8, 01u8, 02u8]).unwrap(); - - assert_pixels_eq!(&flip_vertical(&image), &expected); - } - - #[test] - fn test_flip_horizontal_in_place() { - let mut image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![02u8, 01u8, 00u8, 12u8, 11u8, 10u8]).unwrap(); - - flip_horizontal_in_place(&mut image); - - assert_pixels_eq!(&image, &expected); - } - - #[test] - fn test_flip_vertical_in_place() { - let mut image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![10u8, 11u8, 12u8, 00u8, 01u8, 02u8]).unwrap(); - - flip_vertical_in_place(&mut image); - - assert_pixels_eq!(&image, &expected); - } - - fn pixel_diffs(left: &I, right: &J) -> Vec<((u32, u32, P), (u32, u32, P))> - where - I: GenericImage, - J: GenericImage, - P: Pixel + Eq, - { - left.pixels() - .zip(right.pixels()) - .filter(|&(p, q)| p != q) - .collect::>() - } -} diff --git a/vendor/image/src/imageops/colorops.rs b/vendor/image/src/imageops/colorops.rs deleted file mode 100644 index 085e5f4..0000000 --- a/vendor/image/src/imageops/colorops.rs +++ /dev/null @@ -1,646 +0,0 @@ -//! Functions for altering and converting the color of pixelbufs - -use num_traits::NumCast; -use std::f64::consts::PI; - -use crate::color::{FromColor, IntoColor, Luma, LumaA, Rgba}; -use crate::image::{GenericImage, GenericImageView}; -use crate::traits::{Pixel, Primitive}; -use crate::utils::clamp; -use crate::ImageBuffer; - -type Subpixel = <::Pixel as Pixel>::Subpixel; - -/// Convert the supplied image to grayscale. Alpha channel is discarded. -pub fn grayscale( - image: &I, -) -> ImageBuffer>, Vec>> { - grayscale_with_type(image) -} - -/// Convert the supplied image to grayscale. Alpha channel is preserved. -pub fn grayscale_alpha( - image: &I, -) -> ImageBuffer>, Vec>> { - grayscale_with_type_alpha(image) -} - -/// Convert the supplied image to a grayscale image with the specified pixel type. Alpha channel is discarded. -pub fn grayscale_with_type( - image: &I, -) -> ImageBuffer> -where - NewPixel: Pixel + FromColor>>, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, height); - - for (x, y, pixel) in image.pixels() { - let grayscale = pixel.to_luma(); - let new_pixel = grayscale.into_color(); // no-op for luma->luma - - out.put_pixel(x, y, new_pixel); - } - - out -} - -/// Convert the supplied image to a grayscale image with the specified pixel type. Alpha channel is preserved. -pub fn grayscale_with_type_alpha( - image: &I, -) -> ImageBuffer> -where - NewPixel: Pixel + FromColor>>, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, height); - - for (x, y, pixel) in image.pixels() { - let grayscale = pixel.to_luma_alpha(); - let new_pixel = grayscale.into_color(); // no-op for luma->luma - - out.put_pixel(x, y, new_pixel); - } - - out -} - -/// Invert each pixel within the supplied image. -/// This function operates in place. -pub fn invert(image: &mut I) { - // TODO find a way to use pixels? - let (width, height) = image.dimensions(); - - for y in 0..height { - for x in 0..width { - let mut p = image.get_pixel(x, y); - p.invert(); - - image.put_pixel(x, y, p); - } - } -} - -/// Adjust the contrast of the supplied image. -/// ```contrast``` is the amount to adjust the contrast by. -/// Negative values decrease the contrast and positive values increase the contrast. -/// -/// *[See also `contrast_in_place`.][contrast_in_place]* -pub fn contrast(image: &I, contrast: f32) -> ImageBuffer> -where - I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, height); - - let max = S::DEFAULT_MAX_VALUE; - let max: f32 = NumCast::from(max).unwrap(); - - let percent = ((100.0 + contrast) / 100.0).powi(2); - - for (x, y, pixel) in image.pixels() { - let f = pixel.map(|b| { - let c: f32 = NumCast::from(b).unwrap(); - - let d = ((c / max - 0.5) * percent + 0.5) * max; - let e = clamp(d, 0.0, max); - - NumCast::from(e).unwrap() - }); - out.put_pixel(x, y, f); - } - - out -} - -/// Adjust the contrast of the supplied image in place. -/// ```contrast``` is the amount to adjust the contrast by. -/// Negative values decrease the contrast and positive values increase the contrast. -/// -/// *[See also `contrast`.][contrast]* -pub fn contrast_in_place(image: &mut I, contrast: f32) -where - I: GenericImage, -{ - let (width, height) = image.dimensions(); - - let max = ::Subpixel::DEFAULT_MAX_VALUE; - let max: f32 = NumCast::from(max).unwrap(); - - let percent = ((100.0 + contrast) / 100.0).powi(2); - - // TODO find a way to use pixels? - for y in 0..height { - for x in 0..width { - let f = image.get_pixel(x, y).map(|b| { - let c: f32 = NumCast::from(b).unwrap(); - - let d = ((c / max - 0.5) * percent + 0.5) * max; - let e = clamp(d, 0.0, max); - - NumCast::from(e).unwrap() - }); - - image.put_pixel(x, y, f); - } - } -} - -/// Brighten the supplied image. -/// ```value``` is the amount to brighten each pixel by. -/// Negative values decrease the brightness and positive values increase it. -/// -/// *[See also `brighten_in_place`.][brighten_in_place]* -pub fn brighten(image: &I, value: i32) -> ImageBuffer> -where - I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, height); - - let max = S::DEFAULT_MAX_VALUE; - let max: i32 = NumCast::from(max).unwrap(); - - for (x, y, pixel) in image.pixels() { - let e = pixel.map_with_alpha( - |b| { - let c: i32 = NumCast::from(b).unwrap(); - let d = clamp(c + value, 0, max); - - NumCast::from(d).unwrap() - }, - |alpha| alpha, - ); - out.put_pixel(x, y, e); - } - - out -} - -/// Brighten the supplied image in place. -/// ```value``` is the amount to brighten each pixel by. -/// Negative values decrease the brightness and positive values increase it. -/// -/// *[See also `brighten`.][brighten]* -pub fn brighten_in_place(image: &mut I, value: i32) -where - I: GenericImage, -{ - let (width, height) = image.dimensions(); - - let max = ::Subpixel::DEFAULT_MAX_VALUE; - let max: i32 = NumCast::from(max).unwrap(); // TODO what does this do for f32? clamp at 1?? - - // TODO find a way to use pixels? - for y in 0..height { - for x in 0..width { - let e = image.get_pixel(x, y).map_with_alpha( - |b| { - let c: i32 = NumCast::from(b).unwrap(); - let d = clamp(c + value, 0, max); - - NumCast::from(d).unwrap() - }, - |alpha| alpha, - ); - - image.put_pixel(x, y, e); - } - } -} - -/// Hue rotate the supplied image. -/// `value` is the degrees to rotate each pixel by. -/// 0 and 360 do nothing, the rest rotates by the given degree value. -/// just like the css webkit filter hue-rotate(180) -/// -/// *[See also `huerotate_in_place`.][huerotate_in_place]* -pub fn huerotate(image: &I, value: i32) -> ImageBuffer> -where - I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, height); - - let angle: f64 = NumCast::from(value).unwrap(); - - let cosv = (angle * PI / 180.0).cos(); - let sinv = (angle * PI / 180.0).sin(); - let matrix: [f64; 9] = [ - // Reds - 0.213 + cosv * 0.787 - sinv * 0.213, - 0.715 - cosv * 0.715 - sinv * 0.715, - 0.072 - cosv * 0.072 + sinv * 0.928, - // Greens - 0.213 - cosv * 0.213 + sinv * 0.143, - 0.715 + cosv * 0.285 + sinv * 0.140, - 0.072 - cosv * 0.072 - sinv * 0.283, - // Blues - 0.213 - cosv * 0.213 - sinv * 0.787, - 0.715 - cosv * 0.715 + sinv * 0.715, - 0.072 + cosv * 0.928 + sinv * 0.072, - ]; - for (x, y, pixel) in out.enumerate_pixels_mut() { - let p = image.get_pixel(x, y); - - #[allow(deprecated)] - let (k1, k2, k3, k4) = p.channels4(); - let vec: (f64, f64, f64, f64) = ( - NumCast::from(k1).unwrap(), - NumCast::from(k2).unwrap(), - NumCast::from(k3).unwrap(), - NumCast::from(k4).unwrap(), - ); - - let r = vec.0; - let g = vec.1; - let b = vec.2; - - let new_r = matrix[0] * r + matrix[1] * g + matrix[2] * b; - let new_g = matrix[3] * r + matrix[4] * g + matrix[5] * b; - let new_b = matrix[6] * r + matrix[7] * g + matrix[8] * b; - let max = 255f64; - - #[allow(deprecated)] - let outpixel = Pixel::from_channels( - NumCast::from(clamp(new_r, 0.0, max)).unwrap(), - NumCast::from(clamp(new_g, 0.0, max)).unwrap(), - NumCast::from(clamp(new_b, 0.0, max)).unwrap(), - NumCast::from(clamp(vec.3, 0.0, max)).unwrap(), - ); - *pixel = outpixel; - } - out -} - -/// Hue rotate the supplied image in place. -/// `value` is the degrees to rotate each pixel by. -/// 0 and 360 do nothing, the rest rotates by the given degree value. -/// just like the css webkit filter hue-rotate(180) -/// -/// *[See also `huerotate`.][huerotate]* -pub fn huerotate_in_place(image: &mut I, value: i32) -where - I: GenericImage, -{ - let (width, height) = image.dimensions(); - - let angle: f64 = NumCast::from(value).unwrap(); - - let cosv = (angle * PI / 180.0).cos(); - let sinv = (angle * PI / 180.0).sin(); - let matrix: [f64; 9] = [ - // Reds - 0.213 + cosv * 0.787 - sinv * 0.213, - 0.715 - cosv * 0.715 - sinv * 0.715, - 0.072 - cosv * 0.072 + sinv * 0.928, - // Greens - 0.213 - cosv * 0.213 + sinv * 0.143, - 0.715 + cosv * 0.285 + sinv * 0.140, - 0.072 - cosv * 0.072 - sinv * 0.283, - // Blues - 0.213 - cosv * 0.213 - sinv * 0.787, - 0.715 - cosv * 0.715 + sinv * 0.715, - 0.072 + cosv * 0.928 + sinv * 0.072, - ]; - - // TODO find a way to use pixels? - for y in 0..height { - for x in 0..width { - let pixel = image.get_pixel(x, y); - - #[allow(deprecated)] - let (k1, k2, k3, k4) = pixel.channels4(); - - let vec: (f64, f64, f64, f64) = ( - NumCast::from(k1).unwrap(), - NumCast::from(k2).unwrap(), - NumCast::from(k3).unwrap(), - NumCast::from(k4).unwrap(), - ); - - let r = vec.0; - let g = vec.1; - let b = vec.2; - - let new_r = matrix[0] * r + matrix[1] * g + matrix[2] * b; - let new_g = matrix[3] * r + matrix[4] * g + matrix[5] * b; - let new_b = matrix[6] * r + matrix[7] * g + matrix[8] * b; - let max = 255f64; - - #[allow(deprecated)] - let outpixel = Pixel::from_channels( - NumCast::from(clamp(new_r, 0.0, max)).unwrap(), - NumCast::from(clamp(new_g, 0.0, max)).unwrap(), - NumCast::from(clamp(new_b, 0.0, max)).unwrap(), - NumCast::from(clamp(vec.3, 0.0, max)).unwrap(), - ); - - image.put_pixel(x, y, outpixel); - } - } -} - -/// A color map -pub trait ColorMap { - /// The color type on which the map operates on - type Color; - /// Returns the index of the closest match of `color` - /// in the color map. - fn index_of(&self, color: &Self::Color) -> usize; - /// Looks up color by index in the color map. If `idx` is out of range for the color map, or - /// ColorMap doesn't implement `lookup` `None` is returned. - fn lookup(&self, index: usize) -> Option { - let _ = index; - None - } - /// Determine if this implementation of ColorMap overrides the default `lookup`. - fn has_lookup(&self) -> bool { - false - } - /// Maps `color` to the closest color in the color map. - fn map_color(&self, color: &mut Self::Color); -} - -/// A bi-level color map -/// -/// # Examples -/// ``` -/// use image::imageops::colorops::{index_colors, BiLevel, ColorMap}; -/// use image::{ImageBuffer, Luma}; -/// -/// let (w, h) = (16, 16); -/// // Create an image with a smooth horizontal gradient from black (0) to white (255). -/// let gray = ImageBuffer::from_fn(w, h, |x, y| -> Luma { [(255 * x / w) as u8].into() }); -/// // Mapping the gray image through the `BiLevel` filter should map gray pixels less than half -/// // intensity (127) to black (0), and anything greater to white (255). -/// let cmap = BiLevel; -/// let palletized = index_colors(&gray, &cmap); -/// let mapped = ImageBuffer::from_fn(w, h, |x, y| { -/// let p = palletized.get_pixel(x, y); -/// cmap.lookup(p.0[0] as usize) -/// .expect("indexed color out-of-range") -/// }); -/// // Create an black and white image of expected output. -/// let bw = ImageBuffer::from_fn(w, h, |x, y| -> Luma { -/// if x <= (w / 2) { -/// [0].into() -/// } else { -/// [255].into() -/// } -/// }); -/// assert_eq!(mapped, bw); -/// ``` -#[derive(Clone, Copy)] -pub struct BiLevel; - -impl ColorMap for BiLevel { - type Color = Luma; - - #[inline(always)] - fn index_of(&self, color: &Luma) -> usize { - let luma = color.0; - if luma[0] > 127 { - 1 - } else { - 0 - } - } - - #[inline(always)] - fn lookup(&self, idx: usize) -> Option { - match idx { - 0 => Some([0].into()), - 1 => Some([255].into()), - _ => None, - } - } - - /// Indicate NeuQuant implements `lookup`. - fn has_lookup(&self) -> bool { - true - } - - #[inline(always)] - fn map_color(&self, color: &mut Luma) { - let new_color = 0xFF * self.index_of(color) as u8; - let luma = &mut color.0; - luma[0] = new_color; - } -} - -impl ColorMap for color_quant::NeuQuant { - type Color = Rgba; - - #[inline(always)] - fn index_of(&self, color: &Rgba) -> usize { - self.index_of(color.channels()) - } - - #[inline(always)] - fn lookup(&self, idx: usize) -> Option { - self.lookup(idx).map(|p| p.into()) - } - - /// Indicate NeuQuant implements `lookup`. - fn has_lookup(&self) -> bool { - true - } - - #[inline(always)] - fn map_color(&self, color: &mut Rgba) { - self.map_pixel(color.channels_mut()) - } -} - -/// Floyd-Steinberg error diffusion -fn diffuse_err>(pixel: &mut P, error: [i16; 3], factor: i16) { - for (e, c) in error.iter().zip(pixel.channels_mut().iter_mut()) { - *c = match >::from(*c) + e * factor / 16 { - val if val < 0 => 0, - val if val > 0xFF => 0xFF, - val => val as u8, - } - } -} - -macro_rules! do_dithering( - ($map:expr, $image:expr, $err:expr, $x:expr, $y:expr) => ( - { - let old_pixel = $image[($x, $y)]; - let new_pixel = $image.get_pixel_mut($x, $y); - $map.map_color(new_pixel); - for ((e, &old), &new) in $err.iter_mut() - .zip(old_pixel.channels().iter()) - .zip(new_pixel.channels().iter()) - { - *e = >::from(old) - >::from(new) - } - } - ) -); - -/// Reduces the colors of the image using the supplied `color_map` while applying -/// Floyd-Steinberg dithering to improve the visual conception -pub fn dither(image: &mut ImageBuffer>, color_map: &Map) -where - Map: ColorMap + ?Sized, - Pix: Pixel + 'static, -{ - let (width, height) = image.dimensions(); - let mut err: [i16; 3] = [0; 3]; - for y in 0..height - 1 { - let x = 0; - do_dithering!(color_map, image, err, x, y); - diffuse_err(image.get_pixel_mut(x + 1, y), err, 7); - diffuse_err(image.get_pixel_mut(x, y + 1), err, 5); - diffuse_err(image.get_pixel_mut(x + 1, y + 1), err, 1); - for x in 1..width - 1 { - do_dithering!(color_map, image, err, x, y); - diffuse_err(image.get_pixel_mut(x + 1, y), err, 7); - diffuse_err(image.get_pixel_mut(x - 1, y + 1), err, 3); - diffuse_err(image.get_pixel_mut(x, y + 1), err, 5); - diffuse_err(image.get_pixel_mut(x + 1, y + 1), err, 1); - } - let x = width - 1; - do_dithering!(color_map, image, err, x, y); - diffuse_err(image.get_pixel_mut(x - 1, y + 1), err, 3); - diffuse_err(image.get_pixel_mut(x, y + 1), err, 5); - } - let y = height - 1; - let x = 0; - do_dithering!(color_map, image, err, x, y); - diffuse_err(image.get_pixel_mut(x + 1, y), err, 7); - for x in 1..width - 1 { - do_dithering!(color_map, image, err, x, y); - diffuse_err(image.get_pixel_mut(x + 1, y), err, 7); - } - let x = width - 1; - do_dithering!(color_map, image, err, x, y); -} - -/// Reduces the colors using the supplied `color_map` and returns an image of the indices -pub fn index_colors( - image: &ImageBuffer>, - color_map: &Map, -) -> ImageBuffer, Vec> -where - Map: ColorMap + ?Sized, - Pix: Pixel + 'static, -{ - let mut indices = ImageBuffer::new(image.width(), image.height()); - for (pixel, idx) in image.pixels().zip(indices.pixels_mut()) { - *idx = Luma([color_map.index_of(pixel) as u8]) - } - indices -} - -#[cfg(test)] -mod test { - - use super::*; - use crate::{GrayImage, ImageBuffer}; - - macro_rules! assert_pixels_eq { - ($actual:expr, $expected:expr) => {{ - let actual_dim = $actual.dimensions(); - let expected_dim = $expected.dimensions(); - - if actual_dim != expected_dim { - panic!( - "dimensions do not match. \ - actual: {:?}, expected: {:?}", - actual_dim, expected_dim - ) - } - - let diffs = pixel_diffs($actual, $expected); - - if !diffs.is_empty() { - let mut err = "".to_string(); - - let diff_messages = diffs - .iter() - .take(5) - .map(|d| format!("\nactual: {:?}, expected {:?} ", d.0, d.1)) - .collect::>() - .join(""); - - err.push_str(&diff_messages); - panic!("pixels do not match. {:?}", err) - } - }}; - } - - #[test] - fn test_dither() { - let mut image = ImageBuffer::from_raw(2, 2, vec![127, 127, 127, 127]).unwrap(); - let cmap = BiLevel; - dither(&mut image, &cmap); - assert_eq!(&*image, &[0, 0xFF, 0xFF, 0]); - assert_eq!(index_colors(&image, &cmap).into_raw(), vec![0, 1, 1, 0]) - } - - #[test] - fn test_grayscale() { - let mut image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - assert_pixels_eq!(&grayscale(&mut image), &expected); - } - - #[test] - fn test_invert() { - let mut image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![255u8, 254u8, 253u8, 245u8, 244u8, 243u8]).unwrap(); - - invert(&mut image); - assert_pixels_eq!(&image, &expected); - } - #[test] - fn test_brighten() { - let image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![10u8, 11u8, 12u8, 20u8, 21u8, 22u8]).unwrap(); - - assert_pixels_eq!(&brighten(&image, 10), &expected); - } - - #[test] - fn test_brighten_place() { - let mut image: GrayImage = - ImageBuffer::from_raw(3, 2, vec![00u8, 01u8, 02u8, 10u8, 11u8, 12u8]).unwrap(); - - let expected: GrayImage = - ImageBuffer::from_raw(3, 2, vec![10u8, 11u8, 12u8, 20u8, 21u8, 22u8]).unwrap(); - - brighten_in_place(&mut image, 10); - assert_pixels_eq!(&image, &expected); - } - - fn pixel_diffs(left: &I, right: &J) -> Vec<((u32, u32, P), (u32, u32, P))> - where - I: GenericImage, - J: GenericImage, - P: Pixel + Eq, - { - left.pixels() - .zip(right.pixels()) - .filter(|&(p, q)| p != q) - .collect::>() - } -} diff --git a/vendor/image/src/imageops/mod.rs b/vendor/image/src/imageops/mod.rs deleted file mode 100644 index fdd2bf3..0000000 --- a/vendor/image/src/imageops/mod.rs +++ /dev/null @@ -1,485 +0,0 @@ -//! Image Processing Functions -use std::cmp; - -use crate::image::{GenericImage, GenericImageView, SubImage}; -use crate::traits::{Lerp, Pixel, Primitive}; - -pub use self::sample::FilterType; - -pub use self::sample::FilterType::{CatmullRom, Gaussian, Lanczos3, Nearest, Triangle}; - -/// Affine transformations -pub use self::affine::{ - flip_horizontal, flip_horizontal_in, flip_horizontal_in_place, flip_vertical, flip_vertical_in, - flip_vertical_in_place, rotate180, rotate180_in, rotate180_in_place, rotate270, rotate270_in, - rotate90, rotate90_in, -}; - -/// Image sampling -pub use self::sample::{ - blur, filter3x3, interpolate_bilinear, interpolate_nearest, resize, sample_bilinear, - sample_nearest, thumbnail, unsharpen, -}; - -/// Color operations -pub use self::colorops::{ - brighten, contrast, dither, grayscale, grayscale_alpha, grayscale_with_type, - grayscale_with_type_alpha, huerotate, index_colors, invert, BiLevel, ColorMap, -}; - -mod affine; -// Public only because of Rust bug: -// https://github.com/rust-lang/rust/issues/18241 -pub mod colorops; -mod sample; - -/// Return a mutable view into an image -/// The coordinates set the position of the top left corner of the crop. -pub fn crop( - image: &mut I, - x: u32, - y: u32, - width: u32, - height: u32, -) -> SubImage<&mut I> { - let (x, y, width, height) = crop_dimms(image, x, y, width, height); - SubImage::new(image, x, y, width, height) -} - -/// Return an immutable view into an image -/// The coordinates set the position of the top left corner of the crop. -pub fn crop_imm( - image: &I, - x: u32, - y: u32, - width: u32, - height: u32, -) -> SubImage<&I> { - let (x, y, width, height) = crop_dimms(image, x, y, width, height); - SubImage::new(image, x, y, width, height) -} - -fn crop_dimms( - image: &I, - x: u32, - y: u32, - width: u32, - height: u32, -) -> (u32, u32, u32, u32) { - let (iwidth, iheight) = image.dimensions(); - - let x = cmp::min(x, iwidth); - let y = cmp::min(y, iheight); - - let height = cmp::min(height, iheight - y); - let width = cmp::min(width, iwidth - x); - - (x, y, width, height) -} - -/// Calculate the region that can be copied from top to bottom. -/// -/// Given image size of bottom and top image, and a point at which we want to place the top image -/// onto the bottom image, how large can we be? Have to wary of the following issues: -/// * Top might be larger than bottom -/// * Overflows in the computation -/// * Coordinates could be completely out of bounds -/// -/// The main idea is to make use of inequalities provided by the nature of `saturating_add` and -/// `saturating_sub`. These intrinsically validate that all resulting coordinates will be in bounds -/// for both images. -/// -/// We want that all these coordinate accesses are safe: -/// 1. `bottom.get_pixel(x + [0..x_range), y + [0..y_range))` -/// 2. `top.get_pixel([0..x_range), [0..y_range))` -/// -/// Proof that the function provides the necessary bounds for width. Note that all unaugmented math -/// operations are to be read in standard arithmetic, not integer arithmetic. Since no direct -/// integer arithmetic occurs in the implementation, this is unambiguous. -/// -/// ```text -/// Three short notes/lemmata: -/// - Iff `(a - b) <= 0` then `a.saturating_sub(b) = 0` -/// - Iff `(a - b) >= 0` then `a.saturating_sub(b) = a - b` -/// - If `a <= c` then `a.saturating_sub(b) <= c.saturating_sub(b)` -/// -/// 1.1 We show that if `bottom_width <= x`, then `x_range = 0` therefore `x + [0..x_range)` is empty. -/// -/// x_range -/// = (top_width.saturating_add(x).min(bottom_width)).saturating_sub(x) -/// <= bottom_width.saturating_sub(x) -/// -/// bottom_width <= x -/// <==> bottom_width - x <= 0 -/// <==> bottom_width.saturating_sub(x) = 0 -/// ==> x_range <= 0 -/// ==> x_range = 0 -/// -/// 1.2 If `x < bottom_width` then `x + x_range < bottom_width` -/// -/// x + x_range -/// <= x + bottom_width.saturating_sub(x) -/// = x + (bottom_width - x) -/// = bottom_width -/// -/// 2. We show that `x_range <= top_width` -/// -/// x_range -/// = (top_width.saturating_add(x).min(bottom_width)).saturating_sub(x) -/// <= top_width.saturating_add(x).saturating_sub(x) -/// <= (top_wdith + x).saturating_sub(x) -/// = top_width (due to `top_width >= 0` and `x >= 0`) -/// ``` -/// -/// Proof is the same for height. -pub fn overlay_bounds( - (bottom_width, bottom_height): (u32, u32), - (top_width, top_height): (u32, u32), - x: u32, - y: u32, -) -> (u32, u32) { - let x_range = top_width - .saturating_add(x) // Calculate max coordinate - .min(bottom_width) // Restrict to lower width - .saturating_sub(x); // Determinate length from start `x` - let y_range = top_height - .saturating_add(y) - .min(bottom_height) - .saturating_sub(y); - (x_range, y_range) -} - -/// Calculate the region that can be copied from top to bottom. -/// -/// Given image size of bottom and top image, and a point at which we want to place the top image -/// onto the bottom image, how large can we be? Have to wary of the following issues: -/// * Top might be larger than bottom -/// * Overflows in the computation -/// * Coordinates could be completely out of bounds -/// -/// The returned value is of the form: -/// -/// `(origin_bottom_x, origin_bottom_y, origin_top_x, origin_top_y, x_range, y_range)` -/// -/// The main idea is to do computations on i64's and then clamp to image dimensions. -/// In particular, we want to ensure that all these coordinate accesses are safe: -/// 1. `bottom.get_pixel(origin_bottom_x + [0..x_range), origin_bottom_y + [0..y_range))` -/// 2. `top.get_pixel(origin_top_y + [0..x_range), origin_top_y + [0..y_range))` -/// -fn overlay_bounds_ext( - (bottom_width, bottom_height): (u32, u32), - (top_width, top_height): (u32, u32), - x: i64, - y: i64, -) -> (u32, u32, u32, u32, u32, u32) { - // Return a predictable value if the two images don't overlap at all. - if x > i64::from(bottom_width) - || y > i64::from(bottom_height) - || x.saturating_add(i64::from(top_width)) <= 0 - || y.saturating_add(i64::from(top_height)) <= 0 - { - return (0, 0, 0, 0, 0, 0); - } - - // Find the maximum x and y coordinates in terms of the bottom image. - let max_x = x.saturating_add(i64::from(top_width)); - let max_y = y.saturating_add(i64::from(top_height)); - - // Clip the origin and maximum coordinates to the bounds of the bottom image. - // Casting to a u32 is safe because both 0 and `bottom_{width,height}` fit - // into 32-bits. - let max_inbounds_x = max_x.clamp(0, i64::from(bottom_width)) as u32; - let max_inbounds_y = max_y.clamp(0, i64::from(bottom_height)) as u32; - let origin_bottom_x = x.clamp(0, i64::from(bottom_width)) as u32; - let origin_bottom_y = y.clamp(0, i64::from(bottom_height)) as u32; - - // The range is the difference between the maximum inbounds coordinates and - // the clipped origin. Unchecked subtraction is safe here because both are - // always positive and `max_inbounds_{x,y}` >= `origin_{x,y}` due to - // `top_{width,height}` being >= 0. - let x_range = max_inbounds_x - origin_bottom_x; - let y_range = max_inbounds_y - origin_bottom_y; - - // If x (or y) is negative, then the origin of the top image is shifted by -x (or -y). - let origin_top_x = x.saturating_mul(-1).clamp(0, i64::from(top_width)) as u32; - let origin_top_y = y.saturating_mul(-1).clamp(0, i64::from(top_height)) as u32; - - ( - origin_bottom_x, - origin_bottom_y, - origin_top_x, - origin_top_y, - x_range, - y_range, - ) -} - -/// Overlay an image at a given coordinate (x, y) -pub fn overlay(bottom: &mut I, top: &J, x: i64, y: i64) -where - I: GenericImage, - J: GenericImageView, -{ - let bottom_dims = bottom.dimensions(); - let top_dims = top.dimensions(); - - // Crop our top image if we're going out of bounds - let (origin_bottom_x, origin_bottom_y, origin_top_x, origin_top_y, range_width, range_height) = - overlay_bounds_ext(bottom_dims, top_dims, x, y); - - for y in 0..range_height { - for x in 0..range_width { - let p = top.get_pixel(origin_top_x + x, origin_top_y + y); - let mut bottom_pixel = bottom.get_pixel(origin_bottom_x + x, origin_bottom_y + y); - bottom_pixel.blend(&p); - - bottom.put_pixel(origin_bottom_x + x, origin_bottom_y + y, bottom_pixel); - } - } -} - -/// Tile an image by repeating it multiple times -/// -/// # Examples -/// ```no_run -/// use image::{RgbaImage}; -/// -/// let mut img = RgbaImage::new(1920, 1080); -/// let tile = image::open("tile.png").unwrap(); -/// -/// image::imageops::tile(&mut img, &tile); -/// img.save("tiled_wallpaper.png").unwrap(); -/// ``` -pub fn tile(bottom: &mut I, top: &J) -where - I: GenericImage, - J: GenericImageView, -{ - for x in (0..bottom.width()).step_by(top.width() as usize) { - for y in (0..bottom.height()).step_by(top.height() as usize) { - overlay(bottom, top, i64::from(x), i64::from(y)); - } - } -} - -/// Fill the image with a linear vertical gradient -/// -/// This function assumes a linear color space. -/// -/// # Examples -/// ```no_run -/// use image::{Rgba, RgbaImage, Pixel}; -/// -/// let mut img = RgbaImage::new(100, 100); -/// let start = Rgba::from_slice(&[0, 128, 0, 0]); -/// let end = Rgba::from_slice(&[255, 255, 255, 255]); -/// -/// image::imageops::vertical_gradient(&mut img, start, end); -/// img.save("vertical_gradient.png").unwrap(); -pub fn vertical_gradient(img: &mut I, start: &P, stop: &P) -where - I: GenericImage, - P: Pixel + 'static, - S: Primitive + Lerp + 'static, -{ - for y in 0..img.height() { - let pixel = start.map2(stop, |a, b| { - let y = ::from(y).unwrap(); - let height = ::from(img.height() - 1).unwrap(); - S::lerp(a, b, y / height) - }); - - for x in 0..img.width() { - img.put_pixel(x, y, pixel); - } - } -} - -/// Fill the image with a linear horizontal gradient -/// -/// This function assumes a linear color space. -/// -/// # Examples -/// ```no_run -/// use image::{Rgba, RgbaImage, Pixel}; -/// -/// let mut img = RgbaImage::new(100, 100); -/// let start = Rgba::from_slice(&[0, 128, 0, 0]); -/// let end = Rgba::from_slice(&[255, 255, 255, 255]); -/// -/// image::imageops::horizontal_gradient(&mut img, start, end); -/// img.save("horizontal_gradient.png").unwrap(); -pub fn horizontal_gradient(img: &mut I, start: &P, stop: &P) -where - I: GenericImage, - P: Pixel + 'static, - S: Primitive + Lerp + 'static, -{ - for x in 0..img.width() { - let pixel = start.map2(stop, |a, b| { - let x = ::from(x).unwrap(); - let width = ::from(img.width() - 1).unwrap(); - S::lerp(a, b, x / width) - }); - - for y in 0..img.height() { - img.put_pixel(x, y, pixel); - } - } -} - -/// Replace the contents of an image at a given coordinate (x, y) -pub fn replace(bottom: &mut I, top: &J, x: i64, y: i64) -where - I: GenericImage, - J: GenericImageView, -{ - let bottom_dims = bottom.dimensions(); - let top_dims = top.dimensions(); - - // Crop our top image if we're going out of bounds - let (origin_bottom_x, origin_bottom_y, origin_top_x, origin_top_y, range_width, range_height) = - overlay_bounds_ext(bottom_dims, top_dims, x, y); - - for y in 0..range_height { - for x in 0..range_width { - let p = top.get_pixel(origin_top_x + x, origin_top_y + y); - bottom.put_pixel(origin_bottom_x + x, origin_bottom_y + y, p); - } - } -} - -#[cfg(test)] -mod tests { - - use super::{overlay, overlay_bounds_ext}; - use crate::color::Rgb; - use crate::ImageBuffer; - use crate::RgbaImage; - - #[test] - fn test_overlay_bounds_ext() { - assert_eq!( - overlay_bounds_ext((10, 10), (10, 10), 0, 0), - (0, 0, 0, 0, 10, 10) - ); - assert_eq!( - overlay_bounds_ext((10, 10), (10, 10), 1, 0), - (1, 0, 0, 0, 9, 10) - ); - assert_eq!( - overlay_bounds_ext((10, 10), (10, 10), 0, 11), - (0, 0, 0, 0, 0, 0) - ); - assert_eq!( - overlay_bounds_ext((10, 10), (10, 10), -1, 0), - (0, 0, 1, 0, 9, 10) - ); - assert_eq!( - overlay_bounds_ext((10, 10), (10, 10), -10, 0), - (0, 0, 0, 0, 0, 0) - ); - assert_eq!( - overlay_bounds_ext((10, 10), (10, 10), 1i64 << 50, 0), - (0, 0, 0, 0, 0, 0) - ); - assert_eq!( - overlay_bounds_ext((10, 10), (10, 10), -(1i64 << 50), 0), - (0, 0, 0, 0, 0, 0) - ); - assert_eq!( - overlay_bounds_ext((10, 10), (u32::MAX, 10), 10 - i64::from(u32::MAX), 0), - (0, 0, u32::MAX - 10, 0, 10, 10) - ); - } - - #[test] - /// Test that images written into other images works - fn test_image_in_image() { - let mut target = ImageBuffer::new(32, 32); - let source = ImageBuffer::from_pixel(16, 16, Rgb([255u8, 0, 0])); - overlay(&mut target, &source, 0, 0); - assert!(*target.get_pixel(0, 0) == Rgb([255u8, 0, 0])); - assert!(*target.get_pixel(15, 0) == Rgb([255u8, 0, 0])); - assert!(*target.get_pixel(16, 0) == Rgb([0u8, 0, 0])); - assert!(*target.get_pixel(0, 15) == Rgb([255u8, 0, 0])); - assert!(*target.get_pixel(0, 16) == Rgb([0u8, 0, 0])); - } - - #[test] - /// Test that images written outside of a frame doesn't blow up - fn test_image_in_image_outside_of_bounds() { - let mut target = ImageBuffer::new(32, 32); - let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0])); - overlay(&mut target, &source, 1, 1); - assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0])); - assert!(*target.get_pixel(1, 1) == Rgb([255u8, 0, 0])); - assert!(*target.get_pixel(31, 31) == Rgb([255u8, 0, 0])); - } - - #[test] - /// Test that images written to coordinates out of the frame doesn't blow up - /// (issue came up in #848) - fn test_image_outside_image_no_wrap_around() { - let mut target = ImageBuffer::new(32, 32); - let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0])); - overlay(&mut target, &source, 33, 33); - assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0])); - assert!(*target.get_pixel(1, 1) == Rgb([0, 0, 0])); - assert!(*target.get_pixel(31, 31) == Rgb([0, 0, 0])); - } - - #[test] - /// Test that images written to coordinates with overflow works - fn test_image_coordinate_overflow() { - let mut target = ImageBuffer::new(16, 16); - let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0])); - // Overflows to 'sane' coordinates but top is larger than bot. - overlay( - &mut target, - &source, - i64::from(u32::max_value() - 31), - i64::from(u32::max_value() - 31), - ); - assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0])); - assert!(*target.get_pixel(1, 1) == Rgb([0, 0, 0])); - assert!(*target.get_pixel(15, 15) == Rgb([0, 0, 0])); - } - - use super::{horizontal_gradient, vertical_gradient}; - - #[test] - /// Test that horizontal gradients are correctly generated - fn test_image_horizontal_gradient_limits() { - let mut img = ImageBuffer::new(100, 1); - - let start = Rgb([0u8, 128, 0]); - let end = Rgb([255u8, 255, 255]); - - horizontal_gradient(&mut img, &start, &end); - - assert_eq!(img.get_pixel(0, 0), &start); - assert_eq!(img.get_pixel(img.width() - 1, 0), &end); - } - - #[test] - /// Test that vertical gradients are correctly generated - fn test_image_vertical_gradient_limits() { - let mut img = ImageBuffer::new(1, 100); - - let start = Rgb([0u8, 128, 0]); - let end = Rgb([255u8, 255, 255]); - - vertical_gradient(&mut img, &start, &end); - - assert_eq!(img.get_pixel(0, 0), &start); - assert_eq!(img.get_pixel(0, img.height() - 1), &end); - } - - #[test] - /// Test blur doesn't panick when passed 0.0 - fn test_blur_zero() { - let image = RgbaImage::new(50, 50); - let _ = super::blur(&image, 0.0); - } -} diff --git a/vendor/image/src/imageops/sample.rs b/vendor/image/src/imageops/sample.rs deleted file mode 100644 index a362f83..0000000 --- a/vendor/image/src/imageops/sample.rs +++ /dev/null @@ -1,1228 +0,0 @@ -//! Functions and filters for the sampling of pixels. - -// See http://cs.brown.edu/courses/cs123/lectures/08_Image_Processing_IV.pdf -// for some of the theory behind image scaling and convolution - -use std::f32; - -use num_traits::{NumCast, ToPrimitive, Zero}; - -use crate::image::{GenericImage, GenericImageView}; -use crate::traits::{Enlargeable, Pixel, Primitive}; -use crate::utils::clamp; -use crate::{ImageBuffer, Rgba32FImage}; - -/// Available Sampling Filters. -/// -/// ## Examples -/// -/// To test the different sampling filters on a real example, you can find two -/// examples called -/// [`scaledown`](https://github.com/image-rs/image/tree/master/examples/scaledown) -/// and -/// [`scaleup`](https://github.com/image-rs/image/tree/master/examples/scaleup) -/// in the `examples` directory of the crate source code. -/// -/// Here is a 3.58 MiB -/// [test image](https://github.com/image-rs/image/blob/master/examples/scaledown/test.jpg) -/// that has been scaled down to 300x225 px: -/// -/// -///
-///
-///
-/// Nearest Neighbor -///
-///
-///
-/// Linear: Triangle -///
-///
-///
-/// Cubic: Catmull-Rom -///
-///
-///
-/// Gaussian -///
-///
-///
-/// Lanczos with window 3 -///
-///
-/// -/// ## Speed -/// -/// Time required to create each of the examples above, tested on an Intel -/// i7-4770 CPU with Rust 1.37 in release mode: -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -///
Nearest31 ms
Triangle414 ms
CatmullRom817 ms
Gaussian1180 ms
Lanczos31170 ms
-#[derive(Clone, Copy, Debug, PartialEq)] -pub enum FilterType { - /// Nearest Neighbor - Nearest, - - /// Linear Filter - Triangle, - - /// Cubic Filter - CatmullRom, - - /// Gaussian Filter - Gaussian, - - /// Lanczos with window 3 - Lanczos3, -} - -/// A Representation of a separable filter. -pub(crate) struct Filter<'a> { - /// The filter's filter function. - pub(crate) kernel: Box f32 + 'a>, - - /// The window on which this filter operates. - pub(crate) support: f32, -} - -struct FloatNearest(f32); - -// to_i64, to_u64, and to_f64 implicitly affect all other lower conversions. -// Note that to_f64 by default calls to_i64 and thus needs to be overridden. -impl ToPrimitive for FloatNearest { - // to_{i,u}64 is required, to_{i,u}{8,16} are useful. - // If a usecase for full 32 bits is found its trivial to add - fn to_i8(&self) -> Option { - self.0.round().to_i8() - } - fn to_i16(&self) -> Option { - self.0.round().to_i16() - } - fn to_i64(&self) -> Option { - self.0.round().to_i64() - } - fn to_u8(&self) -> Option { - self.0.round().to_u8() - } - fn to_u16(&self) -> Option { - self.0.round().to_u16() - } - fn to_u64(&self) -> Option { - self.0.round().to_u64() - } - fn to_f64(&self) -> Option { - self.0.to_f64() - } -} - -// sinc function: the ideal sampling filter. -fn sinc(t: f32) -> f32 { - let a = t * f32::consts::PI; - - if t == 0.0 { - 1.0 - } else { - a.sin() / a - } -} - -// lanczos kernel function. A windowed sinc function. -fn lanczos(x: f32, t: f32) -> f32 { - if x.abs() < t { - sinc(x) * sinc(x / t) - } else { - 0.0 - } -} - -// Calculate a splice based on the b and c parameters. -// from authors Mitchell and Netravali. -fn bc_cubic_spline(x: f32, b: f32, c: f32) -> f32 { - let a = x.abs(); - - let k = if a < 1.0 { - (12.0 - 9.0 * b - 6.0 * c) * a.powi(3) - + (-18.0 + 12.0 * b + 6.0 * c) * a.powi(2) - + (6.0 - 2.0 * b) - } else if a < 2.0 { - (-b - 6.0 * c) * a.powi(3) - + (6.0 * b + 30.0 * c) * a.powi(2) - + (-12.0 * b - 48.0 * c) * a - + (8.0 * b + 24.0 * c) - } else { - 0.0 - }; - - k / 6.0 -} - -/// The Gaussian Function. -/// ```r``` is the standard deviation. -pub(crate) fn gaussian(x: f32, r: f32) -> f32 { - ((2.0 * f32::consts::PI).sqrt() * r).recip() * (-x.powi(2) / (2.0 * r.powi(2))).exp() -} - -/// Calculate the lanczos kernel with a window of 3 -pub(crate) fn lanczos3_kernel(x: f32) -> f32 { - lanczos(x, 3.0) -} - -/// Calculate the gaussian function with a -/// standard deviation of 0.5 -pub(crate) fn gaussian_kernel(x: f32) -> f32 { - gaussian(x, 0.5) -} - -/// Calculate the Catmull-Rom cubic spline. -/// Also known as a form of `BiCubic` sampling in two dimensions. -pub(crate) fn catmullrom_kernel(x: f32) -> f32 { - bc_cubic_spline(x, 0.0, 0.5) -} - -/// Calculate the triangle function. -/// Also known as `BiLinear` sampling in two dimensions. -pub(crate) fn triangle_kernel(x: f32) -> f32 { - if x.abs() < 1.0 { - 1.0 - x.abs() - } else { - 0.0 - } -} - -/// Calculate the box kernel. -/// Only pixels inside the box should be considered, and those -/// contribute equally. So this method simply returns 1. -pub(crate) fn box_kernel(_x: f32) -> f32 { - 1.0 -} - -// Sample the rows of the supplied image using the provided filter. -// The height of the image remains unchanged. -// ```new_width``` is the desired width of the new image -// ```filter``` is the filter to use for sampling. -// ```image``` is not necessarily Rgba and the order of channels is passed through. -fn horizontal_sample( - image: &Rgba32FImage, - new_width: u32, - filter: &mut Filter, -) -> ImageBuffer> -where - P: Pixel + 'static, - S: Primitive + 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(new_width, height); - let mut ws = Vec::new(); - - let max: f32 = NumCast::from(S::DEFAULT_MAX_VALUE).unwrap(); - let min: f32 = NumCast::from(S::DEFAULT_MIN_VALUE).unwrap(); - let ratio = width as f32 / new_width as f32; - let sratio = if ratio < 1.0 { 1.0 } else { ratio }; - let src_support = filter.support * sratio; - - for outx in 0..new_width { - // Find the point in the input image corresponding to the centre - // of the current pixel in the output image. - let inputx = (outx as f32 + 0.5) * ratio; - - // Left and right are slice bounds for the input pixels relevant - // to the output pixel we are calculating. Pixel x is relevant - // if and only if (x >= left) && (x < right). - - // Invariant: 0 <= left < right <= width - - let left = (inputx - src_support).floor() as i64; - let left = clamp(left, 0, >::from(width) - 1) as u32; - - let right = (inputx + src_support).ceil() as i64; - let right = clamp( - right, - >::from(left) + 1, - >::from(width), - ) as u32; - - // Go back to left boundary of pixel, to properly compare with i - // below, as the kernel treats the centre of a pixel as 0. - let inputx = inputx - 0.5; - - ws.clear(); - let mut sum = 0.0; - for i in left..right { - let w = (filter.kernel)((i as f32 - inputx) / sratio); - ws.push(w); - sum += w; - } - ws.iter_mut().for_each(|w| *w /= sum); - - for y in 0..height { - let mut t = (0.0, 0.0, 0.0, 0.0); - - for (i, w) in ws.iter().enumerate() { - let p = image.get_pixel(left + i as u32, y); - - #[allow(deprecated)] - let vec = p.channels4(); - - t.0 += vec.0 * w; - t.1 += vec.1 * w; - t.2 += vec.2 * w; - t.3 += vec.3 * w; - } - - #[allow(deprecated)] - let t = Pixel::from_channels( - NumCast::from(FloatNearest(clamp(t.0, min, max))).unwrap(), - NumCast::from(FloatNearest(clamp(t.1, min, max))).unwrap(), - NumCast::from(FloatNearest(clamp(t.2, min, max))).unwrap(), - NumCast::from(FloatNearest(clamp(t.3, min, max))).unwrap(), - ); - - out.put_pixel(outx, y, t); - } - } - - out -} - -/// Linearly sample from an image using coordinates in [0, 1]. -pub fn sample_bilinear( - img: &impl GenericImageView, - u: f32, - v: f32, -) -> Option

{ - if ![u, v].iter().all(|c| (0.0..=1.0).contains(c)) { - return None; - } - - let (w, h) = img.dimensions(); - if w == 0 || h == 0 { - return None; - } - - let ui = w as f32 * u - 0.5; - let vi = h as f32 * v - 0.5; - interpolate_bilinear( - img, - ui.max(0.).min((w - 1) as f32), - vi.max(0.).min((h - 1) as f32), - ) -} - -/// Sample from an image using coordinates in [0, 1], taking the nearest coordinate. -pub fn sample_nearest( - img: &impl GenericImageView, - u: f32, - v: f32, -) -> Option

{ - if ![u, v].iter().all(|c| (0.0..=1.0).contains(c)) { - return None; - } - - let (w, h) = img.dimensions(); - let ui = w as f32 * u - 0.5; - let ui = ui.max(0.).min((w.saturating_sub(1)) as f32); - - let vi = h as f32 * v - 0.5; - let vi = vi.max(0.).min((h.saturating_sub(1)) as f32); - interpolate_nearest(img, ui, vi) -} - -/// Sample from an image using coordinates in [0, w-1] and [0, h-1], taking the -/// nearest pixel. -/// -/// Coordinates outside the image bounds will return `None`, however the -/// behavior for points within half a pixel of the image bounds may change in -/// the future. -pub fn interpolate_nearest( - img: &impl GenericImageView, - x: f32, - y: f32, -) -> Option

{ - let (w, h) = img.dimensions(); - if w == 0 || h == 0 { - return None; - } - if !(0.0..=((w - 1) as f32)).contains(&x) { - return None; - } - if !(0.0..=((h - 1) as f32)).contains(&y) { - return None; - } - - Some(img.get_pixel(x.round() as u32, y.round() as u32)) -} - -/// Linearly sample from an image using coordinates in [0, w-1] and [0, h-1]. -pub fn interpolate_bilinear( - img: &impl GenericImageView, - x: f32, - y: f32, -) -> Option

{ - let (w, h) = img.dimensions(); - if w == 0 || h == 0 { - return None; - } - if !(0.0..=((w - 1) as f32)).contains(&x) { - return None; - } - if !(0.0..=((h - 1) as f32)).contains(&y) { - return None; - } - - let uf = x.floor(); - let vf = y.floor(); - let uc = (x + 1.).min((w - 1) as f32); - let vc = (y + 1.).min((h - 1) as f32); - - // clamp coords to the range of the image - let coords = [[uf, vf], [uf, vc], [uc, vf], [uc, vc]]; - - assert!(coords - .iter() - .all(|&[u, v]| { img.in_bounds(u as u32, v as u32) })); - let samples = coords.map(|[u, v]| img.get_pixel(u as u32, v as u32)); - assert!(P::CHANNEL_COUNT <= 4); - - // convert samples to f32 - // currently rgba is the largest one, - // so just store as many items as necessary, - // because there's not a simple way to be generic over all of them. - let [sff, sfc, scf, scc] = samples.map(|s| { - let mut out = [0.; 4]; - for (i, c) in s.channels().iter().enumerate() { - out[i] = c.to_f32().unwrap(); - } - out - }); - // weights - let [ufw, vfw] = [x - uf, y - vf]; - let [ucw, vcw] = [1. - ufw, 1. - vfw]; - - // https://en.wikipedia.org/wiki/Bilinear_interpolation#Weighted_mean - // the distance between pixels is 1 so there is no denominator - let wff = ucw * vcw; - let wfc = ucw * vfw; - let wcf = ufw * vcw; - let wcc = ufw * vfw; - assert!(f32::abs((wff + wfc + wcf + wcc) - 1.) < 1e-3); - - // hack to get around not being able to construct a generic Pixel - let mut out = samples[0]; - for (i, c) in out.channels_mut().iter_mut().enumerate() { - let v = wff * sff[i] + wfc * sfc[i] + wcf * scf[i] + wcc * scc[i]; - // this rounding may introduce quantization errors, - // but cannot do anything about it. - *c = ::from(v.round()).unwrap_or({ - if v < 0.0 { - P::Subpixel::DEFAULT_MIN_VALUE - } else { - P::Subpixel::DEFAULT_MAX_VALUE - } - }) - } - Some(out) -} - -// Sample the columns of the supplied image using the provided filter. -// The width of the image remains unchanged. -// ```new_height``` is the desired height of the new image -// ```filter``` is the filter to use for sampling. -// The return value is not necessarily Rgba, the underlying order of channels in ```image``` is -// preserved. -fn vertical_sample(image: &I, new_height: u32, filter: &mut Filter) -> Rgba32FImage -where - I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(width, new_height); - let mut ws = Vec::new(); - - let ratio = height as f32 / new_height as f32; - let sratio = if ratio < 1.0 { 1.0 } else { ratio }; - let src_support = filter.support * sratio; - - for outy in 0..new_height { - // For an explanation of this algorithm, see the comments - // in horizontal_sample. - let inputy = (outy as f32 + 0.5) * ratio; - - let left = (inputy - src_support).floor() as i64; - let left = clamp(left, 0, >::from(height) - 1) as u32; - - let right = (inputy + src_support).ceil() as i64; - let right = clamp( - right, - >::from(left) + 1, - >::from(height), - ) as u32; - - let inputy = inputy - 0.5; - - ws.clear(); - let mut sum = 0.0; - for i in left..right { - let w = (filter.kernel)((i as f32 - inputy) / sratio); - ws.push(w); - sum += w; - } - ws.iter_mut().for_each(|w| *w /= sum); - - for x in 0..width { - let mut t = (0.0, 0.0, 0.0, 0.0); - - for (i, w) in ws.iter().enumerate() { - let p = image.get_pixel(x, left + i as u32); - - #[allow(deprecated)] - let (k1, k2, k3, k4) = p.channels4(); - let vec: (f32, f32, f32, f32) = ( - NumCast::from(k1).unwrap(), - NumCast::from(k2).unwrap(), - NumCast::from(k3).unwrap(), - NumCast::from(k4).unwrap(), - ); - - t.0 += vec.0 * w; - t.1 += vec.1 * w; - t.2 += vec.2 * w; - t.3 += vec.3 * w; - } - - #[allow(deprecated)] - // This is not necessarily Rgba. - let t = Pixel::from_channels(t.0, t.1, t.2, t.3); - - out.put_pixel(x, outy, t); - } - } - - out -} - -/// Local struct for keeping track of pixel sums for fast thumbnail averaging -struct ThumbnailSum(S::Larger, S::Larger, S::Larger, S::Larger); - -impl ThumbnailSum { - fn zeroed() -> Self { - ThumbnailSum( - S::Larger::zero(), - S::Larger::zero(), - S::Larger::zero(), - S::Larger::zero(), - ) - } - - fn sample_val(val: S) -> S::Larger { - ::from(val).unwrap() - } - - fn add_pixel>(&mut self, pixel: P) { - #[allow(deprecated)] - let pixel = pixel.channels4(); - self.0 += Self::sample_val(pixel.0); - self.1 += Self::sample_val(pixel.1); - self.2 += Self::sample_val(pixel.2); - self.3 += Self::sample_val(pixel.3); - } -} - -/// Resize the supplied image to the specific dimensions. -/// -/// For downscaling, this method uses a fast integer algorithm where each source pixel contributes -/// to exactly one target pixel. May give aliasing artifacts if new size is close to old size. -/// -/// In case the current width is smaller than the new width or similar for the height, another -/// strategy is used instead. For each pixel in the output, a rectangular region of the input is -/// determined, just as previously. But when no input pixel is part of this region, the nearest -/// pixels are interpolated instead. -/// -/// For speed reasons, all interpolation is performed linearly over the colour values. It will not -/// take the pixel colour spaces into account. -pub fn thumbnail(image: &I, new_width: u32, new_height: u32) -> ImageBuffer> -where - I: GenericImageView, - P: Pixel + 'static, - S: Primitive + Enlargeable + 'static, -{ - let (width, height) = image.dimensions(); - let mut out = ImageBuffer::new(new_width, new_height); - - let x_ratio = width as f32 / new_width as f32; - let y_ratio = height as f32 / new_height as f32; - - for outy in 0..new_height { - let bottomf = outy as f32 * y_ratio; - let topf = bottomf + y_ratio; - - let bottom = clamp(bottomf.ceil() as u32, 0, height - 1); - let top = clamp(topf.ceil() as u32, bottom, height); - - for outx in 0..new_width { - let leftf = outx as f32 * x_ratio; - let rightf = leftf + x_ratio; - - let left = clamp(leftf.ceil() as u32, 0, width - 1); - let right = clamp(rightf.ceil() as u32, left, width); - - let avg = if bottom != top && left != right { - thumbnail_sample_block(image, left, right, bottom, top) - } else if bottom != top { - // && left == right - // In the first column we have left == 0 and right > ceil(y_scale) > 0 so this - // assertion can never trigger. - debug_assert!( - left > 0 && right > 0, - "First output column must have corresponding pixels" - ); - - let fraction_horizontal = (leftf.fract() + rightf.fract()) / 2.; - thumbnail_sample_fraction_horizontal( - image, - right - 1, - fraction_horizontal, - bottom, - top, - ) - } else if left != right { - // && bottom == top - // In the first line we have bottom == 0 and top > ceil(x_scale) > 0 so this - // assertion can never trigger. - debug_assert!( - bottom > 0 && top > 0, - "First output row must have corresponding pixels" - ); - - let fraction_vertical = (topf.fract() + bottomf.fract()) / 2.; - thumbnail_sample_fraction_vertical(image, left, right, top - 1, fraction_vertical) - } else { - // bottom == top && left == right - let fraction_horizontal = (topf.fract() + bottomf.fract()) / 2.; - let fraction_vertical = (leftf.fract() + rightf.fract()) / 2.; - - thumbnail_sample_fraction_both( - image, - right - 1, - fraction_horizontal, - top - 1, - fraction_vertical, - ) - }; - - #[allow(deprecated)] - let pixel = Pixel::from_channels(avg.0, avg.1, avg.2, avg.3); - out.put_pixel(outx, outy, pixel); - } - } - - out -} - -/// Get a pixel for a thumbnail where the input window encloses at least a full pixel. -fn thumbnail_sample_block( - image: &I, - left: u32, - right: u32, - bottom: u32, - top: u32, -) -> (S, S, S, S) -where - I: GenericImageView, - P: Pixel, - S: Primitive + Enlargeable, -{ - let mut sum = ThumbnailSum::zeroed(); - - for y in bottom..top { - for x in left..right { - let k = image.get_pixel(x, y); - sum.add_pixel(k); - } - } - - let n = ::from((right - left) * (top - bottom)).unwrap(); - let round = ::from(n / NumCast::from(2).unwrap()).unwrap(); - ( - S::clamp_from((sum.0 + round) / n), - S::clamp_from((sum.1 + round) / n), - S::clamp_from((sum.2 + round) / n), - S::clamp_from((sum.3 + round) / n), - ) -} - -/// Get a thumbnail pixel where the input window encloses at least a vertical pixel. -fn thumbnail_sample_fraction_horizontal( - image: &I, - left: u32, - fraction_horizontal: f32, - bottom: u32, - top: u32, -) -> (S, S, S, S) -where - I: GenericImageView, - P: Pixel, - S: Primitive + Enlargeable, -{ - let fract = fraction_horizontal; - - let mut sum_left = ThumbnailSum::zeroed(); - let mut sum_right = ThumbnailSum::zeroed(); - for x in bottom..top { - let k_left = image.get_pixel(left, x); - sum_left.add_pixel(k_left); - - let k_right = image.get_pixel(left + 1, x); - sum_right.add_pixel(k_right); - } - - // Now we approximate: left/n*(1-fract) + right/n*fract - let fact_right = fract / ((top - bottom) as f32); - let fact_left = (1. - fract) / ((top - bottom) as f32); - - let mix_left_and_right = |leftv: S::Larger, rightv: S::Larger| { - ::from( - fact_left * leftv.to_f32().unwrap() + fact_right * rightv.to_f32().unwrap(), - ) - .expect("Average sample value should fit into sample type") - }; - - ( - mix_left_and_right(sum_left.0, sum_right.0), - mix_left_and_right(sum_left.1, sum_right.1), - mix_left_and_right(sum_left.2, sum_right.2), - mix_left_and_right(sum_left.3, sum_right.3), - ) -} - -/// Get a thumbnail pixel where the input window encloses at least a horizontal pixel. -fn thumbnail_sample_fraction_vertical( - image: &I, - left: u32, - right: u32, - bottom: u32, - fraction_vertical: f32, -) -> (S, S, S, S) -where - I: GenericImageView, - P: Pixel, - S: Primitive + Enlargeable, -{ - let fract = fraction_vertical; - - let mut sum_bot = ThumbnailSum::zeroed(); - let mut sum_top = ThumbnailSum::zeroed(); - for x in left..right { - let k_bot = image.get_pixel(x, bottom); - sum_bot.add_pixel(k_bot); - - let k_top = image.get_pixel(x, bottom + 1); - sum_top.add_pixel(k_top); - } - - // Now we approximate: bot/n*fract + top/n*(1-fract) - let fact_top = fract / ((right - left) as f32); - let fact_bot = (1. - fract) / ((right - left) as f32); - - let mix_bot_and_top = |botv: S::Larger, topv: S::Larger| { - ::from(fact_bot * botv.to_f32().unwrap() + fact_top * topv.to_f32().unwrap()) - .expect("Average sample value should fit into sample type") - }; - - ( - mix_bot_and_top(sum_bot.0, sum_top.0), - mix_bot_and_top(sum_bot.1, sum_top.1), - mix_bot_and_top(sum_bot.2, sum_top.2), - mix_bot_and_top(sum_bot.3, sum_top.3), - ) -} - -/// Get a single pixel for a thumbnail where the input window does not enclose any full pixel. -fn thumbnail_sample_fraction_both( - image: &I, - left: u32, - fraction_vertical: f32, - bottom: u32, - fraction_horizontal: f32, -) -> (S, S, S, S) -where - I: GenericImageView, - P: Pixel, - S: Primitive + Enlargeable, -{ - #[allow(deprecated)] - let k_bl = image.get_pixel(left, bottom).channels4(); - #[allow(deprecated)] - let k_tl = image.get_pixel(left, bottom + 1).channels4(); - #[allow(deprecated)] - let k_br = image.get_pixel(left + 1, bottom).channels4(); - #[allow(deprecated)] - let k_tr = image.get_pixel(left + 1, bottom + 1).channels4(); - - let frac_v = fraction_vertical; - let frac_h = fraction_horizontal; - - let fact_tr = frac_v * frac_h; - let fact_tl = frac_v * (1. - frac_h); - let fact_br = (1. - frac_v) * frac_h; - let fact_bl = (1. - frac_v) * (1. - frac_h); - - let mix = |br: S, tr: S, bl: S, tl: S| { - ::from( - fact_br * br.to_f32().unwrap() - + fact_tr * tr.to_f32().unwrap() - + fact_bl * bl.to_f32().unwrap() - + fact_tl * tl.to_f32().unwrap(), - ) - .expect("Average sample value should fit into sample type") - }; - - ( - mix(k_br.0, k_tr.0, k_bl.0, k_tl.0), - mix(k_br.1, k_tr.1, k_bl.1, k_tl.1), - mix(k_br.2, k_tr.2, k_bl.2, k_tl.2), - mix(k_br.3, k_tr.3, k_bl.3, k_tl.3), - ) -} - -/// Perform a 3x3 box filter on the supplied image. -/// ```kernel``` is an array of the filter weights of length 9. -pub fn filter3x3(image: &I, kernel: &[f32]) -> ImageBuffer> -where - I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, -{ - // The kernel's input positions relative to the current pixel. - let taps: &[(isize, isize)] = &[ - (-1, -1), - (0, -1), - (1, -1), - (-1, 0), - (0, 0), - (1, 0), - (-1, 1), - (0, 1), - (1, 1), - ]; - - let (width, height) = image.dimensions(); - - let mut out = ImageBuffer::new(width, height); - - let max = S::DEFAULT_MAX_VALUE; - let max: f32 = NumCast::from(max).unwrap(); - - let sum = match kernel.iter().fold(0.0, |s, &item| s + item) { - x if x == 0.0 => 1.0, - sum => sum, - }; - let sum = (sum, sum, sum, sum); - - for y in 1..height - 1 { - for x in 1..width - 1 { - let mut t = (0.0, 0.0, 0.0, 0.0); - - // TODO: There is no need to recalculate the kernel for each pixel. - // Only a subtract and addition is needed for pixels after the first - // in each row. - for (&k, &(a, b)) in kernel.iter().zip(taps.iter()) { - let k = (k, k, k, k); - let x0 = x as isize + a; - let y0 = y as isize + b; - - let p = image.get_pixel(x0 as u32, y0 as u32); - - #[allow(deprecated)] - let (k1, k2, k3, k4) = p.channels4(); - - let vec: (f32, f32, f32, f32) = ( - NumCast::from(k1).unwrap(), - NumCast::from(k2).unwrap(), - NumCast::from(k3).unwrap(), - NumCast::from(k4).unwrap(), - ); - - t.0 += vec.0 * k.0; - t.1 += vec.1 * k.1; - t.2 += vec.2 * k.2; - t.3 += vec.3 * k.3; - } - - let (t1, t2, t3, t4) = (t.0 / sum.0, t.1 / sum.1, t.2 / sum.2, t.3 / sum.3); - - #[allow(deprecated)] - let t = Pixel::from_channels( - NumCast::from(clamp(t1, 0.0, max)).unwrap(), - NumCast::from(clamp(t2, 0.0, max)).unwrap(), - NumCast::from(clamp(t3, 0.0, max)).unwrap(), - NumCast::from(clamp(t4, 0.0, max)).unwrap(), - ); - - out.put_pixel(x, y, t); - } - } - - out -} - -/// Resize the supplied image to the specified dimensions. -/// ```nwidth``` and ```nheight``` are the new dimensions. -/// ```filter``` is the sampling filter to use. -pub fn resize( - image: &I, - nwidth: u32, - nheight: u32, - filter: FilterType, -) -> ImageBuffer::Subpixel>> -where - I::Pixel: 'static, - ::Subpixel: 'static, -{ - // check if the new dimensions are the same as the old. if they are, make a copy instead of resampling - if (nwidth, nheight) == image.dimensions() { - let mut tmp = ImageBuffer::new(image.width(), image.height()); - tmp.copy_from(image, 0, 0).unwrap(); - return tmp; - } - - let mut method = match filter { - FilterType::Nearest => Filter { - kernel: Box::new(box_kernel), - support: 0.0, - }, - FilterType::Triangle => Filter { - kernel: Box::new(triangle_kernel), - support: 1.0, - }, - FilterType::CatmullRom => Filter { - kernel: Box::new(catmullrom_kernel), - support: 2.0, - }, - FilterType::Gaussian => Filter { - kernel: Box::new(gaussian_kernel), - support: 3.0, - }, - FilterType::Lanczos3 => Filter { - kernel: Box::new(lanczos3_kernel), - support: 3.0, - }, - }; - - // Note: tmp is not necessarily actually Rgba - let tmp: Rgba32FImage = vertical_sample(image, nheight, &mut method); - horizontal_sample(&tmp, nwidth, &mut method) -} - -/// Performs a Gaussian blur on the supplied image. -/// ```sigma``` is a measure of how much to blur by. -pub fn blur( - image: &I, - sigma: f32, -) -> ImageBuffer::Subpixel>> -where - I::Pixel: 'static, -{ - let sigma = if sigma <= 0.0 { 1.0 } else { sigma }; - - let mut method = Filter { - kernel: Box::new(|x| gaussian(x, sigma)), - support: 2.0 * sigma, - }; - - let (width, height) = image.dimensions(); - - // Keep width and height the same for horizontal and - // vertical sampling. - // Note: tmp is not necessarily actually Rgba - let tmp: Rgba32FImage = vertical_sample(image, height, &mut method); - horizontal_sample(&tmp, width, &mut method) -} - -/// Performs an unsharpen mask on the supplied image. -/// ```sigma``` is the amount to blur the image by. -/// ```threshold``` is the threshold for minimal brightness change that will be sharpened. -/// -/// See -pub fn unsharpen(image: &I, sigma: f32, threshold: i32) -> ImageBuffer> -where - I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, -{ - let mut tmp = blur(image, sigma); - - let max = S::DEFAULT_MAX_VALUE; - let max: i32 = NumCast::from(max).unwrap(); - let (width, height) = image.dimensions(); - - for y in 0..height { - for x in 0..width { - let a = image.get_pixel(x, y); - let b = tmp.get_pixel_mut(x, y); - - let p = a.map2(b, |c, d| { - let ic: i32 = NumCast::from(c).unwrap(); - let id: i32 = NumCast::from(d).unwrap(); - - let diff = (ic - id).abs(); - - if diff > threshold { - let e = clamp(ic + diff, 0, max); // FIXME what does this do for f32? clamp 0-1 integers?? - - NumCast::from(e).unwrap() - } else { - c - } - }); - - *b = p; - } - } - - tmp -} - -#[cfg(test)] -mod tests { - use super::{resize, sample_bilinear, sample_nearest, FilterType}; - use crate::{GenericImageView, ImageBuffer, RgbImage}; - #[cfg(feature = "benchmarks")] - use test; - - #[bench] - #[cfg(all(feature = "benchmarks", feature = "png"))] - fn bench_resize(b: &mut test::Bencher) { - use std::path::Path; - let img = crate::open(&Path::new("./examples/fractal.png")).unwrap(); - b.iter(|| { - test::black_box(resize(&img, 200, 200, FilterType::Nearest)); - }); - b.bytes = 800 * 800 * 3 + 200 * 200 * 3; - } - - #[test] - #[cfg(feature = "png")] - fn test_resize_same_size() { - use std::path::Path; - let img = crate::open(&Path::new("./examples/fractal.png")).unwrap(); - let resize = img.resize(img.width(), img.height(), FilterType::Triangle); - assert!(img.pixels().eq(resize.pixels())) - } - - #[test] - #[cfg(feature = "png")] - fn test_sample_bilinear() { - use std::path::Path; - let img = crate::open(&Path::new("./examples/fractal.png")).unwrap(); - assert!(sample_bilinear(&img, 0., 0.).is_some()); - assert!(sample_bilinear(&img, 1., 0.).is_some()); - assert!(sample_bilinear(&img, 0., 1.).is_some()); - assert!(sample_bilinear(&img, 1., 1.).is_some()); - assert!(sample_bilinear(&img, 0.5, 0.5).is_some()); - - assert!(sample_bilinear(&img, 1.2, 0.5).is_none()); - assert!(sample_bilinear(&img, 0.5, 1.2).is_none()); - assert!(sample_bilinear(&img, 1.2, 1.2).is_none()); - - assert!(sample_bilinear(&img, -0.1, 0.2).is_none()); - assert!(sample_bilinear(&img, 0.2, -0.1).is_none()); - assert!(sample_bilinear(&img, -0.1, -0.1).is_none()); - } - #[test] - #[cfg(feature = "png")] - fn test_sample_nearest() { - use std::path::Path; - let img = crate::open(&Path::new("./examples/fractal.png")).unwrap(); - assert!(sample_nearest(&img, 0., 0.).is_some()); - assert!(sample_nearest(&img, 1., 0.).is_some()); - assert!(sample_nearest(&img, 0., 1.).is_some()); - assert!(sample_nearest(&img, 1., 1.).is_some()); - assert!(sample_nearest(&img, 0.5, 0.5).is_some()); - - assert!(sample_nearest(&img, 1.2, 0.5).is_none()); - assert!(sample_nearest(&img, 0.5, 1.2).is_none()); - assert!(sample_nearest(&img, 1.2, 1.2).is_none()); - - assert!(sample_nearest(&img, -0.1, 0.2).is_none()); - assert!(sample_nearest(&img, 0.2, -0.1).is_none()); - assert!(sample_nearest(&img, -0.1, -0.1).is_none()); - } - #[test] - fn test_sample_bilinear_correctness() { - use crate::Rgba; - let img = ImageBuffer::from_fn(2, 2, |x, y| match (x, y) { - (0, 0) => Rgba([255, 0, 0, 0]), - (0, 1) => Rgba([0, 255, 0, 0]), - (1, 0) => Rgba([0, 0, 255, 0]), - (1, 1) => Rgba([0, 0, 0, 255]), - _ => panic!(), - }); - assert_eq!(sample_bilinear(&img, 0.5, 0.5), Some(Rgba([64; 4]))); - assert_eq!(sample_bilinear(&img, 0.0, 0.0), Some(Rgba([255, 0, 0, 0]))); - assert_eq!(sample_bilinear(&img, 0.0, 1.0), Some(Rgba([0, 255, 0, 0]))); - assert_eq!(sample_bilinear(&img, 1.0, 0.0), Some(Rgba([0, 0, 255, 0]))); - assert_eq!(sample_bilinear(&img, 1.0, 1.0), Some(Rgba([0, 0, 0, 255]))); - - assert_eq!( - sample_bilinear(&img, 0.5, 0.0), - Some(Rgba([128, 0, 128, 0])) - ); - assert_eq!( - sample_bilinear(&img, 0.0, 0.5), - Some(Rgba([128, 128, 0, 0])) - ); - assert_eq!( - sample_bilinear(&img, 0.5, 1.0), - Some(Rgba([0, 128, 0, 128])) - ); - assert_eq!( - sample_bilinear(&img, 1.0, 0.5), - Some(Rgba([0, 0, 128, 128])) - ); - } - #[test] - fn test_sample_nearest_correctness() { - use crate::Rgba; - let img = ImageBuffer::from_fn(2, 2, |x, y| match (x, y) { - (0, 0) => Rgba([255, 0, 0, 0]), - (0, 1) => Rgba([0, 255, 0, 0]), - (1, 0) => Rgba([0, 0, 255, 0]), - (1, 1) => Rgba([0, 0, 0, 255]), - _ => panic!(), - }); - - assert_eq!(sample_nearest(&img, 0.0, 0.0), Some(Rgba([255, 0, 0, 0]))); - assert_eq!(sample_nearest(&img, 0.0, 1.0), Some(Rgba([0, 255, 0, 0]))); - assert_eq!(sample_nearest(&img, 1.0, 0.0), Some(Rgba([0, 0, 255, 0]))); - assert_eq!(sample_nearest(&img, 1.0, 1.0), Some(Rgba([0, 0, 0, 255]))); - - assert_eq!(sample_nearest(&img, 0.5, 0.5), Some(Rgba([0, 0, 0, 255]))); - assert_eq!(sample_nearest(&img, 0.5, 0.0), Some(Rgba([0, 0, 255, 0]))); - assert_eq!(sample_nearest(&img, 0.0, 0.5), Some(Rgba([0, 255, 0, 0]))); - assert_eq!(sample_nearest(&img, 0.5, 1.0), Some(Rgba([0, 0, 0, 255]))); - assert_eq!(sample_nearest(&img, 1.0, 0.5), Some(Rgba([0, 0, 0, 255]))); - } - - #[bench] - #[cfg(all(feature = "benchmarks", feature = "tiff"))] - fn bench_resize_same_size(b: &mut test::Bencher) { - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/images/tiff/testsuite/mandrill.tiff" - ); - let image = crate::open(path).unwrap(); - b.iter(|| { - test::black_box(image.resize(image.width(), image.height(), FilterType::CatmullRom)); - }); - b.bytes = (image.width() * image.height() * 3) as u64; - } - - #[test] - fn test_issue_186() { - let img: RgbImage = ImageBuffer::new(100, 100); - let _ = resize(&img, 50, 50, FilterType::Lanczos3); - } - - #[bench] - #[cfg(all(feature = "benchmarks", feature = "tiff"))] - fn bench_thumbnail(b: &mut test::Bencher) { - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/images/tiff/testsuite/mandrill.tiff" - ); - let image = crate::open(path).unwrap(); - b.iter(|| { - test::black_box(image.thumbnail(256, 256)); - }); - b.bytes = 512 * 512 * 4 + 256 * 256 * 4; - } - - #[bench] - #[cfg(all(feature = "benchmarks", feature = "tiff"))] - fn bench_thumbnail_upsize(b: &mut test::Bencher) { - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/images/tiff/testsuite/mandrill.tiff" - ); - let image = crate::open(path).unwrap().thumbnail(256, 256); - b.iter(|| { - test::black_box(image.thumbnail(512, 512)); - }); - b.bytes = 512 * 512 * 4 + 256 * 256 * 4; - } - - #[bench] - #[cfg(all(feature = "benchmarks", feature = "tiff"))] - fn bench_thumbnail_upsize_irregular(b: &mut test::Bencher) { - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/images/tiff/testsuite/mandrill.tiff" - ); - let image = crate::open(path).unwrap().thumbnail(193, 193); - b.iter(|| { - test::black_box(image.thumbnail(256, 256)); - }); - b.bytes = 193 * 193 * 4 + 256 * 256 * 4; - } - - #[test] - #[cfg(feature = "png")] - fn resize_transparent_image() { - use super::FilterType::{CatmullRom, Gaussian, Lanczos3, Nearest, Triangle}; - use crate::imageops::crop_imm; - use crate::RgbaImage; - - fn assert_resize(image: &RgbaImage, filter: FilterType) { - let resized = resize(image, 16, 16, filter); - let cropped = crop_imm(&resized, 5, 5, 6, 6).to_image(); - for pixel in cropped.pixels() { - let alpha = pixel.0[3]; - assert!( - alpha != 254 && alpha != 253, - "alpha value: {}, {:?}", - alpha, - filter - ); - } - } - - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/tests/images/png/transparency/tp1n3p08.png" - ); - let img = crate::open(path).unwrap(); - let rgba8 = img.as_rgba8().unwrap(); - let filters = &[Nearest, Triangle, CatmullRom, Gaussian, Lanczos3]; - for filter in filters { - assert_resize(rgba8, *filter); - } - } - - #[test] - fn bug_1600() { - let image = crate::RgbaImage::from_raw(629, 627, vec![255; 629 * 627 * 4]).unwrap(); - let result = resize(&image, 22, 22, FilterType::Lanczos3); - assert!(result.into_raw().into_iter().any(|c| c != 0)); - } -} -- cgit v1.2.3