Vendor things

This commit is contained in:
John Doty 2024-03-08 11:03:01 -08:00
parent 5deceec006
commit 977e3c17e5
19434 changed files with 10682014 additions and 0 deletions

View file

@ -0,0 +1,411 @@
//! 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<I: GenericImageView>(
image: &I,
) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::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<I: GenericImageView>(
image: &I,
) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::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<I: GenericImageView>(
image: &I,
) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::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<I, Container>(
image: &I,
destination: &mut ImageBuffer<I::Pixel, Container>,
) -> crate::ImageResult<()>
where
I: GenericImageView,
I::Pixel: 'static,
Container: std::ops::DerefMut<Target = [<I::Pixel as Pixel>::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<I, Container>(
image: &I,
destination: &mut ImageBuffer<I::Pixel, Container>,
) -> crate::ImageResult<()>
where
I: GenericImageView,
I::Pixel: 'static,
Container: std::ops::DerefMut<Target = [<I::Pixel as Pixel>::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<I, Container>(
image: &I,
destination: &mut ImageBuffer<I::Pixel, Container>,
) -> crate::ImageResult<()>
where
I: GenericImageView,
I::Pixel: 'static,
Container: std::ops::DerefMut<Target = [<I::Pixel as Pixel>::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<I: GenericImageView>(
image: &I,
) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::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<I: GenericImageView>(
image: &I,
) -> ImageBuffer<I::Pixel, Vec<<I::Pixel as Pixel>::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<I, Container>(
image: &I,
destination: &mut ImageBuffer<I::Pixel, Container>,
) -> crate::ImageResult<()>
where
I: GenericImageView,
I::Pixel: 'static,
Container: std::ops::DerefMut<Target = [<I::Pixel as Pixel>::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<I, Container>(
image: &I,
destination: &mut ImageBuffer<I::Pixel, Container>,
) -> crate::ImageResult<()>
where
I: GenericImageView,
I::Pixel: 'static,
Container: std::ops::DerefMut<Target = [<I::Pixel as Pixel>::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<I: GenericImage>(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<I: GenericImage>(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<I: GenericImage>(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::<Vec<_>>()
.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![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(2, 3, vec![10u8, 0u8, 11u8, 1u8, 12u8, 2u8]).unwrap();
assert_pixels_eq!(&rotate90(&image), &expected);
}
#[test]
fn test_rotate180() {
let image: GrayImage =
ImageBuffer::from_raw(3, 2, vec![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(3, 2, vec![12u8, 11u8, 10u8, 2u8, 1u8, 0u8]).unwrap();
assert_pixels_eq!(&rotate180(&image), &expected);
}
#[test]
fn test_rotate270() {
let image: GrayImage =
ImageBuffer::from_raw(3, 2, vec![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(2, 3, vec![2u8, 12u8, 1u8, 11u8, 0u8, 10u8]).unwrap();
assert_pixels_eq!(&rotate270(&image), &expected);
}
#[test]
fn test_rotate180_in_place() {
let mut image: GrayImage =
ImageBuffer::from_raw(3, 2, vec![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(3, 2, vec![12u8, 11u8, 10u8, 2u8, 1u8, 0u8]).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![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(3, 2, vec![2u8, 1u8, 0u8, 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![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(3, 2, vec![10u8, 11u8, 12u8, 0u8, 1u8, 2u8]).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![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(3, 2, vec![2u8, 1u8, 0u8, 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![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(3, 2, vec![10u8, 11u8, 12u8, 0u8, 1u8, 2u8]).unwrap();
flip_vertical_in_place(&mut image);
assert_pixels_eq!(&image, &expected);
}
#[allow(clippy::type_complexity)]
fn pixel_diffs<I, J, P>(left: &I, right: &J) -> Vec<((u32, u32, P), (u32, u32, P))>
where
I: GenericImage<Pixel = P>,
J: GenericImage<Pixel = P>,
P: Pixel + Eq,
{
left.pixels()
.zip(right.pixels())
.filter(|&(p, q)| p != q)
.collect::<Vec<_>>()
}
}

View file

@ -0,0 +1,647 @@
//! 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<I> = <<I as GenericImageView>::Pixel as Pixel>::Subpixel;
/// Convert the supplied image to grayscale. Alpha channel is discarded.
pub fn grayscale<I: GenericImageView>(
image: &I,
) -> ImageBuffer<Luma<Subpixel<I>>, Vec<Subpixel<I>>> {
grayscale_with_type(image)
}
/// Convert the supplied image to grayscale. Alpha channel is preserved.
pub fn grayscale_alpha<I: GenericImageView>(
image: &I,
) -> ImageBuffer<LumaA<Subpixel<I>>, Vec<Subpixel<I>>> {
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<NewPixel, I: GenericImageView>(
image: &I,
) -> ImageBuffer<NewPixel, Vec<NewPixel::Subpixel>>
where
NewPixel: Pixel + FromColor<Luma<Subpixel<I>>>,
{
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<NewPixel, I: GenericImageView>(
image: &I,
) -> ImageBuffer<NewPixel, Vec<NewPixel::Subpixel>>
where
NewPixel: Pixel + FromColor<LumaA<Subpixel<I>>>,
{
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<I: GenericImage>(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<I, P, S>(image: &I, contrast: f32) -> ImageBuffer<P, Vec<S>>
where
I: GenericImageView<Pixel = P>,
P: Pixel<Subpixel = S> + '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<I>(image: &mut I, contrast: f32)
where
I: GenericImage,
{
let (width, height) = image.dimensions();
let max = <I::Pixel as Pixel>::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<I, P, S>(image: &I, value: i32) -> ImageBuffer<P, Vec<S>>
where
I: GenericImageView<Pixel = P>,
P: Pixel<Subpixel = S> + '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<I>(image: &mut I, value: i32)
where
I: GenericImage,
{
let (width, height) = image.dimensions();
let max = <I::Pixel as Pixel>::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<I, P, S>(image: &I, value: i32) -> ImageBuffer<P, Vec<S>>
where
I: GenericImageView<Pixel = P>,
P: Pixel<Subpixel = S> + '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<I>(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<Self::Color> {
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<u8> { [(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<u8> {
/// 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<u8>;
#[inline(always)]
fn index_of(&self, color: &Luma<u8>) -> usize {
let luma = color.0;
if luma[0] > 127 {
1
} else {
0
}
}
#[inline(always)]
fn lookup(&self, idx: usize) -> Option<Self::Color> {
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<u8>) {
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<u8>;
#[inline(always)]
fn index_of(&self, color: &Rgba<u8>) -> usize {
self.index_of(color.channels())
}
#[inline(always)]
fn lookup(&self, idx: usize) -> Option<Self::Color> {
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<u8>) {
self.map_pixel(color.channels_mut())
}
}
/// Floyd-Steinberg error diffusion
fn diffuse_err<P: Pixel<Subpixel = u8>>(pixel: &mut P, error: [i16; 3], factor: i16) {
for (e, c) in error.iter().zip(pixel.channels_mut().iter_mut()) {
*c = match <i16 as From<_>>::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 = <i16 as From<_>>::from(old) - <i16 as From<_>>::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<Pix, Map>(image: &mut ImageBuffer<Pix, Vec<u8>>, color_map: &Map)
where
Map: ColorMap<Color = Pix> + ?Sized,
Pix: Pixel<Subpixel = u8> + '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<Pix, Map>(
image: &ImageBuffer<Pix, Vec<u8>>,
color_map: &Map,
) -> ImageBuffer<Luma<u8>, Vec<u8>>
where
Map: ColorMap<Color = Pix> + ?Sized,
Pix: Pixel<Subpixel = u8> + '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;
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::<Vec<_>>()
.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 image: GrayImage =
ImageBuffer::from_raw(3, 2, vec![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
let expected: GrayImage =
ImageBuffer::from_raw(3, 2, vec![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap();
assert_pixels_eq!(&grayscale(&image), &expected);
}
#[test]
fn test_invert() {
let mut image: GrayImage =
ImageBuffer::from_raw(3, 2, vec![0u8, 1u8, 2u8, 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![0u8, 1u8, 2u8, 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![0u8, 1u8, 2u8, 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);
}
#[allow(clippy::type_complexity)]
fn pixel_diffs<I, J, P>(left: &I, right: &J) -> Vec<((u32, u32, P), (u32, u32, P))>
where
I: GenericImage<Pixel = P>,
J: GenericImage<Pixel = P>,
P: Pixel + Eq,
{
left.pixels()
.zip(right.pixels())
.filter(|&(p, q)| p != q)
.collect::<Vec<_>>()
}
}

View file

@ -0,0 +1,485 @@
//! 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<I: GenericImageView>(
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<I: GenericImageView>(
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<I: GenericImageView>(
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<I, J>(bottom: &mut I, top: &J, x: i64, y: i64)
where
I: GenericImage,
J: GenericImageView<Pixel = I::Pixel>,
{
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<I, J>(bottom: &mut I, top: &J)
where
I: GenericImage,
J: GenericImageView<Pixel = I::Pixel>,
{
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<S, P, I>(img: &mut I, start: &P, stop: &P)
where
I: GenericImage<Pixel = P>,
P: Pixel<Subpixel = S> + 'static,
S: Primitive + Lerp + 'static,
{
for y in 0..img.height() {
let pixel = start.map2(stop, |a, b| {
let y = <S::Ratio as num_traits::NumCast>::from(y).unwrap();
let height = <S::Ratio as num_traits::NumCast>::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<S, P, I>(img: &mut I, start: &P, stop: &P)
where
I: GenericImage<Pixel = P>,
P: Pixel<Subpixel = S> + 'static,
S: Primitive + Lerp + 'static,
{
for x in 0..img.width() {
let pixel = start.map2(stop, |a, b| {
let x = <S::Ratio as num_traits::NumCast>::from(x).unwrap();
let width = <S::Ratio as num_traits::NumCast>::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<I, J>(bottom: &mut I, top: &J, x: i64, y: i64)
where
I: GenericImage,
J: GenericImageView<Pixel = I::Pixel>,
{
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);
}
}

File diff suppressed because it is too large Load diff