diff --git a/Cargo.toml b/Cargo.toml index c8d9b72805..da7d2dc161 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "image" -version = "0.25.1" +version = "0.26.0" edition = "2021" resolver = "2" @@ -22,12 +22,12 @@ categories = ["multimedia::images", "multimedia::encoding", "encoding"] exclude = ["src/png/testdata/*", "examples/*", "tests/*"] include = [ - "/LICENSE-APACHE", - "/LICENSE-MIT", - "/README.md", - "/CHANGES.md", - "/src/", - "/benches/", + "/LICENSE-APACHE", + "/LICENSE-MIT", + "/README.md", + "/CHANGES.md", + "/src/", + "/benches/", ] [package.metadata.docs.rs] @@ -35,9 +35,12 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -bytemuck = { version = "1.8.0", features = ["extern_crate_alloc"] } # includes cast_vec +bytemuck = { version = "1.8.0", features = [ + "extern_crate_alloc", +] } # includes cast_vec byteorder-lite = "0.1.0" num-traits = { version = "0.2.0" } +pixeli = "0.2.1" # Optional dependencies color_quant = { version = "1.1", optional = true } @@ -67,7 +70,23 @@ criterion = "0.5.0" default = ["rayon", "default-formats"] # Format features -default-formats = ["avif", "bmp", "dds", "exr", "ff", "gif", "hdr", "ico", "jpeg", "png", "pnm", "qoi", "tga", "tiff", "webp"] +default-formats = [ + "avif", + "bmp", + "dds", + "exr", + "ff", + "gif", + "hdr", + "ico", + "jpeg", + "png", + "pnm", + "qoi", + "tga", + "tiff", + "webp", +] avif = ["dep:ravif", "dep:rgb"] bmp = [] dds = [] @@ -86,10 +105,17 @@ webp = ["dep:image-webp"] # Other features rayon = ["dep:rayon"] # Enables multi-threading -nasm = ["ravif?/asm"] # Enables use of nasm by rav1e (requires nasm to be installed) +nasm = [ + "ravif?/asm", +] # Enables use of nasm by rav1e (requires nasm to be installed) color_quant = ["dep:color_quant"] # Enables color quantization -avif-native = ["dep:mp4parse", "dep:dcv-color-primitives", "dep:dav1d"] # Enable native dependency libdav1d -benchmarks = [] # Build some inline benchmarks. Useful only during development (requires nightly Rust) +avif-native = [ + "dep:mp4parse", + "dep:dcv-color-primitives", + "dep:dav1d", +] # Enable native dependency libdav1d +benchmarks = [ +] # Build some inline benchmarks. Useful only during development (requires nightly Rust) [[bench]] path = "benches/decode.rs" diff --git a/README.md b/README.md index e3eb168058..7c8eb542a0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Image + [![crates.io](https://img.shields.io/crates/v/image.svg)](https://crates.io/crates/image) [![Documentation](https://docs.rs/image/badge.svg)](https://docs.rs/image) [![Build Status](https://github.com/image-rs/image/workflows/Rust%20CI/badge.svg)](https://github.com/image-rs/image/actions) @@ -42,23 +43,23 @@ image format encoders and decoders. -| Format | Decoding | Encoding | -| -------- | ----------------------------------------- | --------------------------------------- | -| AVIF | Yes (8-bit only) \* | Yes (lossy only) | -| BMP | Yes | Yes | -| DDS | Yes | --- | -| Farbfeld | Yes | Yes | -| GIF | Yes | Yes | -| HDR | Yes | Yes | -| ICO | Yes | Yes | -| JPEG | Yes | Yes | -| EXR | Yes | Yes | -| PNG | Yes | Yes | -| PNM | Yes | Yes | -| QOI | Yes | Yes | -| TGA | Yes | Yes | -| TIFF | Yes | Yes | -| WebP | Yes | Yes (lossless only) | +| Format | Decoding | Encoding | +| -------- | ------------------- | ------------------- | +| AVIF | Yes (8-bit only) \* | Yes (lossy only) | +| BMP | Yes | Yes | +| DDS | Yes | --- | +| Farbfeld | Yes | Yes | +| GIF | Yes | Yes | +| HDR | Yes | Yes | +| ICO | Yes | Yes | +| JPEG | Yes | Yes | +| EXR | Yes | Yes | +| PNG | Yes | Yes | +| PNM | Yes | Yes | +| QOI | Yes | Yes | +| TGA | Yes | Yes | +| TIFF | Yes | Yes | +| WebP | Yes | Yes (lossless only) | - \* Requires the `avif-native` feature, uses the libdav1d C library. @@ -68,11 +69,13 @@ This crate provides a number of different types for representing images. Individual pixels within images are indexed with (0,0) at the top left corner. ### [`ImageBuffer`](https://docs.rs/image/*/image/struct.ImageBuffer.html) + An image parameterised by its Pixel type, represented by a width and height and a vector of pixels. It provides direct access to its pixels and implements the `GenericImageView` and `GenericImage` traits. ### [`DynamicImage`](https://docs.rs/image/*/image/enum.DynamicImage.html) + A `DynamicImage` is an enumeration over all supported `ImageBuffer

` types. Its exact image type is determined at runtime. It is the type returned when opening an image. For convenience `DynamicImage` reimplements all image @@ -83,11 +86,11 @@ processing functions. Traits that provide methods for inspecting (`GenericImageView`) and manipulating (`GenericImage`) images, parameterised over the image's pixel type. ### [`SubImage`](https://docs.rs/image/*/image/struct.SubImage.html) + A view into another image, delimited by the coordinates of a rectangle. The coordinates given set the position of the top left corner of the rectangle. This is used to perform image processing functions on a subregion of an image. - ## The [`ImageDecoder`](https://docs.rs/image/*/image/trait.ImageDecoder.html) and [`ImageDecoderRect`](https://docs.rs/image/*/image/trait.ImageDecoderRect.html) Traits All image format decoders implement the `ImageDecoder` trait which provide @@ -96,46 +99,50 @@ additionally provide `ImageDecoderRect` implementations which allow for decoding only part of an image at once. The most important methods for decoders are... -+ **dimensions**: Return a tuple containing the width and height of the image. -+ **color_type**: Return the color type of the image data produced by this decoder. -+ **read_image**: Decode the entire image into a slice of bytes. + +- **dimensions**: Return a tuple containing the width and height of the image. +- **color_type**: Return the color type of the image data produced by this decoder. +- **read_image**: Decode the entire image into a slice of bytes. ## Pixels `image` provides the following pixel types: -+ **Rgb**: RGB pixel -+ **Rgba**: RGB with alpha (RGBA pixel) -+ **Luma**: Grayscale pixel -+ **LumaA**: Grayscale with alpha + +- **Rgb**: RGB pixel +- **Rgba**: RGB with alpha (RGBA pixel) +- **Luma**: Grayscale pixel +- **LumaA**: Grayscale with alpha All pixels are parameterised by their component type. ## Image Processing Functions + These are the functions defined in the `imageops` module. All functions operate on types that implement the `GenericImage` trait. Note that some of the functions are very slow in debug mode. Make sure to use release mode if you experience any performance issues. -+ **blur**: Performs a Gaussian blur on the supplied image. -+ **brighten**: Brighten the supplied image. -+ **huerotate**: Hue rotate the supplied image by degrees. -+ **contrast**: Adjust the contrast of the supplied image. -+ **crop**: Return a mutable view into an image. -+ **filter3x3**: Perform a 3x3 box filter on the supplied image. -+ **flip_horizontal**: Flip an image horizontally. -+ **flip_vertical**: Flip an image vertically. -+ **grayscale**: Convert the supplied image to grayscale. -+ **invert**: Invert each pixel within the supplied image This function operates in place. -+ **resize**: Resize the supplied image to the specified dimensions. -+ **rotate180**: Rotate an image 180 degrees clockwise. -+ **rotate270**: Rotate an image 270 degrees clockwise. -+ **rotate90**: Rotate an image 90 degrees clockwise. -+ **unsharpen**: Performs an unsharpen mask on the supplied image. +- **blur**: Performs a Gaussian blur on the supplied image. +- **brighten**: Brighten the supplied image. +- **huerotate**: Hue rotate the supplied image by degrees. +- **contrast**: Adjust the contrast of the supplied image. +- **crop**: Return a mutable view into an image. +- **filter3x3**: Perform a 3x3 box filter on the supplied image. +- **flip_horizontal**: Flip an image horizontally. +- **flip_vertical**: Flip an image vertically. +- **grayscale**: Convert the supplied image to grayscale. +- **invert**: Invert each pixel within the supplied image This function operates in place. +- **resize**: Resize the supplied image to the specified dimensions. +- **rotate180**: Rotate an image 180 degrees clockwise. +- **rotate270**: Rotate an image 270 degrees clockwise. +- **rotate90**: Rotate an image 90 degrees clockwise. +- **unsharpen**: Performs an unsharpen mask on the supplied image. For more options, see the [`imageproc`](https://crates.io/crates/imageproc) crate. ## Examples + ### Opening and Saving Images -`image` provides the `open` function for opening images from a path. The image +`image` provides the `open` function for opening images from a path. The image format is determined from the path's file extension. An `io` module provides a reader which offer some more control. @@ -173,7 +180,7 @@ let mut imgbuf = image::ImageBuffer::new(imgx, imgy); for (x, y, pixel) in imgbuf.enumerate_pixels_mut() { let r = (0.3 * x as f32) as u8; let b = (0.3 * y as f32) as u8; - *pixel = image::Rgb([r, 0, b]); + *pixel = pixeli::Rgb{r, g: 0, b}; } // A redundant loop to demonstrate reading image data @@ -192,8 +199,7 @@ for x in 0..imgx { } let pixel = imgbuf.get_pixel_mut(x, y); - let image::Rgb(data) = *pixel; - *pixel = image::Rgb([data[0], i as u8, data[2]]); + *pixel = pixeli::Rgb{r: pixel.r, g: i as u8, b: pixel.b}; } } @@ -206,6 +212,7 @@ Example output: A Julia Fractal, c: -0.4 + 0.6i ### Writing raw buffers + If the high level interface is not needed because the image was obtained by other means, `image` provides the function `save_buffer` to save a buffer to a file. ```rust,no_run diff --git a/benches/copy_from.rs b/benches/copy_from.rs index 37a4af8b9d..2731f1951f 100644 --- a/benches/copy_from.rs +++ b/benches/copy_from.rs @@ -1,9 +1,28 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use image::{GenericImage, ImageBuffer, Rgba}; +use image::{GenericImage, ImageBuffer}; +use pixeli::Rgba; pub fn bench_copy_from(c: &mut Criterion) { - let src = ImageBuffer::from_pixel(2048, 2048, Rgba([255u8, 0, 0, 255])); - let mut dst = ImageBuffer::from_pixel(2048, 2048, Rgba([0u8, 0, 0, 255])); + let src = ImageBuffer::from_pixel( + 2048, + 2048, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); + let mut dst = ImageBuffer::from_pixel( + 2048, + 2048, + Rgba { + r: 0u8, + g: 0, + b: 0, + a: 255, + }, + ); c.bench_function("copy_from", |b| { b.iter(|| dst.copy_from(black_box(&src), 0, 0)) diff --git a/examples/concat/main.rs b/examples/concat/main.rs index 63dcb09167..0bc9413e50 100644 --- a/examples/concat/main.rs +++ b/examples/concat/main.rs @@ -1,4 +1,5 @@ -use image::{GenericImage, GenericImageView, ImageBuffer, Pixel, Primitive}; +use image::{Blend, GenericImage, GenericImageView, ImageBuffer}; +use pixeli::{ContiguousPixel, Pixel, PixelComponent}; /// Example showcasing a generic implementation of image concatenation. /// @@ -20,8 +21,8 @@ fn main() { fn h_concat(images: &[I]) -> ImageBuffer> where I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, + P: Pixel + ContiguousPixel + Blend + 'static, + S: PixelComponent + 'static, { // The final width is the sum of all images width. let img_width_out: u32 = images.iter().map(|im| im.width()).sum(); diff --git a/examples/fractal.rs b/examples/fractal.rs index bba52ae93c..2197506ed1 100644 --- a/examples/fractal.rs +++ b/examples/fractal.rs @@ -1,4 +1,6 @@ //! An example of generating julia fractals. + +use pixeli::Rgb; extern crate image; extern crate num_complex; @@ -16,7 +18,7 @@ fn main() { for (x, y, pixel) in imgbuf.enumerate_pixels_mut() { let r = (0.3 * x as f32) as u8; let b = (0.3 * y as f32) as u8; - *pixel = image::Rgb([r, 0, b]); + *pixel = Rgb { r, g: 0, b }; } // A redundant loop to demonstrate reading image data @@ -35,8 +37,11 @@ fn main() { } let pixel = imgbuf.get_pixel_mut(x, y); - let data = (*pixel as image::Rgb).0; - *pixel = image::Rgb([data[0], i as u8, data[2]]); + *pixel = Rgb { + r: pixel.r, + g: i as u8, + b: pixel.b, + }; } } diff --git a/examples/gradient/main.rs b/examples/gradient/main.rs index 4436885a2d..f26aa91fcd 100644 --- a/examples/gradient/main.rs +++ b/examples/gradient/main.rs @@ -1,16 +1,27 @@ -use image::{Pixel, Rgba, RgbaImage}; +use image::RgbaImage; +use pixeli::Rgba; fn main() { 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]); + let start = Rgba { + r: 0, + g: 128, + b: 0, + a: 0, + }; + let end = Rgba { + r: 255, + g: 255, + b: 255, + a: 255, + }; - image::imageops::vertical_gradient(&mut img, start, end); + image::imageops::vertical_gradient(&mut img, &start, &end); img.save("vertical_gradient.png").unwrap(); - image::imageops::vertical_gradient(&mut img, end, start); + image::imageops::vertical_gradient(&mut img, &end, &start); img.save("vertical_gradient_reverse.png").unwrap(); - image::imageops::horizontal_gradient(&mut img, start, end); + image::imageops::horizontal_gradient(&mut img, &start, &end); img.save("horizontal_gradient.png").unwrap(); } diff --git a/fuzz/fuzzers/roundtrip_webp.rs b/fuzz/fuzzers/roundtrip_webp.rs index 5f305839d2..94589dd6ea 100644 --- a/fuzz/fuzzers/roundtrip_webp.rs +++ b/fuzz/fuzzers/roundtrip_webp.rs @@ -5,8 +5,10 @@ use std::io::Cursor; -use image::{ImageBuffer, Rgba}; -#[macro_use] extern crate libfuzzer_sys; +use image::ImageBuffer; +use image::pixeli::Rgba; +#[macro_use] +extern crate libfuzzer_sys; extern crate image; fuzz_target!(|data: &[u8]| { @@ -22,17 +24,18 @@ fuzz_target!(|data: &[u8]| { let content_len = width * height * 4; if content.len() >= content_len { let content = content[..content_len].to_owned(); - let image : ImageBuffer, Vec> = ImageBuffer::from_vec( - width as u32, height as u32, - content - ).unwrap(); + let image: ImageBuffer, Vec> = + ImageBuffer::from_vec(width as u32, height as u32, content).unwrap(); let encoded: Vec = Vec::new(); let mut cursor = Cursor::new(encoded); - image.write_to(&mut cursor, image::ImageFormat::WebP).unwrap(); + image + .write_to(&mut cursor, image::ImageFormat::WebP) + .unwrap(); let encoded = cursor.into_inner(); // verify that the imade decoded without errors - let decoded = image::load_from_memory_with_format(&encoded, image::ImageFormat::WebP).unwrap(); + let decoded = + image::load_from_memory_with_format(&encoded, image::ImageFormat::WebP).unwrap(); // compare contents - the encoding should be lossless and roundtrip bit-perfectly assert_eq!(image.into_vec(), decoded.into_bytes()); } diff --git a/src/buffer.rs b/src/buffer.rs index 404751522c..ce3741aeef 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -1,38 +1,42 @@ //! Contains the generic `ImageBuffer` struct. use num_traits::Zero; +use pixeli::{ContiguousPixel, FromPixelCommon, Gray, GrayAlpha, Pixel, Rgb, Rgba}; use std::fmt; use std::marker::PhantomData; use std::ops::{Deref, DerefMut, Index, IndexMut, Range}; use std::path::Path; use std::slice::{ChunksExact, ChunksExactMut}; -use crate::color::{FromColor, Luma, LumaA, Rgb, Rgba}; +use crate::color::Blend; use crate::dynimage::{save_buffer, save_buffer_with_format, write_buffer_with_format}; use crate::error::ImageResult; use crate::flat::{FlatSamples, SampleLayout}; use crate::image::{GenericImage, GenericImageView, ImageEncoder, ImageFormat}; use crate::math::Rect; -use crate::traits::{EncodableLayout, Pixel, PixelWithColorType}; +use crate::traits::{EncodableLayout, PixelWithColorType}; use crate::utils::expand_packed; use crate::DynamicImage; /// Iterate over pixel refs. pub struct Pixels<'a, P: Pixel + 'a> where - P::Subpixel: 'a, + P::Component: 'a, { - chunks: ChunksExact<'a, P::Subpixel>, + chunks: ChunksExact<'a, P::Component>, } -impl<'a, P: Pixel + 'a> Iterator for Pixels<'a, P> +impl<'a, P: 'a> Iterator for Pixels<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { type Item = &'a P; #[inline(always)] fn next(&mut self) -> Option<&'a P> { - self.chunks.next().map(|v|

::from_slice(v)) + self.chunks + .next() + .map(|v|

::from_component_slice_ref(v)) } #[inline(always)] @@ -42,22 +46,26 @@ where } } -impl<'a, P: Pixel + 'a> ExactSizeIterator for Pixels<'a, P> +impl<'a, P: 'a> ExactSizeIterator for Pixels<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { fn len(&self) -> usize { self.chunks.len() } } -impl<'a, P: Pixel + 'a> DoubleEndedIterator for Pixels<'a, P> +impl<'a, P: 'a> DoubleEndedIterator for Pixels<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { #[inline(always)] fn next_back(&mut self) -> Option<&'a P> { - self.chunks.next_back().map(|v|

::from_slice(v)) + self.chunks + .next_back() + .map(|v|

::from_component_slice_ref(v)) } } @@ -71,7 +79,7 @@ impl Clone for Pixels<'_, P> { impl fmt::Debug for Pixels<'_, P> where - P::Subpixel: fmt::Debug, + P::Component: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Pixels") @@ -83,20 +91,23 @@ where /// Iterate over mutable pixel refs. pub struct PixelsMut<'a, P: Pixel + 'a> where - P::Subpixel: 'a, + P::Component: 'a, { - chunks: ChunksExactMut<'a, P::Subpixel>, + chunks: ChunksExactMut<'a, P::Component>, } -impl<'a, P: Pixel + 'a> Iterator for PixelsMut<'a, P> +impl<'a, P: 'a> Iterator for PixelsMut<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { type Item = &'a mut P; #[inline(always)] fn next(&mut self) -> Option<&'a mut P> { - self.chunks.next().map(|v|

::from_slice_mut(v)) + self.chunks + .next() + .map(|v|

::from_component_slice_mut(v)) } #[inline(always)] @@ -106,30 +117,33 @@ where } } -impl<'a, P: Pixel + 'a> ExactSizeIterator for PixelsMut<'a, P> +impl<'a, P: 'a> ExactSizeIterator for PixelsMut<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { fn len(&self) -> usize { self.chunks.len() } } -impl<'a, P: Pixel + 'a> DoubleEndedIterator for PixelsMut<'a, P> +impl<'a, P: 'a> DoubleEndedIterator for PixelsMut<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { #[inline(always)] fn next_back(&mut self) -> Option<&'a mut P> { self.chunks .next_back() - .map(|v|

::from_slice_mut(v)) + .map(|v|

::from_component_slice_mut(v)) } } -impl fmt::Debug for PixelsMut<'_, P> +impl

fmt::Debug for PixelsMut<'_, P> where - P::Subpixel: fmt::Debug, + P: ContiguousPixel, + P::Component: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("PixelsMut") @@ -145,16 +159,16 @@ where /// [`ImageBuffer::rows`]: ../struct.ImageBuffer.html#method.rows pub struct Rows<'a, P: Pixel + 'a> where -

::Subpixel: 'a, +

::Component: 'a, { - pixels: ChunksExact<'a, P::Subpixel>, + pixels: ChunksExact<'a, P::Component>, } impl<'a, P: Pixel + 'a> Rows<'a, P> { /// Construct the iterator from image pixels. This is not public since it has a (hidden) panic /// condition. The `pixels` slice must be large enough so that all pixels are addressable. - fn with_image(pixels: &'a [P::Subpixel], width: u32, height: u32) -> Self { - let row_len = (width as usize) * usize::from(

::CHANNEL_COUNT); + fn with_image(pixels: &'a [P::Component], width: u32, height: u32) -> Self { + let row_len = (width as usize) * usize::from(

::COMPONENT_COUNT); if row_len == 0 { Rows { pixels: [].chunks_exact(1), @@ -174,7 +188,7 @@ impl<'a, P: Pixel + 'a> Rows<'a, P> { impl<'a, P: Pixel + 'a> Iterator for Rows<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { type Item = Pixels<'a, P>; @@ -182,8 +196,8 @@ where fn next(&mut self) -> Option> { let row = self.pixels.next()?; Some(Pixels { - // Note: this is not reached when CHANNEL_COUNT is 0. - chunks: row.chunks_exact(

::CHANNEL_COUNT as usize), + // Note: this is not reached when COMPONENT_COUNT is 0. + chunks: row.chunks_exact(

::COMPONENT_COUNT as usize), }) } @@ -196,7 +210,7 @@ where impl<'a, P: Pixel + 'a> ExactSizeIterator for Rows<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { fn len(&self) -> usize { self.pixels.len() @@ -205,14 +219,14 @@ where impl<'a, P: Pixel + 'a> DoubleEndedIterator for Rows<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { #[inline(always)] fn next_back(&mut self) -> Option> { let row = self.pixels.next_back()?; Some(Pixels { - // Note: this is not reached when CHANNEL_COUNT is 0. - chunks: row.chunks_exact(

::CHANNEL_COUNT as usize), + // Note: this is not reached when COMPONENT_COUNT is 0. + chunks: row.chunks_exact(

::COMPONENT_COUNT as usize), }) } } @@ -227,7 +241,7 @@ impl Clone for Rows<'_, P> { impl fmt::Debug for Rows<'_, P> where - P::Subpixel: fmt::Debug, + P::Component: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Rows") @@ -243,16 +257,16 @@ where /// [`ImageBuffer::rows_mut`]: ../struct.ImageBuffer.html#method.rows_mut pub struct RowsMut<'a, P: Pixel + 'a> where -

::Subpixel: 'a, +

::Component: 'a, { - pixels: ChunksExactMut<'a, P::Subpixel>, + pixels: ChunksExactMut<'a, P::Component>, } impl<'a, P: Pixel + 'a> RowsMut<'a, P> { /// Construct the iterator from image pixels. This is not public since it has a (hidden) panic /// condition. The `pixels` slice must be large enough so that all pixels are addressable. - fn with_image(pixels: &'a mut [P::Subpixel], width: u32, height: u32) -> Self { - let row_len = (width as usize) * usize::from(

::CHANNEL_COUNT); + fn with_image(pixels: &'a mut [P::Component], width: u32, height: u32) -> Self { + let row_len = (width as usize) * usize::from(

::COMPONENT_COUNT); if row_len == 0 { RowsMut { pixels: [].chunks_exact_mut(1), @@ -272,7 +286,7 @@ impl<'a, P: Pixel + 'a> RowsMut<'a, P> { impl<'a, P: Pixel + 'a> Iterator for RowsMut<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { type Item = PixelsMut<'a, P>; @@ -280,8 +294,8 @@ where fn next(&mut self) -> Option> { let row = self.pixels.next()?; Some(PixelsMut { - // Note: this is not reached when CHANNEL_COUNT is 0. - chunks: row.chunks_exact_mut(

::CHANNEL_COUNT as usize), + // Note: this is not reached when COMPONENT_COUNT is 0. + chunks: row.chunks_exact_mut(

::COMPONENT_COUNT as usize), }) } @@ -294,7 +308,7 @@ where impl<'a, P: Pixel + 'a> ExactSizeIterator for RowsMut<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { fn len(&self) -> usize { self.pixels.len() @@ -303,21 +317,21 @@ where impl<'a, P: Pixel + 'a> DoubleEndedIterator for RowsMut<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { #[inline(always)] fn next_back(&mut self) -> Option> { let row = self.pixels.next_back()?; Some(PixelsMut { - // Note: this is not reached when CHANNEL_COUNT is 0. - chunks: row.chunks_exact_mut(

::CHANNEL_COUNT as usize), + // Note: this is not reached when COMPONENT_COUNT is 0. + chunks: row.chunks_exact_mut(

::COMPONENT_COUNT as usize), }) } } impl fmt::Debug for RowsMut<'_, P> where - P::Subpixel: fmt::Debug, + P::Component: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("RowsMut") @@ -329,7 +343,7 @@ where /// Enumerate the pixels of an image. pub struct EnumeratePixels<'a, P: Pixel + 'a> where -

::Subpixel: 'a, +

::Component: 'a, { pixels: Pixels<'a, P>, x: u32, @@ -337,9 +351,10 @@ where width: u32, } -impl<'a, P: Pixel + 'a> Iterator for EnumeratePixels<'a, P> +impl<'a, P: 'a> Iterator for EnumeratePixels<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { type Item = (u32, u32, &'a P); @@ -361,9 +376,10 @@ where } } -impl<'a, P: Pixel + 'a> ExactSizeIterator for EnumeratePixels<'a, P> +impl<'a, P: 'a> ExactSizeIterator for EnumeratePixels<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { fn len(&self) -> usize { self.pixels.len() @@ -381,7 +397,7 @@ impl Clone for EnumeratePixels<'_, P> { impl fmt::Debug for EnumeratePixels<'_, P> where - P::Subpixel: fmt::Debug, + P::Component: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("EnumeratePixels") @@ -396,7 +412,7 @@ where /// Enumerate the rows of an image. pub struct EnumerateRows<'a, P: Pixel + 'a> where -

::Subpixel: 'a, +

::Component: 'a, { rows: Rows<'a, P>, y: u32, @@ -405,7 +421,7 @@ where impl<'a, P: Pixel + 'a> Iterator for EnumerateRows<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { type Item = (u32, EnumeratePixels<'a, P>); @@ -435,7 +451,7 @@ where impl<'a, P: Pixel + 'a> ExactSizeIterator for EnumerateRows<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { fn len(&self) -> usize { self.rows.len() @@ -453,7 +469,7 @@ impl Clone for EnumerateRows<'_, P> { impl fmt::Debug for EnumerateRows<'_, P> where - P::Subpixel: fmt::Debug, + P::Component: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("EnumerateRows") @@ -467,7 +483,7 @@ where /// Enumerate the pixels of an image. pub struct EnumeratePixelsMut<'a, P: Pixel + 'a> where -

::Subpixel: 'a, +

::Component: 'a, { pixels: PixelsMut<'a, P>, x: u32, @@ -475,9 +491,10 @@ where width: u32, } -impl<'a, P: Pixel + 'a> Iterator for EnumeratePixelsMut<'a, P> +impl<'a, P: 'a> Iterator for EnumeratePixelsMut<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { type Item = (u32, u32, &'a mut P); @@ -499,18 +516,20 @@ where } } -impl<'a, P: Pixel + 'a> ExactSizeIterator for EnumeratePixelsMut<'a, P> +impl<'a, P: 'a> ExactSizeIterator for EnumeratePixelsMut<'a, P> where - P::Subpixel: 'a, + P: ContiguousPixel, + P::Component: 'a, { fn len(&self) -> usize { self.pixels.len() } } -impl fmt::Debug for EnumeratePixelsMut<'_, P> +impl

fmt::Debug for EnumeratePixelsMut<'_, P> where - P::Subpixel: fmt::Debug, + P: ContiguousPixel, + P::Component: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("EnumeratePixelsMut") @@ -525,7 +544,7 @@ where /// Enumerate the rows of an image. pub struct EnumerateRowsMut<'a, P: Pixel + 'a> where -

::Subpixel: 'a, +

::Component: 'a, { rows: RowsMut<'a, P>, y: u32, @@ -534,7 +553,7 @@ where impl<'a, P: Pixel + 'a> Iterator for EnumerateRowsMut<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { type Item = (u32, EnumeratePixelsMut<'a, P>); @@ -564,7 +583,7 @@ where impl<'a, P: Pixel + 'a> ExactSizeIterator for EnumerateRowsMut<'a, P> where - P::Subpixel: 'a, + P::Component: 'a, { fn len(&self) -> usize { self.rows.len() @@ -573,7 +592,7 @@ where impl fmt::Debug for EnumerateRowsMut<'_, P> where - P::Subpixel: fmt::Debug, + P::Component: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("EnumerateRowsMut") @@ -615,14 +634,15 @@ where /// Create a simple canvas and paint a small cross. /// /// ``` -/// use image::{RgbImage, Rgb}; +/// use image::RgbImage; +/// use pixeli::Rgb; /// /// let mut img = RgbImage::new(32, 32); /// /// for x in 15..=17 { /// for y in 8..24 { -/// img.put_pixel(x, y, Rgb([255, 0, 0])); -/// img.put_pixel(y, x, Rgb([255, 0, 0])); +/// img.put_pixel(x, y, Rgb{r: 255, g: 0, b: 0}); +/// img.put_pixel(y, x, Rgb{r: 255, g: 0, b: 0}); /// } /// } /// ``` @@ -635,9 +655,9 @@ where /// let on_top = open("path/to/some.png").unwrap().into_rgb8(); /// let mut img = ImageBuffer::from_fn(512, 512, |x, y| { /// if (x + y) % 2 == 0 { -/// image::Rgb([0, 0, 0]) +/// pixeli::Rgb{r: 0, g: 0, b: 0} /// } else { -/// image::Rgb([255, 255, 255]) +/// pixeli::Rgb{r: 255, g: 255, b: 255} /// } /// }); /// @@ -663,8 +683,8 @@ pub struct ImageBuffer { // generic implementation, shared along all image buffers impl ImageBuffer where - P: Pixel, - Container: Deref, + P: ContiguousPixel, + Container: Deref, { /// Constructs a buffer from a generic container /// (for example a `Vec` or a slice) @@ -710,7 +730,7 @@ where } // TODO: choose name under which to expose. - pub(crate) fn inner_pixels(&self) -> &[P::Subpixel] { + pub(crate) fn inner_pixels(&self) -> &[P::Component] { let len = Self::image_buffer_len(self.width, self.height).unwrap(); &self.data[..len] } @@ -721,7 +741,7 @@ where Pixels { chunks: self .inner_pixels() - .chunks_exact(

::CHANNEL_COUNT as usize), + .chunks_exact(

::COMPONENT_COUNT as usize), } } @@ -773,7 +793,9 @@ where (x, y), (self.width, self.height) ), - Some(pixel_indices) =>

::from_slice(&self.data[pixel_indices]), + Some(pixel_indices) => { +

::from_component_slice_ref(&self.data[pixel_indices]) + } } } @@ -783,7 +805,7 @@ where if x >= self.width { return None; } - let num_channels =

::CHANNEL_COUNT as usize; + let num_channels =

::COMPONENT_COUNT as usize; let i = (y as usize) .saturating_mul(self.width as usize) .saturating_add(x as usize) @@ -791,7 +813,7 @@ where self.data .get(i..i.checked_add(num_channels)?) - .map(|pixel_indices|

::from_slice(pixel_indices)) + .map(|pixel_indices|

::from_component_slice_ref(pixel_indices)) } /// Test that the image fits inside the buffer. @@ -805,7 +827,7 @@ where } fn image_buffer_len(width: u32, height: u32) -> Option { - Some(

::CHANNEL_COUNT as usize) + Some(

::COMPONENT_COUNT as usize) .and_then(|size| size.checked_mul(width as usize)) .and_then(|size| size.checked_mul(height as usize)) } @@ -821,7 +843,7 @@ where #[inline(always)] fn pixel_indices_unchecked(&self, x: u32, y: u32) -> Range { - let no_channels =

::CHANNEL_COUNT as usize; + let no_channels =

::COMPONENT_COUNT as usize; // If in bounds, this can't overflow as we have tested that at construction! let min_index = (y as usize * self.width as usize + x as usize) * no_channels; min_index..min_index + no_channels @@ -830,7 +852,7 @@ where /// Get the format of the buffer when viewed as a matrix of samples. pub fn sample_layout(&self) -> SampleLayout { // None of these can overflow, as all our memory is addressable. - SampleLayout::row_major_packed(

::CHANNEL_COUNT, self.width, self.height) + SampleLayout::row_major_packed(

::COMPONENT_COUNT, self.width, self.height) } /// Return the raw sample buffer with its stride an dimension information. @@ -841,7 +863,7 @@ where /// also byte strides. pub fn into_flat_samples(self) -> FlatSamples where - Container: AsRef<[P::Subpixel]>, + Container: AsRef<[P::Component]>, { // None of these can overflow, as all our memory is addressable. let layout = self.sample_layout(); @@ -855,9 +877,9 @@ where /// Return a view on the raw sample buffer. /// /// See [`into_flat_samples`](#method.into_flat_samples) for more details. - pub fn as_flat_samples(&self) -> FlatSamples<&[P::Subpixel]> + pub fn as_flat_samples(&self) -> FlatSamples<&[P::Component]> where - Container: AsRef<[P::Subpixel]>, + Container: AsRef<[P::Component]>, { let layout = self.sample_layout(); FlatSamples { @@ -870,9 +892,9 @@ where /// Return a mutable view on the raw sample buffer. /// /// See [`into_flat_samples`](#method.into_flat_samples) for more details. - pub fn as_flat_samples_mut(&mut self) -> FlatSamples<&mut [P::Subpixel]> + pub fn as_flat_samples_mut(&mut self) -> FlatSamples<&mut [P::Component]> where - Container: AsMut<[P::Subpixel]>, + Container: AsMut<[P::Component]>, { let layout = self.sample_layout(); FlatSamples { @@ -885,11 +907,11 @@ where impl ImageBuffer where - P: Pixel, - Container: Deref + DerefMut, + P: ContiguousPixel, + Container: Deref + DerefMut, { // TODO: choose name under which to expose. - pub(crate) fn inner_pixels_mut(&mut self) -> &mut [P::Subpixel] { + pub(crate) fn inner_pixels_mut(&mut self) -> &mut [P::Component] { let len = Self::image_buffer_len(self.width, self.height).unwrap(); &mut self.data[..len] } @@ -899,7 +921,7 @@ where PixelsMut { chunks: self .inner_pixels_mut() - .chunks_exact_mut(

::CHANNEL_COUNT as usize), + .chunks_exact_mut(

::COMPONENT_COUNT as usize), } } @@ -951,7 +973,9 @@ where (x, y), (self.width, self.height) ), - Some(pixel_indices) =>

::from_slice_mut(&mut self.data[pixel_indices]), + Some(pixel_indices) => { +

::from_component_slice_mut(&mut self.data[pixel_indices]) + } } } @@ -961,7 +985,7 @@ where if x >= self.width { return None; } - let num_channels =

::CHANNEL_COUNT as usize; + let num_channels =

::COMPONENT_COUNT as usize; let i = (y as usize) .saturating_mul(self.width as usize) .saturating_add(x as usize) @@ -969,7 +993,7 @@ where self.data .get_mut(i..i.checked_add(num_channels)?) - .map(|pixel_indices|

::from_slice_mut(pixel_indices)) + .map(|pixel_indices|

::from_component_slice_mut(pixel_indices)) } /// Puts a pixel at location `(x, y)` @@ -986,9 +1010,9 @@ where impl ImageBuffer where - P: Pixel, - [P::Subpixel]: EncodableLayout, - Container: Deref, + P: ContiguousPixel, + [P::Component]: EncodableLayout, + Container: Deref, { /// Saves the buffer to a file at the path specified. /// @@ -1010,9 +1034,9 @@ where impl ImageBuffer where - P: Pixel, - [P::Subpixel]: EncodableLayout, - Container: Deref, + P: ContiguousPixel, + [P::Component]: EncodableLayout, + Container: Deref, { /// Saves the buffer to a file at the specified path in /// the specified format. @@ -1038,9 +1062,9 @@ where impl ImageBuffer where - P: Pixel, - [P::Subpixel]: EncodableLayout, - Container: Deref, + P: ContiguousPixel, + [P::Component]: EncodableLayout, + Container: Deref, { /// Writes the buffer to a writer in the specified format. /// @@ -1065,9 +1089,9 @@ where impl ImageBuffer where - P: Pixel, - [P::Subpixel]: EncodableLayout, - Container: Deref, + P: ContiguousPixel, + [P::Component]: EncodableLayout, + Container: Deref, { /// Writes the buffer with the given encoder. pub fn write_with_encoder(&self, encoder: E) -> ImageResult<()> @@ -1103,9 +1127,9 @@ where impl Deref for ImageBuffer where P: Pixel, - Container: Deref, + Container: Deref, { - type Target = [P::Subpixel]; + type Target = [P::Component]; fn deref(&self) -> &::Target { &self.data @@ -1115,7 +1139,7 @@ where impl DerefMut for ImageBuffer where P: Pixel, - Container: Deref + DerefMut, + Container: Deref + DerefMut, { fn deref_mut(&mut self) -> &mut ::Target { &mut self.data @@ -1124,8 +1148,8 @@ where impl Index<(u32, u32)> for ImageBuffer where - P: Pixel, - Container: Deref, + P: ContiguousPixel, + Container: Deref, { type Output = P; @@ -1136,8 +1160,8 @@ where impl IndexMut<(u32, u32)> for ImageBuffer where - P: Pixel, - Container: Deref + DerefMut, + P: ContiguousPixel, + Container: Deref + DerefMut, { fn index_mut(&mut self, (x, y): (u32, u32)) -> &mut P { self.get_pixel_mut(x, y) @@ -1147,7 +1171,7 @@ where impl Clone for ImageBuffer where P: Pixel, - Container: Deref + Clone, + Container: Deref + Clone, { fn clone(&self) -> ImageBuffer { ImageBuffer { @@ -1167,8 +1191,8 @@ where impl GenericImageView for ImageBuffer where - P: Pixel, - Container: Deref + Deref, + P: ContiguousPixel, + Container: Deref + Deref, { type Pixel = P; @@ -1184,14 +1208,14 @@ where #[inline(always)] unsafe fn unsafe_get_pixel(&self, x: u32, y: u32) -> P { let indices = self.pixel_indices_unchecked(x, y); - *

::from_slice(self.data.get_unchecked(indices)) +

::from_components(self.data.get_unchecked(indices).iter().copied()) } } impl GenericImage for ImageBuffer where - P: Pixel, - Container: Deref + DerefMut, + P: ContiguousPixel + Blend, + Container: Deref + DerefMut, { fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut P { self.get_pixel_mut(x, y) @@ -1205,8 +1229,9 @@ where #[inline(always)] unsafe fn unsafe_put_pixel(&mut self, x: u32, y: u32, pixel: P) { let indices = self.pixel_indices_unchecked(x, y); - let p =

::from_slice_mut(self.data.get_unchecked_mut(indices)); - *p = pixel + let pixel_data = self.data.get_unchecked_mut(indices); + let pixel_mut = P::from_component_slice_mut(pixel_data); + *pixel_mut = pixel; } /// Put a pixel at location (x, y), taking into account alpha channels @@ -1260,15 +1285,18 @@ where // there is no such function as `into_vec`, whereas `into_raw` did work, and // `into_vec` is redundant anyway, because `into_raw` will give you the vector, // and it is more generic. -impl ImageBuffer> { - /// Creates a new image buffer based on a `Vec`. +impl

ImageBuffer> +where + P: ContiguousPixel, +{ + /// Creates a new image buffer based on a `Vec`. /// /// all the pixels of this image have a value of zero, regardless of the data type or number of channels. /// /// # Panics /// /// Panics when the resulting image is larger than the maximum size of a vector. - pub fn new(width: u32, height: u32) -> ImageBuffer> { + pub fn new(width: u32, height: u32) -> ImageBuffer> { let size = Self::image_buffer_len(width, height) .expect("Buffer length in `ImageBuffer::new` overflows usize"); ImageBuffer { @@ -1284,7 +1312,7 @@ impl ImageBuffer> { /// # Panics /// /// Panics when the resulting image is larger the the maximum size of a vector. - pub fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuffer> { + pub fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuffer> { let mut buf = ImageBuffer::new(width, height); for p in buf.pixels_mut() { *p = pixel @@ -1299,7 +1327,7 @@ impl ImageBuffer> { /// # Panics /// /// Panics when the resulting image is larger the the maximum size of a vector. - pub fn from_fn(width: u32, height: u32, mut f: F) -> ImageBuffer> + pub fn from_fn(width: u32, height: u32, mut f: F) -> ImageBuffer> where F: FnMut(u32, u32) -> P, { @@ -1315,14 +1343,14 @@ impl ImageBuffer> { pub fn from_vec( width: u32, height: u32, - buf: Vec, - ) -> Option>> { + buf: Vec, + ) -> Option>> { ImageBuffer::from_raw(width, height, buf) } /// Consumes the image buffer and returns the underlying data /// as an owned buffer - pub fn into_vec(self) -> Vec { + pub fn into_vec(self) -> Vec { self.into_raw() } } @@ -1336,7 +1364,7 @@ pub trait ConvertBuffer { fn convert(&self) -> T; } -// concrete implementation Luma -> Rgba +// concrete implementation Gray -> Rgba impl GrayImage { /// Expands a color palette by re-using the existing buffer. /// Assumes 8 bit per pixel. Uses an optionally transparent index to @@ -1372,13 +1400,13 @@ impl GrayImage { } // TODO: Equality constraints are not yet supported in where clauses, when they -// are, the T parameter should be removed in favor of ToType::Subpixel, which -// will then be FromType::Subpixel. -impl - ConvertBuffer>> for ImageBuffer +// are, the T parameter should be removed in favor of ToType::Component, which +// will then be FromType::Component. +impl + ConvertBuffer>> for ImageBuffer where - Container: Deref, - ToType: FromColor, + Container: Deref, + ToType: FromPixelCommon, { /// # Examples /// Convert RGB image to gray image. @@ -1393,11 +1421,11 @@ where /// /// let gray_image: GrayImage = image.convert(); /// ``` - fn convert(&self) -> ImageBuffer> { - let mut buffer: ImageBuffer> = + fn convert(&self) -> ImageBuffer> { + let mut buffer: ImageBuffer> = ImageBuffer::new(self.width, self.height); for (to, from) in buffer.pixels_mut().zip(self.pixels()) { - to.from_color(from) + *to = ToType::from_pixel_common(*from) } buffer } @@ -1408,25 +1436,29 @@ pub type RgbImage = ImageBuffer, Vec>; /// Sendable Rgb + alpha channel image buffer pub type RgbaImage = ImageBuffer, Vec>; /// Sendable grayscale image buffer -pub type GrayImage = ImageBuffer, Vec>; +pub type GrayImage = ImageBuffer, Vec>; /// Sendable grayscale + alpha channel image buffer -pub type GrayAlphaImage = ImageBuffer, Vec>; +pub type GrayAlphaImage = ImageBuffer, Vec>; /// Sendable 16-bit Rgb image buffer pub(crate) type Rgb16Image = ImageBuffer, Vec>; /// Sendable 16-bit Rgb + alpha channel image buffer pub(crate) type Rgba16Image = ImageBuffer, Vec>; /// Sendable 16-bit grayscale image buffer -pub(crate) type Gray16Image = ImageBuffer, Vec>; +pub(crate) type Gray16Image = ImageBuffer, Vec>; /// Sendable 16-bit grayscale + alpha channel image buffer -pub(crate) type GrayAlpha16Image = ImageBuffer, Vec>; - +pub(crate) type GrayAlpha16Image = ImageBuffer, Vec>; /// An image buffer for 32-bit float RGB pixels, /// where the backing container is a flattened vector of floats. pub type Rgb32FImage = ImageBuffer, Vec>; - /// An image buffer for 32-bit float RGBA pixels, /// where the backing container is a flattened vector of floats. pub type Rgba32FImage = ImageBuffer, Vec>; +/// An image buffer for 32-bit float RGB pixels, +/// where the backing container is a flattened vector of floats. +pub type Gray32FImage = ImageBuffer, Vec>; +/// An image buffer for 32-bit float RGBA pixels, +/// where the backing container is a flattened vector of floats. +pub type GrayAlpha32FImage = ImageBuffer, Vec>; impl From for RgbImage { fn from(value: DynamicImage) -> Self { @@ -1488,14 +1520,17 @@ mod test { use crate::math::Rect; use crate::GenericImage as _; use crate::ImageFormat; - use crate::{Luma, LumaA, Pixel, Rgb, Rgba}; use num_traits::Zero; + use pixeli::GrayAlpha; + use pixeli::Rgb; + use pixeli::Rgba; + use pixeli::{Gray, Pixel}; #[test] /// Tests if image buffers from slices work fn slice_buffer() { let data = [0; 9]; - let buf: ImageBuffer, _> = ImageBuffer::from_raw(3, 3, &data[..]).unwrap(); + let buf: ImageBuffer, _> = ImageBuffer::from_raw(3, 3, &data[..]).unwrap(); assert_eq!(&*buf, &data[..]) } @@ -1503,20 +1538,20 @@ mod test { ($test_name:ident, $pxt:ty) => { #[test] fn $test_name() { - let buffer = ImageBuffer::<$pxt, Vec<<$pxt as Pixel>::Subpixel>>::new(2, 2); + let buffer = ImageBuffer::<$pxt, Vec<<$pxt as Pixel>::Component>>::new(2, 2); assert!(buffer .iter() - .all(|p| *p == <$pxt as Pixel>::Subpixel::zero())); + .all(|p| *p == <$pxt as Pixel>::Component::zero())); } }; } - new_buffer_zero_test!(luma_u8_zero_test, Luma); - new_buffer_zero_test!(luma_u16_zero_test, Luma); - new_buffer_zero_test!(luma_f32_zero_test, Luma); - new_buffer_zero_test!(luma_a_u8_zero_test, LumaA); - new_buffer_zero_test!(luma_a_u16_zero_test, LumaA); - new_buffer_zero_test!(luma_a_f32_zero_test, LumaA); + new_buffer_zero_test!(luma_u8_zero_test, Gray); + new_buffer_zero_test!(luma_u16_zero_test, Gray); + new_buffer_zero_test!(luma_f32_zero_test, Gray); + new_buffer_zero_test!(luma_a_u8_zero_test, GrayAlpha); + new_buffer_zero_test!(luma_a_u16_zero_test, GrayAlpha); + new_buffer_zero_test!(luma_a_f32_zero_test, GrayAlpha); new_buffer_zero_test!(rgb_u8_zero_test, Rgb); new_buffer_zero_test!(rgb_u16_zero_test, Rgb); new_buffer_zero_test!(rgb_f32_zero_test, Rgb); @@ -1531,15 +1566,15 @@ mod test { let b = a.get_mut(3 * 10).unwrap(); *b = 255; } - assert_eq!(a.get_pixel(0, 1)[0], 255) + assert_eq!(a.get_pixel(0, 1).r, 255) } #[test] fn get_pixel_checked() { let mut a: RgbImage = ImageBuffer::new(10, 10); - a.get_pixel_mut_checked(0, 1).unwrap()[0] = 255; + a.get_pixel_mut_checked(0, 1).unwrap().r = 255; - assert_eq!(a.get_pixel_checked(0, 1), Some(&Rgb([255, 0, 0]))); + assert_eq!(a.get_pixel_checked(0, 1), Some(&Rgb { r: 255, g: 0, b: 0 })); assert_eq!(a.get_pixel_checked(0, 1).unwrap(), a.get_pixel(0, 1)); assert_eq!(a.get_pixel_checked(10, 0), None); assert_eq!(a.get_pixel_checked(0, 10), None); @@ -1547,7 +1582,11 @@ mod test { assert_eq!(a.get_pixel_mut_checked(0, 10), None); // From image/issues/1672 - const WHITE: Rgb = Rgb([255_u8, 255, 255]); + const WHITE: Rgb = Rgb { + r: 255_u8, + g: 255, + b: 255, + }; let mut a = RgbImage::new(2, 1); a.put_pixel(1, 0, WHITE); @@ -1560,7 +1599,7 @@ mod test { let mut a: RgbImage = ImageBuffer::new(10, 10); { let val = a.pixels_mut().next().unwrap(); - *val = Rgb([42, 0, 0]); + *val = Rgb { r: 42, g: 0, b: 0 }; } assert_eq!(a.data[0], 42) } @@ -1756,16 +1795,15 @@ mod test { #[cfg(test)] #[cfg(feature = "benchmarks")] mod benchmarks { - use super::{ConvertBuffer, GrayImage, ImageBuffer, Pixel, RgbImage}; + use super::{ConvertBuffer, GrayImage, ImageBuffer, RgbImage}; #[bench] fn conversion(b: &mut test::Bencher) { let mut a: RgbImage = ImageBuffer::new(1000, 1000); for p in a.pixels_mut() { - let rgb = p.channels_mut(); - rgb[0] = 255; - rgb[1] = 23; - rgb[2] = 42; + p.r = 255; + p.g = 23; + p.b = 42; } assert!(a.data[0] != 0); b.iter(|| { @@ -1781,10 +1819,9 @@ mod benchmarks { fn image_access_row_by_row(b: &mut test::Bencher) { let mut a: RgbImage = ImageBuffer::new(1000, 1000); for p in a.pixels_mut() { - let rgb = p.channels_mut(); - rgb[0] = 255; - rgb[1] = 23; - rgb[2] = 42; + p.r = 255; + p.g = 23; + p.b = 42; } b.iter(move || { @@ -1793,9 +1830,9 @@ mod benchmarks { for y in 0..1000 { for x in 0..1000 { let pixel = image.get_pixel(x, y); - sum = sum.wrapping_add(pixel[0] as usize); - sum = sum.wrapping_add(pixel[1] as usize); - sum = sum.wrapping_add(pixel[2] as usize); + sum = sum.wrapping_add(pixel.r as usize); + sum = sum.wrapping_add(pixel.g as usize); + sum = sum.wrapping_add(pixel.b as usize); } } test::black_box(sum) @@ -1808,10 +1845,9 @@ mod benchmarks { fn image_access_col_by_col(b: &mut test::Bencher) { let mut a: RgbImage = ImageBuffer::new(1000, 1000); for p in a.pixels_mut() { - let rgb = p.channels_mut(); - rgb[0] = 255; - rgb[1] = 23; - rgb[2] = 42; + p.r = 255; + p.g = 23; + p.b = 42; } b.iter(move || { @@ -1820,9 +1856,9 @@ mod benchmarks { for x in 0..1000 { for y in 0..1000 { let pixel = image.get_pixel(x, y); - sum = sum.wrapping_add(pixel[0] as usize); - sum = sum.wrapping_add(pixel[1] as usize); - sum = sum.wrapping_add(pixel[2] as usize); + sum = sum.wrapping_add(pixel.r as usize); + sum = sum.wrapping_add(pixel.g as usize); + sum = sum.wrapping_add(pixel.b as usize); } } test::black_box(sum) diff --git a/src/buffer_par.rs b/src/buffer_par.rs index aa90a86664..5cd5543cc3 100644 --- a/src/buffer_par.rs +++ b/src/buffer_par.rs @@ -1,10 +1,10 @@ +use pixeli::{ContiguousPixel, Pixel}; use rayon::iter::plumbing::*; use rayon::iter::{IndexedParallelIterator, ParallelIterator}; use rayon::slice::{ChunksExact, ChunksExactMut, ParallelSlice, ParallelSliceMut}; use std::fmt; use std::ops::{Deref, DerefMut}; -use crate::traits::Pixel; use crate::ImageBuffer; /// Parallel iterator over pixel refs. @@ -12,15 +12,15 @@ use crate::ImageBuffer; pub struct PixelsPar<'a, P> where P: Pixel + Sync + 'a, - P::Subpixel: Sync + 'a, + P::Component: Sync + 'a, { - chunks: ChunksExact<'a, P::Subpixel>, + chunks: ChunksExact<'a, P::Component>, } impl<'a, P> ParallelIterator for PixelsPar<'a, P> where - P: Pixel + Sync + 'a, - P::Subpixel: Sync + 'a, + P: ContiguousPixel + Sync + 'a, + P::Component: Sync + 'a, { type Item = &'a P; @@ -29,7 +29,7 @@ where C: UnindexedConsumer, { self.chunks - .map(|v|

::from_slice(v)) + .map(|v|

::from_component_slice_ref(v)) .drive_unindexed(consumer) } @@ -40,12 +40,12 @@ where impl<'a, P> IndexedParallelIterator for PixelsPar<'a, P> where - P: Pixel + Sync + 'a, - P::Subpixel: Sync + 'a, + P: ContiguousPixel + Sync + 'a, + P::Component: Sync + 'a, { fn drive>(self, consumer: C) -> C::Result { self.chunks - .map(|v|

::from_slice(v)) + .map(|v|

::from_component_slice_ref(v)) .drive(consumer) } @@ -55,7 +55,7 @@ where fn with_producer>(self, callback: CB) -> CB::Output { self.chunks - .map(|v|

::from_slice(v)) + .map(|v|

::from_component_slice_ref(v)) .with_producer(callback) } } @@ -63,7 +63,7 @@ where impl

fmt::Debug for PixelsPar<'_, P> where P: Pixel + Sync, - P::Subpixel: Sync + fmt::Debug, + P::Component: Sync + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("PixelsPar") @@ -76,15 +76,15 @@ where pub struct PixelsMutPar<'a, P> where P: Pixel + Send + Sync + 'a, - P::Subpixel: Send + Sync + 'a, + P::Component: Send + Sync + 'a, { - chunks: ChunksExactMut<'a, P::Subpixel>, + chunks: ChunksExactMut<'a, P::Component>, } impl<'a, P> ParallelIterator for PixelsMutPar<'a, P> where - P: Pixel + Send + Sync + 'a, - P::Subpixel: Send + Sync + 'a, + P: ContiguousPixel + Send + Sync + 'a, + P::Component: Send + Sync + 'a, { type Item = &'a mut P; @@ -93,7 +93,7 @@ where C: UnindexedConsumer, { self.chunks - .map(|v|

::from_slice_mut(v)) + .map(|v|

::from_component_slice_mut(v)) .drive_unindexed(consumer) } @@ -104,12 +104,12 @@ where impl<'a, P> IndexedParallelIterator for PixelsMutPar<'a, P> where - P: Pixel + Send + Sync + 'a, - P::Subpixel: Send + Sync + 'a, + P: ContiguousPixel + Send + Sync + 'a, + P::Component: Send + Sync + 'a, { fn drive>(self, consumer: C) -> C::Result { self.chunks - .map(|v|

::from_slice_mut(v)) + .map(|v|

::from_component_slice_mut(v)) .drive(consumer) } @@ -119,7 +119,7 @@ where fn with_producer>(self, callback: CB) -> CB::Output { self.chunks - .map(|v|

::from_slice_mut(v)) + .map(|v|

::from_component_slice_mut(v)) .with_producer(callback) } } @@ -127,7 +127,7 @@ where impl

fmt::Debug for PixelsMutPar<'_, P> where P: Pixel + Send + Sync, - P::Subpixel: Send + Sync + fmt::Debug, + P::Component: Send + Sync + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("PixelsMutPar") @@ -141,7 +141,7 @@ where pub struct EnumeratePixelsPar<'a, P> where P: Pixel + Sync + 'a, - P::Subpixel: Sync + 'a, + P::Component: Sync + 'a, { pixels: PixelsPar<'a, P>, width: u32, @@ -149,8 +149,8 @@ where impl<'a, P> ParallelIterator for EnumeratePixelsPar<'a, P> where - P: Pixel + Sync + 'a, - P::Subpixel: Sync + 'a, + P: ContiguousPixel + Sync + 'a, + P::Component: Sync + 'a, { type Item = (u32, u32, &'a P); @@ -177,8 +177,8 @@ where impl<'a, P> IndexedParallelIterator for EnumeratePixelsPar<'a, P> where - P: Pixel + Sync + 'a, - P::Subpixel: Sync + 'a, + P: ContiguousPixel + Sync + 'a, + P::Component: Sync + 'a, { fn drive>(self, consumer: C) -> C::Result { self.pixels @@ -214,7 +214,7 @@ where impl

fmt::Debug for EnumeratePixelsPar<'_, P> where P: Pixel + Sync, - P::Subpixel: Sync + fmt::Debug, + P::Component: Sync + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("EnumeratePixelsPar") @@ -228,7 +228,7 @@ where pub struct EnumeratePixelsMutPar<'a, P> where P: Pixel + Send + Sync + 'a, - P::Subpixel: Send + Sync + 'a, + P::Component: Send + Sync + 'a, { pixels: PixelsMutPar<'a, P>, width: u32, @@ -236,8 +236,8 @@ where impl<'a, P> ParallelIterator for EnumeratePixelsMutPar<'a, P> where - P: Pixel + Send + Sync + 'a, - P::Subpixel: Send + Sync + 'a, + P: ContiguousPixel + Send + Sync + 'a, + P::Component: Send + Sync + 'a, { type Item = (u32, u32, &'a mut P); @@ -264,8 +264,8 @@ where impl<'a, P> IndexedParallelIterator for EnumeratePixelsMutPar<'a, P> where - P: Pixel + Send + Sync + 'a, - P::Subpixel: Send + Sync + 'a, + P: ContiguousPixel + Send + Sync + 'a, + P::Component: Send + Sync + 'a, { fn drive>(self, consumer: C) -> C::Result { self.pixels @@ -301,7 +301,7 @@ where impl

fmt::Debug for EnumeratePixelsMutPar<'_, P> where P: Pixel + Send + Sync, - P::Subpixel: Send + Sync + fmt::Debug, + P::Component: Send + Sync + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("EnumeratePixelsMutPar") @@ -313,9 +313,9 @@ where impl ImageBuffer where - P: Pixel + Sync, - P::Subpixel: Sync, - Container: Deref, + P: ContiguousPixel + Sync, + P::Component: Sync, + Container: Deref, { /// Returns a parallel iterator over the pixels of this image, usable with `rayon`. /// See [`pixels`] for more information. @@ -325,7 +325,7 @@ where PixelsPar { chunks: self .inner_pixels() - .par_chunks_exact(

::CHANNEL_COUNT as usize), + .par_chunks_exact(

::COMPONENT_COUNT as usize), } } @@ -343,9 +343,9 @@ where impl ImageBuffer where - P: Pixel + Send + Sync, - P::Subpixel: Send + Sync, - Container: Deref + DerefMut, + P: ContiguousPixel + Send + Sync, + P::Component: Send + Sync, + Container: Deref + DerefMut, { /// Returns a parallel iterator over the mutable pixels of this image, usable with `rayon`. /// See [`pixels_mut`] for more information. @@ -355,7 +355,7 @@ where PixelsMutPar { chunks: self .inner_pixels_mut() - .par_chunks_exact_mut(

::CHANNEL_COUNT as usize), + .par_chunks_exact_mut(

::COMPONENT_COUNT as usize), } } @@ -372,10 +372,10 @@ where } } -impl

ImageBuffer> +impl

ImageBuffer> where - P: Pixel + Send + Sync, - P::Subpixel: Send + Sync, + P: ContiguousPixel + Send + Sync, + P::Component: Send + Sync, { /// Constructs a new ImageBuffer by repeated application of the supplied function, /// utilizing multi-threading via `rayon`. @@ -385,7 +385,7 @@ where /// # Panics /// /// Panics when the resulting image is larger the the maximum size of a vector. - pub fn from_par_fn(width: u32, height: u32, f: F) -> ImageBuffer> + pub fn from_par_fn(width: u32, height: u32, f: F) -> ImageBuffer> where F: Fn(u32, u32) -> P + Send + Sync, { @@ -400,9 +400,11 @@ where #[cfg(test)] mod test { - use crate::{Rgb, RgbImage}; + use pixeli::Rgb; use rayon::iter::{IndexedParallelIterator, ParallelIterator}; + use crate::RgbImage; + fn test_width_height(width: u32, height: u32, len: usize) { let mut image = RgbImage::new(width, height); @@ -430,7 +432,7 @@ mod test { #[test] fn iter_parity() { let mut image1 = RgbImage::from_fn(17, 29, |x, y| { - Rgb(std::array::from_fn(|i| { + Rgb::from(std::array::from_fn::<_, 3, _>(|i| { ((x + y * 98 + i as u32 * 27) % 255) as u8 })) }); @@ -458,7 +460,8 @@ mod test { #[cfg(test)] #[cfg(feature = "benchmarks")] mod benchmarks { - use crate::{Rgb, RgbImage}; + use crate::RgbImage; + use pixeli::{Pixel, Rgb}; const S: u32 = 1024; @@ -489,7 +492,7 @@ mod benchmarks { fn pixel_func() -> Rgb { use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hasher}; - Rgb(std::array::from_fn(|_| { + Rgb::from_components(std::array::from_fn::<_, 3, _>(|_| { RandomState::new().build_hasher().finish() as u8 })) } diff --git a/src/codecs/avif/encoder.rs b/src/codecs/avif/encoder.rs index 58cbe4c506..59f0cb7d1e 100644 --- a/src/codecs/avif/encoder.rs +++ b/src/codecs/avif/encoder.rs @@ -8,15 +8,15 @@ use std::cmp::min; use std::io::Write; use crate::buffer::ConvertBuffer; -use crate::color::{FromColor, Luma, LumaA, Rgb, Rgba}; use crate::error::{ EncodingError, ParameterError, ParameterErrorKind, UnsupportedError, UnsupportedErrorKind, }; -use crate::{ExtendedColorType, ImageBuffer, ImageEncoder, ImageFormat, Pixel}; +use crate::{ExtendedColorType, ImageBuffer, ImageEncoder, ImageFormat}; use crate::{ImageError, ImageResult}; use bytemuck::{try_cast_slice, try_cast_slice_mut, Pod, PodCastError}; use num_traits::Zero; +use pixeli::{ContiguousPixel, FromPixelCommon, Gray, GrayAlpha, Rgb, Rgba}; use ravif::{Encoder, Img, RGB8, RGBA8}; use rgb::AsPixels; @@ -145,11 +145,11 @@ impl AvifEncoder { color: ExtendedColorType, ) -> ImageResult> { // Error wrapping utility for color dependent buffer dimensions. - fn try_from_raw( - data: &[P::Subpixel], + fn try_from_raw( + data: &[P::Component], width: u32, height: u32, - ) -> ImageResult> { + ) -> ImageResult> { ImageBuffer::from_raw(width, height, data).ok_or_else(|| { ImageError::Parameter(ParameterError::from_kind( ParameterErrorKind::DimensionMismatch, @@ -160,11 +160,11 @@ impl AvifEncoder { // Convert to target color type using few buffer allocations. fn convert_into<'buf, P>( buf: &'buf mut Vec, - image: ImageBuffer, + image: ImageBuffer, ) -> Img<&'buf [RGBA8]> where - P: Pixel + 'static, - Rgba: FromColor

, + P: ContiguousPixel + 'static, + Rgba: FromPixelCommon

, { let (width, height) = image.dimensions(); // TODO: conversion re-using the target buffer? @@ -245,22 +245,22 @@ impl AvifEncoder { } // we need a separate buffer.. ExtendedColorType::L8 => { - let image = try_from_raw::>(data, width, height)?; + let image = try_from_raw::>(data, width, height)?; Ok(RgbColor::Rgba8(convert_into(fallback, image))) } ExtendedColorType::La8 => { - let image = try_from_raw::>(data, width, height)?; + let image = try_from_raw::>(data, width, height)?; Ok(RgbColor::Rgba8(convert_into(fallback, image))) } // we need to really convert data.. ExtendedColorType::L16 => { let buffer = cast_buffer(data)?; - let image = try_from_raw::>(&buffer, width, height)?; + let image = try_from_raw::>(&buffer, width, height)?; Ok(RgbColor::Rgba8(convert_into(fallback, image))) } ExtendedColorType::La16 => { let buffer = cast_buffer(data)?; - let image = try_from_raw::>(&buffer, width, height)?; + let image = try_from_raw::>(&buffer, width, height)?; Ok(RgbColor::Rgba8(convert_into(fallback, image))) } ExtendedColorType::Rgb16 => { diff --git a/src/codecs/bmp/encoder.rs b/src/codecs/bmp/encoder.rs index 794998c3b3..68b8bd294a 100644 --- a/src/codecs/bmp/encoder.rs +++ b/src/codecs/bmp/encoder.rs @@ -39,7 +39,7 @@ impl<'a, W: Write + 'a> BmpEncoder<'a, W> { } /// Same as `encode`, but allow a palette to be passed in. The `palette` is ignored for color - /// types other than Luma/Luma-with-alpha. + /// types other than Gray/Gray-with-alpha. /// /// # Panics /// diff --git a/src/codecs/gif.rs b/src/codecs/gif.rs index 55e51ff389..afe362625f 100644 --- a/src/codecs/gif.rs +++ b/src/codecs/gif.rs @@ -33,9 +33,10 @@ use std::mem; use gif::ColorOutput; use gif::{DisposalMethod, Frame}; +use pixeli::Rgba; use crate::animation::{self, Ratio}; -use crate::color::{ColorType, Rgba}; +use crate::color::ColorType; use crate::error::LimitError; use crate::error::LimitErrorKind; use crate::error::{ @@ -43,7 +44,6 @@ use crate::error::{ UnsupportedError, UnsupportedErrorKind, }; use crate::image::{AnimationDecoder, ImageDecoder, ImageFormat}; -use crate::traits::Pixel; use crate::ExtendedColorType; use crate::ImageBuffer; use crate::Limits; @@ -204,7 +204,12 @@ impl ImageDecoder for GifDecoder { *pixel = *frame_buffer.get_pixel(frame_x, frame_y); } else { // this is only necessary in case the buffer is not zeroed - *pixel = Rgba([0, 0, 0, 0]); + *pixel = Rgba { + r: 0, + g: 0, + b: 0, + a: 0, + }; } } } @@ -264,7 +269,12 @@ impl Iterator for GifFrameIterator { self.non_disposed_frame = Some(ImageBuffer::from_pixel( self.width, self.height, - Rgba([0, 0, 0, 0]), + Rgba { + r: 0, + g: 0, + b: 0, + a: 0, + }, )); } // Bind to a variable to avoid repeated `.unwrap()` calls @@ -327,8 +337,7 @@ impl Iterator for GifFrameIterator { previous: &mut Rgba, current: &mut Rgba, ) { - let pixel_alpha = current.channels()[3]; - if pixel_alpha == 0 { + if current.a == 0 { *current = *previous; } @@ -343,7 +352,12 @@ impl Iterator for GifFrameIterator { DisposalMethod::Background => { // restore to background color // (background shows through transparent pixels in the next frame) - *previous = Rgba([0, 0, 0, 0]); + *previous = Rgba { + r: 0, + g: 0, + b: 0, + a: 0, + }; } DisposalMethod::Previous => { // restore to previous diff --git a/src/codecs/hdr/decoder.rs b/src/codecs/hdr/decoder.rs index c704f1ab8d..82886aceb7 100644 --- a/src/codecs/hdr/decoder.rs +++ b/src/codecs/hdr/decoder.rs @@ -3,7 +3,9 @@ use std::io::{self, Read}; use std::num::{ParseFloatError, ParseIntError}; use std::{error, fmt}; -use crate::color::{ColorType, Rgb}; +use pixeli::{Pixel, Rgb}; + +use crate::color::ColorType; use crate::error::{ DecodingError, ImageError, ImageFormatHint, ImageResult, UnsupportedError, UnsupportedErrorKind, }; @@ -148,15 +150,19 @@ impl Rgbe8Pixel { #[inline] pub(crate) fn to_hdr(self) -> Rgb { if self.e == 0 { - Rgb([0.0, 0.0, 0.0]) + Rgb { + r: 0.0, + g: 0.0, + b: 0.0, + } } else { // let exp = f32::ldexp(1., self.e as isize - (128 + 8)); // unstable let exp = f32::exp2(>::from(self.e) - (128.0 + 8.0)); - Rgb([ - exp * >::from(self.c[0]), - exp * >::from(self.c[1]), - exp * >::from(self.c[2]), - ]) + Rgb { + r: exp * >::from(self.c[0]), + g: exp * >::from(self.c[1]), + b: exp * >::from(self.c[2]), + } } } } @@ -309,11 +315,19 @@ impl ImageDecoder for HdrDecoder { fn read_image(self, buf: &mut [u8]) -> ImageResult<()> { assert_eq!(u64::try_from(buf.len()), Ok(self.total_bytes())); - let mut img = vec![Rgb([0.0, 0.0, 0.0]); self.width as usize * self.height as usize]; + let mut img = vec![ + Rgb { + r: 0.0, + g: 0.0, + b: 0.0 + }; + self.width as usize * self.height as usize + ]; self.read_image_transform(|pix| pix.to_hdr(), &mut img[..])?; - for (i, Rgb(data)) in img.into_iter().enumerate() { - buf[(i * 12)..][..12].copy_from_slice(bytemuck::cast_slice(&data)); + for (i, rgb) in img.into_iter().enumerate() { + buf[(i * 12)..][..12] + .copy_from_slice(bytemuck::cast_slice(rgb.component_array().as_slice())); } Ok(()) diff --git a/src/codecs/hdr/encoder.rs b/src/codecs/hdr/encoder.rs index 5686004c8f..4058c26859 100644 --- a/src/codecs/hdr/encoder.rs +++ b/src/codecs/hdr/encoder.rs @@ -1,5 +1,6 @@ +use pixeli::{Pixel, Rgb}; + use crate::codecs::hdr::{rgbe8, Rgbe8Pixel, SIGNATURE}; -use crate::color::Rgb; use crate::error::{EncodingError, ImageFormatHint, ImageResult}; use crate::{ExtendedColorType, ImageEncoder, ImageError, ImageFormat}; use std::cmp::Ordering; @@ -21,9 +22,11 @@ impl ImageEncoder for HdrEncoder { match color_type { ExtendedColorType::Rgb32F => { let bytes_per_pixel = color_type.bits_per_pixel() as usize / 8; - let rgbe_pixels = unaligned_bytes - .chunks_exact(bytes_per_pixel) - .map(|bytes| to_rgbe8(Rgb::(bytemuck::pod_read_unaligned(bytes)))); + let rgbe_pixels = unaligned_bytes.chunks_exact(bytes_per_pixel).map(|bytes| { + to_rgbe8(Rgb::::from_components(bytemuck::pod_read_unaligned::< + [f32; 3], + >(bytes))) + }); // the length will be checked inside encode_pixels self.encode_pixels(rgbe_pixels, width as usize, height as usize) @@ -275,8 +278,7 @@ fn write_rgbe8(w: &mut W, v: Rgbe8Pixel) -> Result<()> { /// Converts ```Rgb``` into ```Rgbe8Pixel``` pub(crate) fn to_rgbe8(pix: Rgb) -> Rgbe8Pixel { - let pix = pix.0; - let mx = f32::max(pix[0], f32::max(pix[1], pix[2])); + let mx = f32::max(pix.r, f32::max(pix.g, pix.b)); if mx <= 0.0 { Rgbe8Pixel { c: [0, 0, 0], e: 0 } } else { @@ -284,7 +286,7 @@ pub(crate) fn to_rgbe8(pix: Rgb) -> Rgbe8Pixel { let exp = mx.log2().floor() as i32 + 1; let mul = f32::powi(2.0, exp); let mut conv = [0u8; 3]; - for (cv, &sv) in conv.iter_mut().zip(pix.iter()) { + for (cv, sv) in conv.iter_mut().zip(pix.component_array()) { *cv = f32::trunc(sv / mul * 256.0) as u8; } Rgbe8Pixel { @@ -323,14 +325,16 @@ fn to_rgbe8_test() { } fn relative_dist(a: Rgb, b: Rgb) -> f32 { // maximal difference divided by maximal value - let max_diff = - a.0.iter() - .zip(b.0.iter()) - .fold(0.0, |diff, (&a, &b)| f32::max(diff, (a - b).abs())); - let max_val = - a.0.iter() - .chain(b.0.iter()) - .fold(0.0, |maxv, &a| f32::max(maxv, a)); + let max_diff = a + .component_array() + .into_iter() + .zip(b.component_array()) + .fold(0.0, |diff, (a, b)| f32::max(diff, (a - b).abs())); + let max_val = a + .component_array() + .into_iter() + .chain(b.component_array()) + .fold(0.0, f32::max); if max_val == 0.0 { 0.0 } else { @@ -344,7 +348,7 @@ fn to_rgbe8_test() { for &r in &test_values { for &g in &test_values { for &b in &test_values { - let c1 = Rgb([r, g, b]); + let c1 = Rgb { r, g, b }; let c2 = to_rgbe8(c1).to_hdr(); let rel_dist = relative_dist(c1, c2); // Maximal value is normalized to the range 128..256, thus we have 1/128 precision diff --git a/src/codecs/jpeg/decoder.rs b/src/codecs/jpeg/decoder.rs index 3584a6768f..ec311135ee 100644 --- a/src/codecs/jpeg/decoder.rs +++ b/src/codecs/jpeg/decoder.rs @@ -105,14 +105,13 @@ impl ImageDecoder for JpegDecoder { impl ColorType { fn from_jpeg(colorspace: ZuneColorSpace) -> ColorType { let colorspace = to_supported_color_space(colorspace); - use zune_core::colorspace::ColorSpace::*; match colorspace { // As of zune-jpeg 0.3.13 the output is always 8-bit, // but support for 16-bit JPEG might be added in the future. - RGB => ColorType::Rgb8, - RGBA => ColorType::Rgba8, - Luma => ColorType::L8, - LumaA => ColorType::La8, + ZuneColorSpace::RGB => ColorType::Rgb8, + ZuneColorSpace::RGBA => ColorType::Rgba8, + ZuneColorSpace::Luma => ColorType::L8, + ZuneColorSpace::LumaA => ColorType::La8, // to_supported_color_space() doesn't return any of the other variants _ => unreachable!(), } @@ -120,11 +119,13 @@ impl ColorType { } fn to_supported_color_space(orig: ZuneColorSpace) -> ZuneColorSpace { - use zune_core::colorspace::ColorSpace::*; match orig { - RGB | RGBA | Luma | LumaA => orig, + ZuneColorSpace::RGB + | ZuneColorSpace::RGBA + | ZuneColorSpace::Luma + | ZuneColorSpace::LumaA => orig, // the rest is not supported by `image` so it will be converted to RGB during decoding - _ => RGB, + _ => ZuneColorSpace::RGB, } } diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 27958c7dee..528ac7d16f 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -3,13 +3,15 @@ use std::borrow::Cow; use std::io::{self, Write}; +use pixeli::{FromComponentCommon, FromPixelCommon, Gray, Pixel, PixelComponent, Rgb}; + use crate::error::{ ImageError, ImageResult, ParameterError, ParameterErrorKind, UnsupportedError, UnsupportedErrorKind, }; use crate::image::{ImageEncoder, ImageFormat}; use crate::utils::clamp; -use crate::{ExtendedColorType, GenericImageView, ImageBuffer, Luma, Pixel, Rgb}; +use crate::{ExtendedColorType, GenericImageView, ImageBuffer}; use super::entropy::build_huff_lut_const; use super::transform; @@ -453,7 +455,7 @@ impl JpegEncoder { match color_type { ExtendedColorType::L8 => { - let image: ImageBuffer, _> = + let image: ImageBuffer, _> = ImageBuffer::from_raw(width, height, image).unwrap(); self.encode_image(&image) } @@ -483,8 +485,11 @@ impl JpegEncoder { pub fn encode_image(&mut self, image: &I) -> ImageResult<()> where I::Pixel: PixelWithColorType, + Gray: FromPixelCommon, + Rgb: FromPixelCommon, + f32: FromComponentCommon<::Component>, { - let n = I::Pixel::CHANNEL_COUNT; + let n = I::Pixel::COMPONENT_COUNT; let color_type = I::Pixel::COLOR_TYPE; let num_components = if n == 1 || n == 2 { 1 } else { 3 }; @@ -574,7 +579,10 @@ impl JpegEncoder { Ok(()) } - fn encode_gray(&mut self, image: &I) -> io::Result<()> { + fn encode_gray(&mut self, image: &I) -> io::Result<()> + where + Gray: FromPixelCommon, + { let mut yblock = [0u8; 64]; let mut y_dcprev = 0; let mut dct_yblock = [0i32; 64]; @@ -602,7 +610,11 @@ impl JpegEncoder { Ok(()) } - fn encode_rgb(&mut self, image: &I) -> io::Result<()> { + fn encode_rgb(&mut self, image: &I) -> io::Result<()> + where + f32: FromComponentCommon<::Component>, + Rgb: FromPixelCommon, + { let mut y_dcprev = 0; let mut cb_dcprev = 0; let mut cr_dcprev = 0; @@ -771,20 +783,19 @@ fn encode_coefficient(coefficient: i32) -> (u8, u16) { } #[inline] -fn rgb_to_ycbcr(pixel: P) -> (u8, u8, u8) { - use crate::traits::Primitive; - use num_traits::cast::ToPrimitive; - - let [r, g, b] = pixel.to_rgb().0; - let max: f32 = P::Subpixel::DEFAULT_MAX_VALUE.to_f32().unwrap(); - let r: f32 = r.to_f32().unwrap(); - let g: f32 = g.to_f32().unwrap(); - let b: f32 = b.to_f32().unwrap(); +fn rgb_to_ycbcr

(pixel: P) -> (u8, u8, u8) +where + P: Pixel, + Rgb: FromPixelCommon

, + f32: FromComponentCommon, +{ + let p = Rgb::from_pixel_common(pixel); + let max: f32 = f32::from_component_common(::COMPONENT_MAX); // Coefficients from JPEG File Interchange Format (Version 1.02), multiplied for 255 maximum. - let y = 76.245 / max * r + 149.685 / max * g + 29.07 / max * b; - let cb = -43.0185 / max * r - 84.4815 / max * g + 127.5 / max * b + 128.; - let cr = 127.5 / max * r - 106.7685 / max * g - 20.7315 / max * b + 128.; + let y = 76.245 / max * p.r + 149.685 / max * p.g + 29.07 / max * p.b; + let cb = -43.0185 / max * p.r - 84.4815 / max * p.g + 127.5 / max * p.b + 128.; + let cr = 127.5 / max * p.r - 106.7685 / max * p.g - 20.7315 / max * p.b + 128.; (y as u8, cb as u8, cr as u8) } @@ -807,7 +818,10 @@ fn copy_blocks_ycbcr( yb: &mut [u8; 64], cbb: &mut [u8; 64], crb: &mut [u8; 64], -) { +) where + f32: FromComponentCommon<::Component>, + Rgb: FromPixelCommon, +{ for y in 0..8 { for x in 0..8 { let pixel = pixel_at_or_near(source, x + x0, y + y0); @@ -820,13 +834,14 @@ fn copy_blocks_ycbcr( } } -fn copy_blocks_gray(source: &I, x0: u32, y0: u32, gb: &mut [u8; 64]) { - use num_traits::cast::ToPrimitive; +fn copy_blocks_gray(source: &I, x0: u32, y0: u32, gb: &mut [u8; 64]) +where + Gray: FromPixelCommon, +{ for y in 0..8 { for x in 0..8 { let pixel = pixel_at_or_near(source, x0 + x, y0 + y); - let [luma] = pixel.to_luma().0; - gb[(y * 8 + x) as usize] = luma.to_u8().unwrap(); + gb[(y * 8 + x) as usize] = Gray::::from_pixel_common(pixel).gray; } } } diff --git a/src/codecs/openexr.rs b/src/codecs/openexr.rs index 4ddffe3a41..efb775ca01 100644 --- a/src/codecs/openexr.rs +++ b/src/codecs/openexr.rs @@ -334,6 +334,8 @@ fn to_image_err(exr_error: Error) -> ImageError { #[cfg(test)] mod test { + use pixeli::{Pixel, Rgb, Rgba}; + use super::*; use std::fs::File; @@ -342,7 +344,7 @@ mod test { use crate::buffer_::{Rgb32FImage, Rgba32FImage}; use crate::error::{LimitError, LimitErrorKind}; - use crate::{DynamicImage, ImageBuffer, Rgb, Rgba}; + use crate::{DynamicImage, ImageBuffer}; const BASE_PATH: &[&str] = &[".", "tests", "images", "exr"]; @@ -437,7 +439,11 @@ mod test { assert_eq!(exr_pixels.dimensions(), hdr.dimensions()); for (expected, found) in hdr.pixels().zip(exr_pixels.pixels()) { - for (expected, found) in expected.0.iter().zip(found.0.iter()) { + for (expected, found) in expected + .component_array() + .into_iter() + .zip(found.component_array()) + { // the large tolerance seems to be caused by // the RGBE u8x4 pixel quantization of the hdr image format assert!( @@ -458,8 +464,11 @@ mod test { .cycle(); let mut next_random = move || next_random.next().unwrap(); - let generated_image: Rgba32FImage = ImageBuffer::from_fn(9, 31, |_x, _y| { - Rgba([next_random(), next_random(), next_random(), next_random()]) + let generated_image: Rgba32FImage = ImageBuffer::from_fn(9, 31, |_x, _y| Rgba { + r: next_random(), + g: next_random(), + b: next_random(), + a: next_random(), }); let mut bytes = vec![]; @@ -476,8 +485,10 @@ mod test { .cycle(); let mut next_random = move || next_random.next().unwrap(); - let generated_image: Rgb32FImage = ImageBuffer::from_fn(9, 31, |_x, _y| { - Rgb([next_random(), next_random(), next_random()]) + let generated_image: Rgb32FImage = ImageBuffer::from_fn(9, 31, |_x, _y| Rgb { + r: next_random(), + g: next_random(), + b: next_random(), }); let mut bytes = vec![]; @@ -499,8 +510,23 @@ mod test { assert_eq!(rgba.dimensions(), rgb.dimensions()); - for (Rgb(rgb), Rgba(rgba)) in rgb.pixels().zip(rgba.pixels()) { - assert_eq!(rgb, &rgba[..3]); + for ( + Rgb { + r: r1, + g: g1, + b: b1, + }, + Rgba { + r: r2, + g: g2, + b: b2, + .. + }, + ) in rgb.pixels().zip(rgba.pixels()) + { + assert_eq!(r1, r2); + assert_eq!(g1, g2); + assert_eq!(b1, b2); } } diff --git a/src/codecs/png.rs b/src/codecs/png.rs index 7ecfc96b56..209ca22dc0 100644 --- a/src/codecs/png.rs +++ b/src/codecs/png.rs @@ -9,6 +9,7 @@ use std::fmt; use std::io::{BufRead, Seek, Write}; +use pixeli::{Gray, GrayAlpha, Rgb, Rgba}; use png::{BlendOp, DisposeOp}; use crate::animation::{Delay, Frame, Frames, Ratio}; @@ -19,7 +20,7 @@ use crate::error::{ }; use crate::image::{AnimationDecoder, ImageDecoder, ImageEncoder, ImageFormat}; use crate::Limits; -use crate::{DynamicImage, GenericImage, ImageBuffer, Luma, LumaA, Rgb, Rgba, RgbaImage}; +use crate::{DynamicImage, GenericImage, ImageBuffer, RgbaImage}; // http://www.w3.org/TR/PNG-Structure.html // The first eight bytes of a PNG file always contain the following (decimal) values: @@ -316,9 +317,14 @@ impl ApngDecoder { } DisposeOp::Background => { previous.clone_from(current); - current - .pixels_mut() - .for_each(|pixel| *pixel = Rgba([0, 0, 0, 0])); + current.pixels_mut().for_each(|pixel| { + *pixel = Rgba { + r: 0, + g: 0, + b: 0, + a: 0, + } + }); } DisposeOp::Previous => { current.clone_from(previous); @@ -366,12 +372,13 @@ impl ApngDecoder { limits.reserve_buffer(width, height, COLOR_TYPE)?; let source = match self.inner.color_type { ColorType::L8 => { - let image = ImageBuffer::, _>::from_raw(width, height, buffer).unwrap(); - DynamicImage::ImageLuma8(image).into_rgba8() + let image = ImageBuffer::, _>::from_raw(width, height, buffer).unwrap(); + DynamicImage::ImageGray8(image).into_rgba8() } ColorType::La8 => { - let image = ImageBuffer::, _>::from_raw(width, height, buffer).unwrap(); - DynamicImage::ImageLumaA8(image).into_rgba8() + let image = + ImageBuffer::, _>::from_raw(width, height, buffer).unwrap(); + DynamicImage::ImageGrayAlpha8(image).into_rgba8() } ColorType::Rgb8 => { let image = ImageBuffer::, _>::from_raw(width, height, buffer).unwrap(); diff --git a/src/codecs/webp/decoder.rs b/src/codecs/webp/decoder.rs index dd148a820b..156931d171 100644 --- a/src/codecs/webp/decoder.rs +++ b/src/codecs/webp/decoder.rs @@ -1,9 +1,11 @@ use std::io::{BufRead, Read, Seek}; +use pixeli::Rgba; + use crate::buffer::ConvertBuffer; use crate::error::{DecodingError, ImageError, ImageResult}; use crate::image::{ImageDecoder, ImageFormat}; -use crate::{AnimationDecoder, ColorType, Delay, Frame, Frames, RgbImage, Rgba, RgbaImage}; +use crate::{AnimationDecoder, ColorType, Delay, Frame, Frames, RgbImage, RgbaImage}; /// WebP Image format decoder. Currently only supports lossy RGB images or lossless RGBA images. pub struct WebPDecoder { @@ -27,7 +29,7 @@ impl WebPDecoder { /// Sets the background color if the image is an extended and animated webp. pub fn set_background_color(&mut self, color: Rgba) -> ImageResult<()> { self.inner - .set_background_color(color.0) + .set_background_color(color.into()) .map_err(ImageError::from_webp_decode) } } diff --git a/src/color.rs b/src/color.rs index 2002a27f14..06e42b33ee 100644 --- a/src/color.rs +++ b/src/color.rs @@ -1,8 +1,5 @@ -use std::ops::{Index, IndexMut}; - -use num_traits::{NumCast, ToPrimitive, Zero}; - -use crate::traits::{Enlargeable, Pixel, Primitive}; +use num_traits::NumCast; +use pixeli::{Gray, GrayAlpha, PixelComponent, Rgb, Rgba}; /// An enumeration over supported color types and bit depths #[derive(Copy, PartialEq, Eq, Debug, Clone, Hash)] @@ -30,6 +27,10 @@ pub enum ColorType { Rgb32F, /// Pixel is 32-bit float RGBA Rgba32F, + /// Pixel is 32-bit float Gray + Gray32F, + /// Pixel is 32-bit float GrayAlpha + GrayAlpha32F, } impl ColorType { @@ -44,6 +45,8 @@ impl ColorType { ColorType::Rgba16 => 8, ColorType::Rgb32F => 3 * 4, ColorType::Rgba32F => 4 * 4, + ColorType::Gray32F => 4, + ColorType::GrayAlpha32F => 2 * 4, } } @@ -51,8 +54,8 @@ impl ColorType { pub fn has_alpha(self) -> bool { use ColorType::*; match self { - L8 | L16 | Rgb8 | Rgb16 | Rgb32F => false, - La8 | Rgba8 | La16 | Rgba16 | Rgba32F => true, + L8 | L16 | Rgb8 | Rgb16 | Rgb32F | Gray32F => false, + La8 | Rgba8 | La16 | Rgba16 | Rgba32F | GrayAlpha32F => true, } } @@ -60,7 +63,7 @@ impl ColorType { pub fn has_color(self) -> bool { use ColorType::*; match self { - L8 | L16 | La8 | La16 => false, + L8 | L16 | La8 | La16 | Gray32F | GrayAlpha32F => false, Rgb8 | Rgb16 | Rgba8 | Rgba16 | Rgb32F | Rgba32F => true, } } @@ -141,6 +144,10 @@ pub enum ExtendedColorType { Rgb32F, /// Pixel is 32-bit float RGBA Rgba32F, + /// Pixel is 32-bit float Gray + Gray32F, + /// Pixel is 32-bit float GrayAlpha + GrayAlpha32F, /// Pixel is 8-bit CMYK Cmyk8, @@ -164,12 +171,14 @@ impl ExtendedColorType { | ExtendedColorType::L4 | ExtendedColorType::L8 | ExtendedColorType::L16 + | ExtendedColorType::Gray32F | ExtendedColorType::Unknown(_) => 1, ExtendedColorType::La1 | ExtendedColorType::La2 | ExtendedColorType::La4 | ExtendedColorType::La8 - | ExtendedColorType::La16 => 2, + | ExtendedColorType::La16 + | ExtendedColorType::GrayAlpha32F => 2, ExtendedColorType::Rgb1 | ExtendedColorType::Rgb2 | ExtendedColorType::Rgb4 @@ -214,6 +223,8 @@ impl ExtendedColorType { ExtendedColorType::Rgba16 => 64, ExtendedColorType::Rgb32F => 96, ExtendedColorType::Rgba32F => 128, + ExtendedColorType::Gray32F => 32, + ExtendedColorType::GrayAlpha32F => 32 * 2, ExtendedColorType::Bgr8 => 24, ExtendedColorType::Bgra8 => 32, ExtendedColorType::Cmyk8 => 32, @@ -241,506 +252,24 @@ impl From for ExtendedColorType { ColorType::Rgba16 => ExtendedColorType::Rgba16, ColorType::Rgb32F => ExtendedColorType::Rgb32F, ColorType::Rgba32F => ExtendedColorType::Rgba32F, + ColorType::Gray32F => ExtendedColorType::Gray32F, + ColorType::GrayAlpha32F => ExtendedColorType::GrayAlpha32F, } } } -macro_rules! define_colors { - {$( - $(#[$doc:meta])* - pub struct $ident:ident([T; $channels:expr, $alphas:expr]) - = $interpretation:literal; - )*} => { - -$( // START Structure definitions - -$(#[$doc])* -#[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)] -#[repr(transparent)] -#[allow(missing_docs)] -pub struct $ident (pub [T; $channels]); - -impl Pixel for $ident { - type Subpixel = T; - - const CHANNEL_COUNT: u8 = $channels; - - #[inline(always)] - fn channels(&self) -> &[T] { - &self.0 - } - - #[inline(always)] - fn channels_mut(&mut self) -> &mut [T] { - &mut self.0 - } - - const COLOR_MODEL: &'static str = $interpretation; - - fn channels4(&self) -> (T, T, T, T) { - const CHANNELS: usize = $channels; - let mut channels = [T::DEFAULT_MAX_VALUE; 4]; - channels[0..CHANNELS].copy_from_slice(&self.0); - (channels[0], channels[1], channels[2], channels[3]) - } - - fn from_channels(a: T, b: T, c: T, d: T,) -> $ident { - const CHANNELS: usize = $channels; - *<$ident as Pixel>::from_slice(&[a, b, c, d][..CHANNELS]) - } - - fn from_slice(slice: &[T]) -> &$ident { - assert_eq!(slice.len(), $channels); - unsafe { &*(slice.as_ptr() as *const $ident) } - } - fn from_slice_mut(slice: &mut [T]) -> &mut $ident { - assert_eq!(slice.len(), $channels); - unsafe { &mut *(slice.as_mut_ptr() as *mut $ident) } - } - - fn to_rgb(&self) -> Rgb { - let mut pix = Rgb([Zero::zero(), Zero::zero(), Zero::zero()]); - pix.from_color(self); - pix - } - - fn to_rgba(&self) -> Rgba { - let mut pix = Rgba([Zero::zero(), Zero::zero(), Zero::zero(), Zero::zero()]); - pix.from_color(self); - pix - } - - fn to_luma(&self) -> Luma { - let mut pix = Luma([Zero::zero()]); - pix.from_color(self); - pix - } - - fn to_luma_alpha(&self) -> LumaA { - let mut pix = LumaA([Zero::zero(), Zero::zero()]); - pix.from_color(self); - pix - } - - fn map(& self, f: F) -> $ident where F: FnMut(T) -> T { - let mut this = (*self).clone(); - this.apply(f); - this - } - - fn apply(&mut self, mut f: F) where F: FnMut(T) -> T { - for v in &mut self.0 { - *v = f(*v) - } - } - - fn map_with_alpha(&self, f: F, g: G) -> $ident where F: FnMut(T) -> T, G: FnMut(T) -> T { - let mut this = (*self).clone(); - this.apply_with_alpha(f, g); - this - } - - fn apply_with_alpha(&mut self, mut f: F, mut g: G) where F: FnMut(T) -> T, G: FnMut(T) -> T { - const ALPHA: usize = $channels - $alphas; - for v in self.0[..ALPHA].iter_mut() { - *v = f(*v) - } - // The branch of this match is `const`. This way ensures that no subexpression fails the - // `const_err` lint (the expression `self.0[ALPHA]` would). - if let Some(v) = self.0.get_mut(ALPHA) { - *v = g(*v) - } - } - - fn map2(&self, other: &Self, f: F) -> $ident where F: FnMut(T, T) -> T { - let mut this = (*self).clone(); - this.apply2(other, f); - this - } - - fn apply2(&mut self, other: &$ident, mut f: F) where F: FnMut(T, T) -> T { - for (a, &b) in self.0.iter_mut().zip(other.0.iter()) { - *a = f(*a, b) - } - } - - fn invert(&mut self) { - Invert::invert(self) - } - - fn blend(&mut self, other: &$ident) { - Blend::blend(self, other) - } -} - -impl Index for $ident { - type Output = T; - #[inline(always)] - fn index(&self, _index: usize) -> &T { - &self.0[_index] - } -} - -impl IndexMut for $ident { - #[inline(always)] - fn index_mut(&mut self, _index: usize) -> &mut T { - &mut self.0[_index] - } -} - -impl From<[T; $channels]> for $ident { - fn from(c: [T; $channels]) -> Self { - Self(c) - } -} - -)* // END Structure definitions - - } -} - -define_colors! { - /// RGB colors. - /// - /// For the purpose of color conversion, as well as blending, the implementation of `Pixel` - /// assumes an `sRGB` color space of its data. - pub struct Rgb([T; 3, 0]) = "RGB"; - /// Grayscale colors. - pub struct Luma([T; 1, 0]) = "Y"; - /// RGB colors + alpha channel - pub struct Rgba([T; 4, 1]) = "RGBA"; - /// Grayscale colors + alpha channel - pub struct LumaA([T; 2, 1]) = "YA"; -} - -/// Convert from one pixel component type to another. For example, convert from `u8` to `f32` pixel values. -pub trait FromPrimitive { - /// Converts from any pixel component type to this type. - fn from_primitive(component: Component) -> Self; -} - -impl FromPrimitive for T { - fn from_primitive(sample: T) -> Self { - sample - } -} - -// from f32: -// Note that in to-integer-conversion we are performing rounding but NumCast::from is implemented -// as truncate towards zero. We emulate rounding by adding a bias. - -impl FromPrimitive for u8 { - fn from_primitive(float: f32) -> Self { - let inner = (float.clamp(0.0, 1.0) * u8::MAX as f32).round(); - NumCast::from(inner).unwrap() - } -} - -impl FromPrimitive for u16 { - fn from_primitive(float: f32) -> Self { - let inner = (float.clamp(0.0, 1.0) * u16::MAX as f32).round(); - NumCast::from(inner).unwrap() - } -} - -// from u16: - -impl FromPrimitive for u8 { - fn from_primitive(c16: u16) -> Self { - fn from(c: impl Into) -> u32 { - c.into() - } - // The input c is the numerator of `c / u16::MAX`. - // Derive numerator of `num / u8::MAX`, with rounding. - // - // This method is based on the inverse (see FromPrimitive for u16) and was tested - // exhaustively in Python. It's the same as the reference function: - // round(c * (2**8 - 1) / (2**16 - 1)) - NumCast::from((from(c16) + 128) / 257).unwrap() - } -} - -impl FromPrimitive for f32 { - fn from_primitive(int: u16) -> Self { - (int as f32 / u16::MAX as f32).clamp(0.0, 1.0) - } -} - -// from u8: - -impl FromPrimitive for f32 { - fn from_primitive(int: u8) -> Self { - (int as f32 / u8::MAX as f32).clamp(0.0, 1.0) - } -} - -impl FromPrimitive for u16 { - fn from_primitive(c8: u8) -> Self { - let x = c8.to_u64().unwrap(); - NumCast::from((x << 8) | x).unwrap() - } -} - -/// Provides color conversions for the different pixel types. -pub trait FromColor { - /// Changes `self` to represent `Other` in the color space of `Self` - #[allow(clippy::wrong_self_convention)] - fn from_color(&mut self, _: &Other); -} - -/// Copy-based conversions to target pixel types using `FromColor`. -// FIXME: this trait should be removed and replaced with real color space models -// rather than assuming sRGB. -pub(crate) trait IntoColor { - /// Constructs a pixel of the target type and converts this pixel into it. - #[allow(clippy::wrong_self_convention)] - fn into_color(&self) -> Other; -} - -impl IntoColor for S -where - O: Pixel + FromColor, -{ - #[allow(clippy::wrong_self_convention)] - fn into_color(&self) -> O { - // Note we cannot use Pixel::CHANNELS_COUNT here to directly construct - // the pixel due to a current bug/limitation of consts. - #[allow(deprecated)] - let mut pix = O::from_channels(Zero::zero(), Zero::zero(), Zero::zero(), Zero::zero()); - pix.from_color(self); - pix - } -} - -/// Coefficients to transform from sRGB to a CIE Y (luminance) value. -const SRGB_LUMA: [u32; 3] = [2126, 7152, 722]; -const SRGB_LUMA_DIV: u32 = 10000; - -#[inline] -fn rgb_to_luma(rgb: &[T]) -> T { - let l = ::from(SRGB_LUMA[0]).unwrap() * rgb[0].to_larger() - + ::from(SRGB_LUMA[1]).unwrap() * rgb[1].to_larger() - + ::from(SRGB_LUMA[2]).unwrap() * rgb[2].to_larger(); - T::clamp_from(l / ::from(SRGB_LUMA_DIV).unwrap()) -} - -// `FromColor` for Luma -impl FromColor> for Luma -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Luma) { - let own = self.channels_mut(); - let other = other.channels(); - own[0] = T::from_primitive(other[0]); - } -} - -impl FromColor> for Luma -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &LumaA) { - self.channels_mut()[0] = T::from_primitive(other.channels()[0]) - } -} - -impl FromColor> for Luma -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Rgb) { - let gray = self.channels_mut(); - let rgb = other.channels(); - gray[0] = T::from_primitive(rgb_to_luma(rgb)); - } -} - -impl FromColor> for Luma -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Rgba) { - let gray = self.channels_mut(); - let rgb = other.channels(); - let l = rgb_to_luma(rgb); - gray[0] = T::from_primitive(l); - } -} - -// `FromColor` for LumaA - -impl FromColor> for LumaA -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &LumaA) { - let own = self.channels_mut(); - let other = other.channels(); - own[0] = T::from_primitive(other[0]); - own[1] = T::from_primitive(other[1]); - } -} - -impl FromColor> for LumaA -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Rgb) { - let gray_a = self.channels_mut(); - let rgb = other.channels(); - gray_a[0] = T::from_primitive(rgb_to_luma(rgb)); - gray_a[1] = T::DEFAULT_MAX_VALUE; - } -} - -impl FromColor> for LumaA -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Rgba) { - let gray_a = self.channels_mut(); - let rgba = other.channels(); - gray_a[0] = T::from_primitive(rgb_to_luma(rgba)); - gray_a[1] = T::from_primitive(rgba[3]); - } -} - -impl FromColor> for LumaA -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Luma) { - let gray_a = self.channels_mut(); - gray_a[0] = T::from_primitive(other.channels()[0]); - gray_a[1] = T::DEFAULT_MAX_VALUE; - } -} - -// `FromColor` for RGBA - -impl FromColor> for Rgba -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Rgba) { - let own = &mut self.0; - let other = &other.0; - own[0] = T::from_primitive(other[0]); - own[1] = T::from_primitive(other[1]); - own[2] = T::from_primitive(other[2]); - own[3] = T::from_primitive(other[3]); - } -} - -impl FromColor> for Rgba -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Rgb) { - let rgba = &mut self.0; - let rgb = &other.0; - rgba[0] = T::from_primitive(rgb[0]); - rgba[1] = T::from_primitive(rgb[1]); - rgba[2] = T::from_primitive(rgb[2]); - rgba[3] = T::DEFAULT_MAX_VALUE; - } -} - -impl FromColor> for Rgba -where - T: FromPrimitive, -{ - fn from_color(&mut self, gray: &LumaA) { - let rgba = &mut self.0; - let gray = &gray.0; - rgba[0] = T::from_primitive(gray[0]); - rgba[1] = T::from_primitive(gray[0]); - rgba[2] = T::from_primitive(gray[0]); - rgba[3] = T::from_primitive(gray[1]); - } -} - -impl FromColor> for Rgba -where - T: FromPrimitive, -{ - fn from_color(&mut self, gray: &Luma) { - let rgba = &mut self.0; - let gray = gray.0[0]; - rgba[0] = T::from_primitive(gray); - rgba[1] = T::from_primitive(gray); - rgba[2] = T::from_primitive(gray); - rgba[3] = T::DEFAULT_MAX_VALUE; - } -} - -// `FromColor` for RGB - -impl FromColor> for Rgb -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Rgb) { - let own = &mut self.0; - let other = &other.0; - own[0] = T::from_primitive(other[0]); - own[1] = T::from_primitive(other[1]); - own[2] = T::from_primitive(other[2]); - } -} - -impl FromColor> for Rgb -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Rgba) { - let rgb = &mut self.0; - let rgba = &other.0; - rgb[0] = T::from_primitive(rgba[0]); - rgb[1] = T::from_primitive(rgba[1]); - rgb[2] = T::from_primitive(rgba[2]); - } -} - -impl FromColor> for Rgb -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &LumaA) { - let rgb = &mut self.0; - let gray = other.0[0]; - rgb[0] = T::from_primitive(gray); - rgb[1] = T::from_primitive(gray); - rgb[2] = T::from_primitive(gray); - } -} - -impl FromColor> for Rgb -where - T: FromPrimitive, -{ - fn from_color(&mut self, other: &Luma) { - let rgb = &mut self.0; - let gray = other.0[0]; - rgb[0] = T::from_primitive(gray); - rgb[1] = T::from_primitive(gray); - rgb[2] = T::from_primitive(gray); - } -} - /// Blends a color inter another one -pub(crate) trait Blend { +pub trait Blend { /// Blends a color in-place. fn blend(&mut self, other: &Self); } -impl Blend for LumaA { - fn blend(&mut self, other: &LumaA) { - let max_t = T::DEFAULT_MAX_VALUE; +impl Blend for GrayAlpha { + fn blend(&mut self, other: &GrayAlpha) { + let max_t = T::COMPONENT_MAX; let max_t = max_t.to_f32().unwrap(); - let (bg_luma, bg_a) = (self.0[0], self.0[1]); - let (fg_luma, fg_a) = (other.0[0], other.0[1]); + let (bg_luma, bg_a) = (self.gray, self.a); + let (fg_luma, fg_a) = (other.gray, other.a); let (bg_luma, bg_a) = ( bg_luma.to_f32().unwrap() / max_t, @@ -761,36 +290,36 @@ impl Blend for LumaA { let out_luma_a = fg_luma_a + bg_luma_a * (1.0 - fg_a); let out_luma = out_luma_a / alpha_final; - *self = LumaA([ - NumCast::from(max_t * out_luma).unwrap(), - NumCast::from(max_t * alpha_final).unwrap(), - ]) + *self = GrayAlpha { + gray: NumCast::from(max_t * out_luma).unwrap(), + a: NumCast::from(max_t * alpha_final).unwrap(), + } } } -impl Blend for Luma { - fn blend(&mut self, other: &Luma) { +impl Blend for Gray { + fn blend(&mut self, other: &Gray) { *self = *other } } -impl Blend for Rgba { +impl Blend for Rgba { fn blend(&mut self, other: &Rgba) { // http://stackoverflow.com/questions/7438263/alpha-compositing-algorithm-blend-modes#answer-11163848 - if other.0[3].is_zero() { + if other.a.is_zero() { return; } - if other.0[3] == T::DEFAULT_MAX_VALUE { + if other.a == T::COMPONENT_MAX { *self = *other; return; } // First, as we don't know what type our pixel is, we have to convert to floats between 0.0 and 1.0 - let max_t = T::DEFAULT_MAX_VALUE; + let max_t = T::COMPONENT_MAX; let max_t = max_t.to_f32().unwrap(); - let (bg_r, bg_g, bg_b, bg_a) = (self.0[0], self.0[1], self.0[2], self.0[3]); - let (fg_r, fg_g, fg_b, fg_a) = (other.0[0], other.0[1], other.0[2], other.0[3]); + let (bg_r, bg_g, bg_b, bg_a) = (self.r, self.g, self.b, self.a); + let (fg_r, fg_g, fg_b, fg_a) = (other.r, other.g, other.b, other.a); let (bg_r, bg_g, bg_b, bg_a) = ( bg_r.to_f32().unwrap() / max_t, bg_g.to_f32().unwrap() / max_t, @@ -829,204 +358,177 @@ impl Blend for Rgba { ); // Cast back to our initial type on return - *self = Rgba([ - NumCast::from(max_t * out_r).unwrap(), - NumCast::from(max_t * out_g).unwrap(), - NumCast::from(max_t * out_b).unwrap(), - NumCast::from(max_t * alpha_final).unwrap(), - ]) + *self = Rgba { + r: NumCast::from(max_t * out_r).unwrap(), + g: NumCast::from(max_t * out_g).unwrap(), + b: NumCast::from(max_t * out_b).unwrap(), + a: NumCast::from(max_t * alpha_final).unwrap(), + } } } -impl Blend for Rgb { +impl Blend for Rgb { fn blend(&mut self, other: &Rgb) { *self = *other } } /// Invert a color -pub(crate) trait Invert { +pub trait Invert { /// Inverts a color in-place. fn invert(&mut self); } -impl Invert for LumaA { +impl Invert for GrayAlpha { fn invert(&mut self) { - let l = self.0; - let max = T::DEFAULT_MAX_VALUE; + let max = T::COMPONENT_MAX; - *self = LumaA([max - l[0], l[1]]) + *self = GrayAlpha { + gray: max - self.gray, + a: self.a, + } } } -impl Invert for Luma { +impl Invert for Gray { fn invert(&mut self) { - let l = self.0; - - let max = T::DEFAULT_MAX_VALUE; - let l1 = max - l[0]; - - *self = Luma([l1]) + *self = Gray { + gray: T::COMPONENT_MAX - self.gray, + } } } -impl Invert for Rgba { +impl Invert for Rgba { fn invert(&mut self) { - let rgba = self.0; + let max = T::COMPONENT_MAX; - let max = T::DEFAULT_MAX_VALUE; - - *self = Rgba([max - rgba[0], max - rgba[1], max - rgba[2], rgba[3]]) + *self = Rgba { + r: max - self.r, + g: max - self.g, + b: max - self.b, + a: self.a, + } } } -impl Invert for Rgb { +impl Invert for Rgb { fn invert(&mut self) { - let rgb = self.0; + let max = T::COMPONENT_MAX; - let max = T::DEFAULT_MAX_VALUE; - - let r1 = max - rgb[0]; - let g1 = max - rgb[1]; - let b1 = max - rgb[2]; - - *self = Rgb([r1, g1, b1]) + *self = Rgb { + r: max - self.r, + g: max - self.g, + b: max - self.b, + } } } #[cfg(test)] mod tests { - use super::{Luma, LumaA, Pixel, Rgb, Rgba}; - - #[test] - fn test_apply_with_alpha_rgba() { - let mut rgba = Rgba([0, 0, 0, 0]); - rgba.apply_with_alpha(|s| s, |_| 0xFF); - assert_eq!(rgba, Rgba([0, 0, 0, 0xFF])); - } - - #[test] - fn test_apply_with_alpha_rgb() { - let mut rgb = Rgb([0, 0, 0]); - rgb.apply_with_alpha(|s| s, |_| panic!("bug")); - assert_eq!(rgb, Rgb([0, 0, 0])); - } + use crate::color::Blend; - #[test] - fn test_map_with_alpha_rgba() { - let rgba = Rgba([0, 0, 0, 0]).map_with_alpha(|s| s, |_| 0xFF); - assert_eq!(rgba, Rgba([0, 0, 0, 0xFF])); - } - - #[test] - fn test_map_with_alpha_rgb() { - let rgb = Rgb([0, 0, 0]).map_with_alpha(|s| s, |_| panic!("bug")); - assert_eq!(rgb, Rgb([0, 0, 0])); - } + use super::{GrayAlpha, Rgba}; + use pixeli::Pixel; #[test] fn test_blend_luma_alpha() { - let a = &mut LumaA([255_u8, 255]); - let b = LumaA([255_u8, 255]); + let a = &mut GrayAlpha { + gray: 255_u8, + a: 255, + }; + let b = GrayAlpha { + gray: 255_u8, + a: 255, + }; a.blend(&b); - assert_eq!(a.0[0], 255); - assert_eq!(a.0[1], 255); + assert_eq!(a.gray, 255); + assert_eq!(a.a, 255); - let a = &mut LumaA([255_u8, 0]); - let b = LumaA([255_u8, 255]); + let a = &mut GrayAlpha { gray: 255_u8, a: 0 }; + let b = GrayAlpha { + gray: 255_u8, + a: 255, + }; a.blend(&b); - assert_eq!(a.0[0], 255); - assert_eq!(a.0[1], 255); + assert_eq!(a.gray, 255); + assert_eq!(a.a, 255); - let a = &mut LumaA([255_u8, 255]); - let b = LumaA([255_u8, 0]); + let a = &mut GrayAlpha { + gray: 255_u8, + a: 255, + }; + let b = GrayAlpha { gray: 255_u8, a: 0 }; a.blend(&b); - assert_eq!(a.0[0], 255); - assert_eq!(a.0[1], 255); + assert_eq!(a.gray, 255); + assert_eq!(a.a, 255); - let a = &mut LumaA([255_u8, 0]); - let b = LumaA([255_u8, 0]); + let a = &mut GrayAlpha { gray: 255_u8, a: 0 }; + let b = GrayAlpha { gray: 255_u8, a: 0 }; a.blend(&b); - assert_eq!(a.0[0], 255); - assert_eq!(a.0[1], 0); + assert_eq!(a.gray, 255); + assert_eq!(a.a, 0); } #[test] fn test_blend_rgba() { - let a = &mut Rgba([255_u8, 255, 255, 255]); - let b = Rgba([255_u8, 255, 255, 255]); - a.blend(&b); - assert_eq!(a.0, [255, 255, 255, 255]); - - let a = &mut Rgba([255_u8, 255, 255, 0]); - let b = Rgba([255_u8, 255, 255, 255]); + let a = &mut Rgba { + r: 255_u8, + g: 255, + b: 255, + a: 255, + }; + let b = Rgba { + r: 255_u8, + g: 255, + b: 255, + a: 255, + }; a.blend(&b); - assert_eq!(a.0, [255, 255, 255, 255]); + assert_eq!(a.component_array(), [255, 255, 255, 255]); - let a = &mut Rgba([255_u8, 255, 255, 255]); - let b = Rgba([255_u8, 255, 255, 0]); + let a = &mut Rgba { + r: 255_u8, + g: 255, + b: 255, + a: 0, + }; + let b = Rgba { + r: 255_u8, + g: 255, + b: 255, + a: 255, + }; a.blend(&b); - assert_eq!(a.0, [255, 255, 255, 255]); + assert_eq!(a.component_array(), [255, 255, 255, 255]); - let a = &mut Rgba([255_u8, 255, 255, 0]); - let b = Rgba([255_u8, 255, 255, 0]); + let a = &mut Rgba { + r: 255_u8, + g: 255, + b: 255, + a: 255, + }; + let b = Rgba { + r: 255_u8, + g: 255, + b: 255, + a: 0, + }; a.blend(&b); - assert_eq!(a.0, [255, 255, 255, 0]); - } - - #[test] - fn test_apply_without_alpha_rgba() { - let mut rgba = Rgba([0, 0, 0, 0]); - rgba.apply_without_alpha(|s| s + 1); - assert_eq!(rgba, Rgba([1, 1, 1, 0])); - } - - #[test] - fn test_apply_without_alpha_rgb() { - let mut rgb = Rgb([0, 0, 0]); - rgb.apply_without_alpha(|s| s + 1); - assert_eq!(rgb, Rgb([1, 1, 1])); - } - - #[test] - fn test_map_without_alpha_rgba() { - let rgba = Rgba([0, 0, 0, 0]).map_without_alpha(|s| s + 1); - assert_eq!(rgba, Rgba([1, 1, 1, 0])); - } - - #[test] - fn test_map_without_alpha_rgb() { - let rgb = Rgb([0, 0, 0]).map_without_alpha(|s| s + 1); - assert_eq!(rgb, Rgb([1, 1, 1])); - } + assert_eq!(a.component_array(), [255, 255, 255, 255]); - macro_rules! test_lossless_conversion { - ($a:ty, $b:ty, $c:ty) => { - let a: $a = [<$a as Pixel>::Subpixel::DEFAULT_MAX_VALUE >> 2; - <$a as Pixel>::CHANNEL_COUNT as usize] - .into(); - let b: $b = a.into_color(); - let c: $c = b.into_color(); - assert_eq!(a.channels(), c.channels()); + let a = &mut Rgba { + r: 255_u8, + g: 255, + b: 255, + a: 0, }; - } - - #[test] - fn test_lossless_conversions() { - use super::IntoColor; - use crate::traits::Primitive; - - test_lossless_conversion!(Luma, Luma, Luma); - test_lossless_conversion!(LumaA, LumaA, LumaA); - test_lossless_conversion!(Rgb, Rgb, Rgb); - test_lossless_conversion!(Rgba, Rgba, Rgba); - } - - #[test] - fn accuracy_conversion() { - use super::{Luma, Pixel, Rgb}; - let pixel = Rgb::from([13, 13, 13]); - let Luma([luma]) = pixel.to_luma(); - assert_eq!(luma, 13); + let b = Rgba { + r: 255_u8, + g: 255, + b: 255, + a: 0, + }; + a.blend(&b); + assert_eq!(a.component_array(), [255, 255, 255, 0]); } } diff --git a/src/dynimage.rs b/src/dynimage.rs index f67196c7f6..a17e23acf4 100644 --- a/src/dynimage.rs +++ b/src/dynimage.rs @@ -1,24 +1,25 @@ use std::io::{self, Seek, Write}; use std::path::Path; +use pixeli::{FromPixelCommon, Gray, GrayAlpha, Rgb, Rgba}; + #[cfg(feature = "gif")] use crate::codecs::gif; #[cfg(feature = "png")] use crate::codecs::png; use crate::buffer_::{ - ConvertBuffer, Gray16Image, GrayAlpha16Image, GrayAlphaImage, GrayImage, ImageBuffer, - Rgb16Image, RgbImage, Rgba16Image, RgbaImage, + ConvertBuffer, Gray16Image, Gray32FImage, GrayAlpha16Image, GrayAlpha32FImage, GrayAlphaImage, + GrayImage, ImageBuffer, Rgb16Image, RgbImage, Rgba16Image, RgbaImage, }; -use crate::color::{self, IntoColor}; +use crate::color::{self}; use crate::error::{ImageError, ImageResult, ParameterError, ParameterErrorKind}; use crate::flat::FlatSamples; +use crate::image; use crate::image::{GenericImage, GenericImageView, ImageDecoder, ImageEncoder, ImageFormat}; use crate::image_reader::free_functions; use crate::math::resize_dimensions; -use crate::traits::Pixel; use crate::ImageReader; -use crate::{image, Luma, LumaA}; use crate::{imageops, ExtendedColorType}; use crate::{Rgb32FImage, Rgba32FImage}; @@ -48,11 +49,11 @@ use crate::{Rgb32FImage, Rgba32FImage}; #[derive(Debug, PartialEq)] #[non_exhaustive] pub enum DynamicImage { - /// Each pixel in this image is 8-bit Luma - ImageLuma8(GrayImage), + /// Each pixel in this image is 8-bit Gray + ImageGray8(GrayImage), - /// Each pixel in this image is 8-bit Luma with alpha - ImageLumaA8(GrayAlphaImage), + /// Each pixel in this image is 8-bit Gray with alpha + ImageGrayAlpha8(GrayAlphaImage), /// Each pixel in this image is 8-bit Rgb ImageRgb8(RgbImage), @@ -60,11 +61,11 @@ pub enum DynamicImage { /// Each pixel in this image is 8-bit Rgb with alpha ImageRgba8(RgbaImage), - /// Each pixel in this image is 16-bit Luma - ImageLuma16(Gray16Image), + /// Each pixel in this image is 16-bit Gray + ImageGray16(Gray16Image), - /// Each pixel in this image is 16-bit Luma with alpha - ImageLumaA16(GrayAlpha16Image), + /// Each pixel in this image is 16-bit Gray with alpha + ImageGrayAlpha16(GrayAlpha16Image), /// Each pixel in this image is 16-bit Rgb ImageRgb16(Rgb16Image), @@ -77,37 +78,47 @@ pub enum DynamicImage { /// Each pixel in this image is 32-bit float Rgb with alpha ImageRgba32F(Rgba32FImage), + + /// Each pixel in this image is 32-bit float Gray + ImageGray32F(Gray32FImage), + + /// Each pixel in this image is 32-bit float Gray with alpha + ImageGrayAlpha32F(GrayAlpha32FImage), } macro_rules! dynamic_map( ($dynimage: expr, $image: pat => $action: expr) => ({ use DynamicImage::*; match $dynimage { - ImageLuma8($image) => ImageLuma8($action), - ImageLumaA8($image) => ImageLumaA8($action), + ImageGray8($image) => ImageGray8($action), + ImageGrayAlpha8($image) => ImageGrayAlpha8($action), ImageRgb8($image) => ImageRgb8($action), ImageRgba8($image) => ImageRgba8($action), - ImageLuma16($image) => ImageLuma16($action), - ImageLumaA16($image) => ImageLumaA16($action), + ImageGray16($image) => ImageGray16($action), + ImageGrayAlpha16($image) => ImageGrayAlpha16($action), ImageRgb16($image) => ImageRgb16($action), ImageRgba16($image) => ImageRgba16($action), ImageRgb32F($image) => ImageRgb32F($action), ImageRgba32F($image) => ImageRgba32F($action), + ImageGray32F($image) => ImageGray32F($action), + ImageGrayAlpha32F($image) => ImageGrayAlpha32F($action), } }); ($dynimage: expr, $image:pat_param, $action: expr) => ( match $dynimage { - DynamicImage::ImageLuma8($image) => $action, - DynamicImage::ImageLumaA8($image) => $action, + DynamicImage::ImageGray8($image) => $action, + DynamicImage::ImageGrayAlpha8($image) => $action, DynamicImage::ImageRgb8($image) => $action, DynamicImage::ImageRgba8($image) => $action, - DynamicImage::ImageLuma16($image) => $action, - DynamicImage::ImageLumaA16($image) => $action, + DynamicImage::ImageGray16($image) => $action, + DynamicImage::ImageGrayAlpha16($image) => $action, DynamicImage::ImageRgb16($image) => $action, DynamicImage::ImageRgba16($image) => $action, DynamicImage::ImageRgb32F($image) => $action, DynamicImage::ImageRgba32F($image) => $action, + DynamicImage::ImageGray32F($image) => $action, + DynamicImage::ImageGrayAlpha32F($image) => $action, } ); ); @@ -119,12 +130,12 @@ impl Clone for DynamicImage { fn clone_from(&mut self, source: &Self) { match (self, source) { - (Self::ImageLuma8(p1), Self::ImageLuma8(p2)) => p1.clone_from(p2), - (Self::ImageLumaA8(p1), Self::ImageLumaA8(p2)) => p1.clone_from(p2), + (Self::ImageGray8(p1), Self::ImageGray8(p2)) => p1.clone_from(p2), + (Self::ImageGrayAlpha8(p1), Self::ImageGrayAlpha8(p2)) => p1.clone_from(p2), (Self::ImageRgb8(p1), Self::ImageRgb8(p2)) => p1.clone_from(p2), (Self::ImageRgba8(p1), Self::ImageRgba8(p2)) => p1.clone_from(p2), - (Self::ImageLuma16(p1), Self::ImageLuma16(p2)) => p1.clone_from(p2), - (Self::ImageLumaA16(p1), Self::ImageLumaA16(p2)) => p1.clone_from(p2), + (Self::ImageGray16(p1), Self::ImageGray16(p2)) => p1.clone_from(p2), + (Self::ImageGrayAlpha16(p1), Self::ImageGrayAlpha16(p2)) => p1.clone_from(p2), (Self::ImageRgb16(p1), Self::ImageRgb16(p2)) => p1.clone_from(p2), (Self::ImageRgba16(p1), Self::ImageRgba16(p2)) => p1.clone_from(p2), (Self::ImageRgb32F(p1), Self::ImageRgb32F(p2)) => p1.clone_from(p2), @@ -150,18 +161,20 @@ impl DynamicImage { Rgba16 => Self::new_rgba16(w, h), Rgb32F => Self::new_rgb32f(w, h), Rgba32F => Self::new_rgba32f(w, h), + Gray32F => Self::new_gray32f(w, h), + GrayAlpha32F => Self::new_grayalpha32f(w, h), } } /// Creates a dynamic image backed by a buffer of gray pixels. pub fn new_luma8(w: u32, h: u32) -> DynamicImage { - DynamicImage::ImageLuma8(ImageBuffer::new(w, h)) + DynamicImage::ImageGray8(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of gray /// pixels with transparency. pub fn new_luma_a8(w: u32, h: u32) -> DynamicImage { - DynamicImage::ImageLumaA8(ImageBuffer::new(w, h)) + DynamicImage::ImageGrayAlpha8(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of RGB pixels. @@ -176,13 +189,13 @@ impl DynamicImage { /// Creates a dynamic image backed by a buffer of gray pixels. pub fn new_luma16(w: u32, h: u32) -> DynamicImage { - DynamicImage::ImageLuma16(ImageBuffer::new(w, h)) + DynamicImage::ImageGray16(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of gray /// pixels with transparency. pub fn new_luma_a16(w: u32, h: u32) -> DynamicImage { - DynamicImage::ImageLumaA16(ImageBuffer::new(w, h)) + DynamicImage::ImageGrayAlpha16(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of RGB pixels. @@ -205,6 +218,16 @@ impl DynamicImage { DynamicImage::ImageRgba32F(ImageBuffer::new(w, h)) } + /// Creates a dynamic image backed by a buffer of RGB pixels. + pub fn new_gray32f(w: u32, h: u32) -> DynamicImage { + DynamicImage::ImageGray32F(ImageBuffer::new(w, h)) + } + + /// Creates a dynamic image backed by a buffer of RGBA pixels. + pub fn new_grayalpha32f(w: u32, h: u32) -> DynamicImage { + DynamicImage::ImageGrayAlpha32F(ImageBuffer::new(w, h)) + } + /// Decodes an encoded image into a dynamic image. pub fn from_decoder(decoder: impl ImageDecoder) -> ImageResult { decoder_to_image(decoder) @@ -240,33 +263,33 @@ impl DynamicImage { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a Luma image. + /// Returns a copy of this image as a Gray image. pub fn to_luma8(&self) -> GrayImage { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a Luma image. + /// Returns a copy of this image as a Gray image. pub fn to_luma16(&self) -> Gray16Image { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a Luma image. - pub fn to_luma32f(&self) -> ImageBuffer, Vec> { + /// Returns a copy of this image as a Gray image. + pub fn to_luma32f(&self) -> ImageBuffer, Vec> { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a LumaA image. + /// Returns a copy of this image as a GrayAlpha image. pub fn to_luma_alpha8(&self) -> GrayAlphaImage { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a LumaA image. + /// Returns a copy of this image as a GrayAlpha image. pub fn to_luma_alpha16(&self) -> GrayAlpha16Image { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a LumaA image. - pub fn to_luma_alpha32f(&self) -> ImageBuffer, Vec> { + /// Returns a copy of this image as a GrayAlpha image. + pub fn to_luma_alpha32f(&self) -> ImageBuffer, Vec> { dynamic_map!(*self, ref p, p.convert()) } @@ -336,46 +359,46 @@ impl DynamicImage { } } - /// Consume the image and returns a Luma image. + /// Consume the image and returns a Gray image. /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. pub fn into_luma8(self) -> GrayImage { match self { - DynamicImage::ImageLuma8(x) => x, + DynamicImage::ImageGray8(x) => x, x => x.to_luma8(), } } - /// Consume the image and returns a Luma image. + /// Consume the image and returns a Gray image. /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. pub fn into_luma16(self) -> Gray16Image { match self { - DynamicImage::ImageLuma16(x) => x, + DynamicImage::ImageGray16(x) => x, x => x.to_luma16(), } } - /// Consume the image and returns a LumaA image. + /// Consume the image and returns a GrayAlpha image. /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. pub fn into_luma_alpha8(self) -> GrayAlphaImage { match self { - DynamicImage::ImageLumaA8(x) => x, + DynamicImage::ImageGrayAlpha8(x) => x, x => x.to_luma_alpha8(), } } - /// Consume the image and returns a LumaA image. + /// Consume the image and returns a GrayAlpha image. /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. pub fn into_luma_alpha16(self) -> GrayAlpha16Image { match self { - DynamicImage::ImageLumaA16(x) => x, + DynamicImage::ImageGrayAlpha16(x) => x, x => x.to_luma_alpha16(), } } @@ -428,7 +451,7 @@ impl DynamicImage { /// Return a reference to an 8bit Grayscale image pub fn as_luma8(&self) -> Option<&GrayImage> { match *self { - DynamicImage::ImageLuma8(ref p) => Some(p), + DynamicImage::ImageGray8(ref p) => Some(p), _ => None, } } @@ -436,7 +459,7 @@ impl DynamicImage { /// Return a mutable reference to an 8bit Grayscale image pub fn as_mut_luma8(&mut self) -> Option<&mut GrayImage> { match *self { - DynamicImage::ImageLuma8(ref mut p) => Some(p), + DynamicImage::ImageGray8(ref mut p) => Some(p), _ => None, } } @@ -444,7 +467,7 @@ impl DynamicImage { /// Return a reference to an 8bit Grayscale image with an alpha channel pub fn as_luma_alpha8(&self) -> Option<&GrayAlphaImage> { match *self { - DynamicImage::ImageLumaA8(ref p) => Some(p), + DynamicImage::ImageGrayAlpha8(ref p) => Some(p), _ => None, } } @@ -452,7 +475,7 @@ impl DynamicImage { /// Return a mutable reference to an 8bit Grayscale image with an alpha channel pub fn as_mut_luma_alpha8(&mut self) -> Option<&mut GrayAlphaImage> { match *self { - DynamicImage::ImageLumaA8(ref mut p) => Some(p), + DynamicImage::ImageGrayAlpha8(ref mut p) => Some(p), _ => None, } } @@ -524,7 +547,7 @@ impl DynamicImage { /// Return a reference to an 16bit Grayscale image pub fn as_luma16(&self) -> Option<&Gray16Image> { match *self { - DynamicImage::ImageLuma16(ref p) => Some(p), + DynamicImage::ImageGray16(ref p) => Some(p), _ => None, } } @@ -532,7 +555,7 @@ impl DynamicImage { /// Return a mutable reference to an 16bit Grayscale image pub fn as_mut_luma16(&mut self) -> Option<&mut Gray16Image> { match *self { - DynamicImage::ImageLuma16(ref mut p) => Some(p), + DynamicImage::ImageGray16(ref mut p) => Some(p), _ => None, } } @@ -540,7 +563,7 @@ impl DynamicImage { /// Return a reference to an 16bit Grayscale image with an alpha channel pub fn as_luma_alpha16(&self) -> Option<&GrayAlpha16Image> { match *self { - DynamicImage::ImageLumaA16(ref p) => Some(p), + DynamicImage::ImageGrayAlpha16(ref p) => Some(p), _ => None, } } @@ -548,7 +571,7 @@ impl DynamicImage { /// Return a mutable reference to an 16bit Grayscale image with an alpha channel pub fn as_mut_luma_alpha16(&mut self) -> Option<&mut GrayAlpha16Image> { match *self { - DynamicImage::ImageLumaA16(ref mut p) => Some(p), + DynamicImage::ImageGrayAlpha16(ref mut p) => Some(p), _ => None, } } @@ -556,8 +579,8 @@ impl DynamicImage { /// Return a view on the raw sample buffer for 8 bit per channel images. pub fn as_flat_samples_u8(&self) -> Option> { match *self { - DynamicImage::ImageLuma8(ref p) => Some(p.as_flat_samples()), - DynamicImage::ImageLumaA8(ref p) => Some(p.as_flat_samples()), + DynamicImage::ImageGray8(ref p) => Some(p.as_flat_samples()), + DynamicImage::ImageGrayAlpha8(ref p) => Some(p.as_flat_samples()), DynamicImage::ImageRgb8(ref p) => Some(p.as_flat_samples()), DynamicImage::ImageRgba8(ref p) => Some(p.as_flat_samples()), _ => None, @@ -567,8 +590,8 @@ impl DynamicImage { /// Return a view on the raw sample buffer for 16 bit per channel images. pub fn as_flat_samples_u16(&self) -> Option> { match *self { - DynamicImage::ImageLuma16(ref p) => Some(p.as_flat_samples()), - DynamicImage::ImageLumaA16(ref p) => Some(p.as_flat_samples()), + DynamicImage::ImageGray16(ref p) => Some(p.as_flat_samples()), + DynamicImage::ImageGrayAlpha16(ref p) => Some(p.as_flat_samples()), DynamicImage::ImageRgb16(ref p) => Some(p.as_flat_samples()), DynamicImage::ImageRgba16(ref p) => Some(p.as_flat_samples()), _ => None, @@ -627,16 +650,18 @@ impl DynamicImage { /// Return this image's color type. pub fn color(&self) -> color::ColorType { match *self { - DynamicImage::ImageLuma8(_) => color::ColorType::L8, - DynamicImage::ImageLumaA8(_) => color::ColorType::La8, + DynamicImage::ImageGray8(_) => color::ColorType::L8, + DynamicImage::ImageGrayAlpha8(_) => color::ColorType::La8, DynamicImage::ImageRgb8(_) => color::ColorType::Rgb8, DynamicImage::ImageRgba8(_) => color::ColorType::Rgba8, - DynamicImage::ImageLuma16(_) => color::ColorType::L16, - DynamicImage::ImageLumaA16(_) => color::ColorType::La16, + DynamicImage::ImageGray16(_) => color::ColorType::L16, + DynamicImage::ImageGrayAlpha16(_) => color::ColorType::La16, DynamicImage::ImageRgb16(_) => color::ColorType::Rgb16, DynamicImage::ImageRgba16(_) => color::ColorType::Rgba16, DynamicImage::ImageRgb32F(_) => color::ColorType::Rgb32F, DynamicImage::ImageRgba32F(_) => color::ColorType::Rgba32F, + DynamicImage::ImageGray32F(_) => color::ColorType::Rgb32F, + DynamicImage::ImageGrayAlpha32F(_) => color::ColorType::Rgba32F, } } @@ -651,32 +676,36 @@ impl DynamicImage { } /// Return a grayscale version of this image. - /// Returns `Luma` images in most cases. However, for `f32` images, - /// this will return a grayscale `Rgb/Rgba` image instead. pub fn grayscale(&self) -> DynamicImage { match *self { - DynamicImage::ImageLuma8(ref p) => DynamicImage::ImageLuma8(p.clone()), - DynamicImage::ImageLumaA8(ref p) => { - DynamicImage::ImageLumaA8(imageops::grayscale_alpha(p)) + DynamicImage::ImageGray8(ref p) => DynamicImage::ImageGray8(p.clone()), + DynamicImage::ImageGrayAlpha8(ref p) => { + DynamicImage::ImageGrayAlpha8(imageops::convert_generic_image(p)) + } + DynamicImage::ImageRgb8(ref p) => { + DynamicImage::ImageGray8(imageops::convert_generic_image(p)) } - DynamicImage::ImageRgb8(ref p) => DynamicImage::ImageLuma8(imageops::grayscale(p)), DynamicImage::ImageRgba8(ref p) => { - DynamicImage::ImageLumaA8(imageops::grayscale_alpha(p)) + DynamicImage::ImageGrayAlpha8(imageops::convert_generic_image(p)) + } + DynamicImage::ImageGray16(ref p) => DynamicImage::ImageGray16(p.clone()), + DynamicImage::ImageGrayAlpha16(ref p) => { + DynamicImage::ImageGrayAlpha16(imageops::convert_generic_image(p)) } - DynamicImage::ImageLuma16(ref p) => DynamicImage::ImageLuma16(p.clone()), - DynamicImage::ImageLumaA16(ref p) => { - DynamicImage::ImageLumaA16(imageops::grayscale_alpha(p)) + DynamicImage::ImageRgb16(ref p) => { + DynamicImage::ImageGray16(imageops::convert_generic_image(p)) } - DynamicImage::ImageRgb16(ref p) => DynamicImage::ImageLuma16(imageops::grayscale(p)), DynamicImage::ImageRgba16(ref p) => { - DynamicImage::ImageLumaA16(imageops::grayscale_alpha(p)) + DynamicImage::ImageGrayAlpha16(imageops::convert_generic_image(p)) } DynamicImage::ImageRgb32F(ref p) => { - DynamicImage::ImageRgb32F(imageops::grayscale_with_type(p)) + DynamicImage::ImageGray32F(imageops::convert_generic_image(p)) } DynamicImage::ImageRgba32F(ref p) => { - DynamicImage::ImageRgba32F(imageops::grayscale_with_type_alpha(p)) + DynamicImage::ImageGrayAlpha32F(imageops::convert_generic_image(p)) } + DynamicImage::ImageGray32F(ref p) => DynamicImage::ImageGray32F(p.clone()), + DynamicImage::ImageGrayAlpha32F(ref p) => DynamicImage::ImageGrayAlpha32F(p.clone()), } } @@ -895,13 +924,13 @@ impl DynamicImage { impl From for DynamicImage { fn from(image: GrayImage) -> Self { - DynamicImage::ImageLuma8(image) + DynamicImage::ImageGray8(image) } } impl From for DynamicImage { fn from(image: GrayAlphaImage) -> Self { - DynamicImage::ImageLumaA8(image) + DynamicImage::ImageGrayAlpha8(image) } } @@ -919,13 +948,13 @@ impl From for DynamicImage { impl From for DynamicImage { fn from(image: Gray16Image) -> Self { - DynamicImage::ImageLuma16(image) + DynamicImage::ImageGray16(image) } } impl From for DynamicImage { fn from(image: GrayAlpha16Image) -> Self { - DynamicImage::ImageLumaA16(image) + DynamicImage::ImageGrayAlpha16(image) } } @@ -953,73 +982,109 @@ impl From for DynamicImage { } } -impl From, Vec>> for DynamicImage { - fn from(image: ImageBuffer, Vec>) -> Self { +impl From, Vec>> for DynamicImage { + fn from(image: ImageBuffer, Vec>) -> Self { DynamicImage::ImageRgb32F(image.convert()) } } -impl From, Vec>> for DynamicImage { - fn from(image: ImageBuffer, Vec>) -> Self { +impl From, Vec>> for DynamicImage { + fn from(image: ImageBuffer, Vec>) -> Self { DynamicImage::ImageRgba32F(image.convert()) } } #[allow(deprecated)] impl GenericImageView for DynamicImage { - type Pixel = color::Rgba; // TODO use f32 as default for best precision and unbounded color? + type Pixel = Rgba; // TODO use f32 as default for best precision and unbounded color? fn dimensions(&self) -> (u32, u32) { dynamic_map!(*self, ref p, p.dimensions()) } - fn get_pixel(&self, x: u32, y: u32) -> color::Rgba { - dynamic_map!(*self, ref p, p.get_pixel(x, y).to_rgba().into_color()) + fn get_pixel(&self, x: u32, y: u32) -> Rgba { + dynamic_map!(*self, ref p, Rgba::from_pixel_common(*p.get_pixel(x, y))) } } #[allow(deprecated)] impl GenericImage for DynamicImage { - fn put_pixel(&mut self, x: u32, y: u32, pixel: color::Rgba) { + fn put_pixel(&mut self, x: u32, y: u32, pixel: Rgba) { match *self { - DynamicImage::ImageLuma8(ref mut p) => p.put_pixel(x, y, pixel.to_luma()), - DynamicImage::ImageLumaA8(ref mut p) => p.put_pixel(x, y, pixel.to_luma_alpha()), - DynamicImage::ImageRgb8(ref mut p) => p.put_pixel(x, y, pixel.to_rgb()), + DynamicImage::ImageGray8(ref mut p) => { + p.put_pixel(x, y, Gray::from_pixel_common(pixel)) + } + DynamicImage::ImageGrayAlpha8(ref mut p) => { + p.put_pixel(x, y, GrayAlpha::from_pixel_common(pixel)) + } + DynamicImage::ImageRgb8(ref mut p) => p.put_pixel(x, y, Rgb::from_pixel_common(pixel)), DynamicImage::ImageRgba8(ref mut p) => p.put_pixel(x, y, pixel), - DynamicImage::ImageLuma16(ref mut p) => p.put_pixel(x, y, pixel.to_luma().into_color()), - DynamicImage::ImageLumaA16(ref mut p) => { - p.put_pixel(x, y, pixel.to_luma_alpha().into_color()) + DynamicImage::ImageGray16(ref mut p) => { + p.put_pixel(x, y, Gray::from_pixel_common(pixel)) + } + DynamicImage::ImageGrayAlpha16(ref mut p) => { + p.put_pixel(x, y, GrayAlpha::from_pixel_common(pixel)) + } + DynamicImage::ImageRgb16(ref mut p) => p.put_pixel(x, y, Rgb::from_pixel_common(pixel)), + DynamicImage::ImageRgba16(ref mut p) => { + p.put_pixel(x, y, Rgba::from_pixel_common(pixel)) + } + DynamicImage::ImageRgb32F(ref mut p) => { + p.put_pixel(x, y, Rgb::from_pixel_common(pixel)) + } + DynamicImage::ImageRgba32F(ref mut p) => { + p.put_pixel(x, y, Rgba::from_pixel_common(pixel)) + } + DynamicImage::ImageGray32F(ref mut p) => { + p.put_pixel(x, y, Gray::from_pixel_common(pixel)) + } + DynamicImage::ImageGrayAlpha32F(ref mut p) => { + p.put_pixel(x, y, GrayAlpha::from_pixel_common(pixel)) } - DynamicImage::ImageRgb16(ref mut p) => p.put_pixel(x, y, pixel.to_rgb().into_color()), - DynamicImage::ImageRgba16(ref mut p) => p.put_pixel(x, y, pixel.into_color()), - DynamicImage::ImageRgb32F(ref mut p) => p.put_pixel(x, y, pixel.to_rgb().into_color()), - DynamicImage::ImageRgba32F(ref mut p) => p.put_pixel(x, y, pixel.into_color()), } } - fn blend_pixel(&mut self, x: u32, y: u32, pixel: color::Rgba) { + fn blend_pixel(&mut self, x: u32, y: u32, pixel: Rgba) { match *self { - DynamicImage::ImageLuma8(ref mut p) => p.blend_pixel(x, y, pixel.to_luma()), - DynamicImage::ImageLumaA8(ref mut p) => p.blend_pixel(x, y, pixel.to_luma_alpha()), - DynamicImage::ImageRgb8(ref mut p) => p.blend_pixel(x, y, pixel.to_rgb()), + DynamicImage::ImageGray8(ref mut p) => { + p.blend_pixel(x, y, Gray::from_pixel_common(pixel)) + } + DynamicImage::ImageGrayAlpha8(ref mut p) => { + p.blend_pixel(x, y, GrayAlpha::from_pixel_common(pixel)) + } + DynamicImage::ImageRgb8(ref mut p) => { + p.blend_pixel(x, y, Rgb::from_pixel_common(pixel)) + } DynamicImage::ImageRgba8(ref mut p) => p.blend_pixel(x, y, pixel), - DynamicImage::ImageLuma16(ref mut p) => { - p.blend_pixel(x, y, pixel.to_luma().into_color()) + DynamicImage::ImageGray16(ref mut p) => { + p.blend_pixel(x, y, Gray::from_pixel_common(pixel)) + } + DynamicImage::ImageGrayAlpha16(ref mut p) => { + p.blend_pixel(x, y, GrayAlpha::from_pixel_common(pixel)) } - DynamicImage::ImageLumaA16(ref mut p) => { - p.blend_pixel(x, y, pixel.to_luma_alpha().into_color()) + DynamicImage::ImageRgb16(ref mut p) => { + p.blend_pixel(x, y, Rgb::from_pixel_common(pixel)) + } + DynamicImage::ImageRgba16(ref mut p) => { + p.blend_pixel(x, y, Rgba::from_pixel_common(pixel)) } - DynamicImage::ImageRgb16(ref mut p) => p.blend_pixel(x, y, pixel.to_rgb().into_color()), - DynamicImage::ImageRgba16(ref mut p) => p.blend_pixel(x, y, pixel.into_color()), DynamicImage::ImageRgb32F(ref mut p) => { - p.blend_pixel(x, y, pixel.to_rgb().into_color()) + p.blend_pixel(x, y, Rgb::from_pixel_common(pixel)) + } + DynamicImage::ImageRgba32F(ref mut p) => { + p.blend_pixel(x, y, Rgba::from_pixel_common(pixel)) + } + DynamicImage::ImageGray32F(ref mut p) => { + p.blend_pixel(x, y, Gray::from_pixel_common(pixel)) + } + DynamicImage::ImageGrayAlpha32F(ref mut p) => { + p.blend_pixel(x, y, GrayAlpha::from_pixel_common(pixel)) } - DynamicImage::ImageRgba32F(ref mut p) => p.blend_pixel(x, y, pixel.into_color()), } } /// Do not use is function: It is unimplemented! - fn get_pixel_mut(&mut self, _: u32, _: u32) -> &mut color::Rgba { + fn get_pixel_mut(&mut self, _: u32, _: u32) -> &mut Rgba { unimplemented!() } } @@ -1048,12 +1113,12 @@ fn decoder_to_image(decoder: I) -> ImageResult { color::ColorType::L8 => { let buf = image::decoder_to_vec(decoder)?; - ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageLuma8) + ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageGray8) } color::ColorType::La8 => { let buf = image::decoder_to_vec(decoder)?; - ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageLumaA8) + ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageGrayAlpha8) } color::ColorType::Rgb16 => { @@ -1076,14 +1141,24 @@ fn decoder_to_image(decoder: I) -> ImageResult { ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageRgba32F) } + color::ColorType::Gray32F => { + let buf = image::decoder_to_vec(decoder)?; + ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageGray32F) + } + + color::ColorType::GrayAlpha32F => { + let buf = image::decoder_to_vec(decoder)?; + ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageGrayAlpha32F) + } + color::ColorType::L16 => { let buf = image::decoder_to_vec(decoder)?; - ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageLuma16) + ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageGray16) } color::ColorType::La16 => { let buf = image::decoder_to_vec(decoder)?; - ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageLumaA16) + ImageBuffer::from_raw(w, h, buf).map(DynamicImage::ImageGrayAlpha16) } }; @@ -1221,6 +1296,8 @@ mod bench { #[cfg(test)] mod test { + use pixeli::Rgba; + use crate::color::ColorType; #[test] @@ -1246,11 +1323,26 @@ mod test { fn test_grayscale(mut img: super::DynamicImage, alpha_discarded: bool) { use crate::image::{GenericImage, GenericImageView}; - img.put_pixel(0, 0, crate::color::Rgba([255, 0, 0, 100])); + img.put_pixel( + 0, + 0, + Rgba { + r: 255, + g: 0, + b: 0, + a: 100, + }, + ); let expected_alpha = if alpha_discarded { 255 } else { 100 }; assert_eq!( img.grayscale().get_pixel(0, 0), - crate::color::Rgba([54, 54, 54, expected_alpha]) + Rgba { + r: 54, + g: 54, + b: 54, + a: expected_alpha + }, + "alpha_discarded={alpha_discarded}" ); } @@ -1322,6 +1414,18 @@ mod test { test_grayscale_alpha_preserved(super::DynamicImage::new(1, 1, ColorType::Rgba32F)); } + #[test] + fn test_grayscale_gray32f() { + test_grayscale_alpha_discarded(super::DynamicImage::new_gray32f(1, 1)); + test_grayscale_alpha_discarded(super::DynamicImage::new(1, 1, ColorType::Gray32F)); + } + + #[test] + fn test_grayscale_grayalpha32f() { + test_grayscale_alpha_preserved(super::DynamicImage::new_grayalpha32f(1, 1)); + test_grayscale_alpha_preserved(super::DynamicImage::new(1, 1, ColorType::GrayAlpha32F)); + } + #[test] fn test_dynamic_image_default_implementation() { // Test that structs wrapping a DynamicImage are able to auto-derive the Default trait @@ -1343,7 +1447,7 @@ mod test { let pixels = vec![65535u16; 64 * 64]; let img = super::ImageBuffer::from_vec(64, 64, pixels).unwrap(); - let img = super::DynamicImage::ImageLuma16(img); + let img = super::DynamicImage::ImageGray16(img); assert!(img.as_luma16().is_some()); let bytes: Vec = img.into_bytes(); diff --git a/src/flat.rs b/src/flat.rs index d54b8c6539..5cc03f719a 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -9,7 +9,7 @@ //! ```no_run //! use std::ptr; //! use std::slice; -//! use image::Rgb; +//! use pixeli::Rgb; //! use image::flat::{FlatSamples, SampleLayout}; //! use image::imageops::thumbnail; //! @@ -46,14 +46,14 @@ use std::ops::{Deref, Index, IndexMut}; use std::{cmp, error, fmt}; use num_traits::Zero; +use pixeli::{ContiguousPixel, Pixel}; -use crate::color::ColorType; +use crate::color::{Blend, ColorType}; use crate::error::{ DecodingError, ImageError, ImageFormatHint, ParameterError, ParameterErrorKind, UnsupportedError, UnsupportedErrorKind, }; use crate::image::{GenericImage, GenericImageView}; -use crate::traits::Pixel; use crate::ImageBuffer; /// A flat buffer over a (multi channel) image. @@ -594,15 +594,15 @@ impl FlatSamples { /// buffer. It also checks that the specified pixel format expects the same number of channels /// that are present in this buffer. Neither are larger nor a smaller number will be accepted. /// There is no automatic conversion. - pub fn as_view

(&self) -> Result, Error> + pub fn as_view

(&self) -> Result, Error> where P: Pixel, - Buffer: AsRef<[P::Subpixel]>, + Buffer: AsRef<[P::Component]>, { - if self.layout.channels != P::CHANNEL_COUNT { + if self.layout.channels != P::COMPONENT_COUNT { return Err(Error::ChannelCountMismatch( self.layout.channels, - P::CHANNEL_COUNT, + P::COMPONENT_COUNT, )); } @@ -636,15 +636,15 @@ impl FlatSamples { /// **WARNING**: Note that of course samples may alias, so that the mutable reference returned /// for one sample can in fact modify other samples as well. Sometimes exactly this is /// intended. - pub fn as_view_with_mut_samples

(&mut self) -> Result, Error> + pub fn as_view_with_mut_samples

(&mut self) -> Result, Error> where P: Pixel, - Buffer: AsMut<[P::Subpixel]>, + Buffer: AsMut<[P::Component]>, { - if self.layout.channels != P::CHANNEL_COUNT { + if self.layout.channels != P::COMPONENT_COUNT { return Err(Error::ChannelCountMismatch( self.layout.channels, - P::CHANNEL_COUNT, + P::COMPONENT_COUNT, )); } @@ -674,19 +674,19 @@ impl FlatSamples { /// provides many more operations, is possibly faster (if not you may want to open an issue) is /// generally polished. You can also try to convert this buffer inline, see /// `ImageBuffer::from_raw`. - pub fn as_view_mut

(&mut self) -> Result, Error> + pub fn as_view_mut

(&mut self) -> Result, Error> where P: Pixel, - Buffer: AsMut<[P::Subpixel]>, + Buffer: AsMut<[P::Component]>, { if !self.layout.is_normal(NormalForm::PixelPacked) { return Err(Error::NormalFormRequired(NormalForm::PixelPacked)); } - if self.layout.channels != P::CHANNEL_COUNT { + if self.layout.channels != P::COMPONENT_COUNT { return Err(Error::ChannelCountMismatch( self.layout.channels, - P::CHANNEL_COUNT, + P::COMPONENT_COUNT, )); } @@ -774,17 +774,17 @@ impl FlatSamples { /// not release any allocation. pub fn try_into_buffer

(self) -> Result, (Error, Self)> where - P: Pixel + 'static, - P::Subpixel: 'static, - Buffer: Deref, + P: ContiguousPixel + 'static, + P::Component: 'static, + Buffer: Deref, { if !self.is_normal(NormalForm::RowMajorPacked) { return Err((Error::NormalFormRequired(NormalForm::RowMajorPacked), self)); } - if self.layout.channels != P::CHANNEL_COUNT { + if self.layout.channels != P::COMPONENT_COUNT { return Err(( - Error::ChannelCountMismatch(self.layout.channels, P::CHANNEL_COUNT), + Error::ChannelCountMismatch(self.layout.channels, P::COMPONENT_COUNT), self, )); } @@ -925,7 +925,7 @@ impl FlatSamples { } } -impl<'buf, Subpixel> FlatSamples<&'buf [Subpixel]> { +impl<'buf, Component, const N: usize> FlatSamples<[Component; N]> { /// Create a monocolor image from a single pixel. /// /// This can be used as a very cheap source of a `GenericImageView` with an arbitrary number of @@ -935,9 +935,10 @@ impl<'buf, Subpixel> FlatSamples<&'buf [Subpixel]> { /// /// ``` /// # fn paint_something(_: T) {} - /// use image::{flat::FlatSamples, GenericImage, RgbImage, Rgb}; + /// use image::{flat::FlatSamples, GenericImage, RgbImage}; + /// use pixeli::Rgb; /// - /// let background = Rgb([20, 20, 20]); + /// let background = Rgb{r: 20, g: 20, b: 20}; /// let bg = FlatSamples::with_monocolor(&background, 200, 200);; /// /// let mut image = RgbImage::new(200, 200); @@ -948,13 +949,12 @@ impl<'buf, Subpixel> FlatSamples<&'buf [Subpixel]> { /// ``` pub fn with_monocolor

(pixel: &'buf P, width: u32, height: u32) -> Self where - P: Pixel, - Subpixel: crate::Primitive, + P: Pixel = [Component; N]>, { FlatSamples { - samples: pixel.channels(), + samples: pixel.component_array(), layout: SampleLayout { - channels: P::CHANNEL_COUNT, + channels: P::COMPONENT_COUNT, channel_stride: 1, width, width_stride: 0, @@ -985,7 +985,7 @@ impl<'buf, Subpixel> FlatSamples<&'buf [Subpixel]> { #[derive(Clone, Debug)] pub struct View where - Buffer: AsRef<[P::Subpixel]>, + Buffer: AsRef<[P::Component]>, { inner: FlatSamples, phantom: PhantomData

, @@ -995,7 +995,7 @@ where /// /// While this wraps a buffer similar to `ImageBuffer`, this is mostly intended as a utility. The /// library endorsed normalized representation is still `ImageBuffer`. Also, the implementation of -/// `AsMut<[P::Subpixel]>` must always yield the same buffer. Therefore there is no public way to +/// `AsMut<[P::Component]>` must always yield the same buffer. Therefore there is no public way to /// construct this with an owning buffer. /// /// # Inner invariants @@ -1008,7 +1008,7 @@ where #[derive(Clone, Debug)] pub struct ViewMut where - Buffer: AsMut<[P::Subpixel]>, + Buffer: AsMut<[P::Component]>, { inner: FlatSamples, phantom: PhantomData

, @@ -1018,7 +1018,7 @@ where /// /// The biggest use case being `ImageBuffer` which expects closely packed /// samples in a row major matrix representation. But this error type may be -/// resused for other import functions. A more versatile user may also try to +/// re-used for other import functions. A more versatile user may also try to /// correct the underlying representation depending on the error variant. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Error { @@ -1087,7 +1087,7 @@ pub enum NormalForm { impl View where - Buffer: AsRef<[P::Subpixel]>, + Buffer: AsRef<[P::Component]>, { /// Take out the sample buffer. /// @@ -1118,7 +1118,7 @@ where /// /// This method will return `None` when the sample is out-of-bounds. All errors that could /// occur due to overflow have been eliminated while construction the `View`. - pub fn get_sample(&self, channel: u8, x: u32, y: u32) -> Option<&P::Subpixel> { + pub fn get_sample(&self, channel: u8, x: u32, y: u32) -> Option<&P::Component> { if !self.inner.in_bounds(channel, x, y) { return None; } @@ -1136,9 +1136,9 @@ where /// /// **WARNING**: Note that of course samples may alias, so that the mutable reference returned /// here can in fact modify more than the coordinate in the argument. - pub fn get_mut_sample(&mut self, channel: u8, x: u32, y: u32) -> Option<&mut P::Subpixel> + pub fn get_mut_sample(&mut self, channel: u8, x: u32, y: u32) -> Option<&mut P::Component> where - Buffer: AsMut<[P::Subpixel]>, + Buffer: AsMut<[P::Component]>, { if !self.inner.in_bounds(channel, x, y) { return None; @@ -1160,7 +1160,7 @@ where /// /// While this can not fail–the validity of all coordinates has been validated during the /// conversion from `FlatSamples`–the resulting slice may still contain holes. - pub fn image_slice(&self) -> &[P::Subpixel] { + pub fn image_slice(&self) -> &[P::Component] { &self.samples().as_ref()[..self.min_length()] } @@ -1169,9 +1169,9 @@ where /// This is relevant only when constructed with `FlatSamples::as_view_with_mut_samples`. While /// this can not fail–the validity of all coordinates has been validated during the conversion /// from `FlatSamples`–the resulting slice may still contain holes. - pub fn image_mut_slice(&mut self) -> &mut [P::Subpixel] + pub fn image_mut_slice(&mut self) -> &mut [P::Component] where - Buffer: AsMut<[P::Subpixel]>, + Buffer: AsMut<[P::Component]>, { let min_length = self.min_length(); &mut self.inner.samples.as_mut()[..min_length] @@ -1196,7 +1196,7 @@ where /// /// ``` /// # use image::RgbImage; - /// # use image::Rgb; + /// # use pixeli::Rgb; /// let mut buffer = RgbImage::new(480, 640).into_flat_samples(); /// let view = buffer.as_view_with_mut_samples::>().unwrap(); /// @@ -1207,7 +1207,7 @@ where /// ``` pub fn try_upgrade(self) -> Result, (Error, Self)> where - Buffer: AsMut<[P::Subpixel]>, + Buffer: AsMut<[P::Component]>, { if !self.inner.is_normal(NormalForm::PixelPacked) { return Err((Error::NormalFormRequired(NormalForm::PixelPacked), self)); @@ -1223,7 +1223,7 @@ where impl ViewMut where - Buffer: AsMut<[P::Subpixel]>, + Buffer: AsMut<[P::Component]>, { /// Take out the sample buffer. /// @@ -1262,9 +1262,9 @@ where /// /// This method will return `None` when the sample is out-of-bounds. All errors that could /// occur due to overflow have been eliminated while construction the `View`. - pub fn get_sample(&self, channel: u8, x: u32, y: u32) -> Option<&P::Subpixel> + pub fn get_sample(&self, channel: u8, x: u32, y: u32) -> Option<&P::Component> where - Buffer: AsRef<[P::Subpixel]>, + Buffer: AsRef<[P::Component]>, { if !self.inner.in_bounds(channel, x, y) { return None; @@ -1279,7 +1279,7 @@ where /// /// This method will return `None` when the sample is out-of-bounds. All errors that could /// occur due to overflow have been eliminated while construction the `View`. - pub fn get_mut_sample(&mut self, channel: u8, x: u32, y: u32) -> Option<&mut P::Subpixel> { + pub fn get_mut_sample(&mut self, channel: u8, x: u32, y: u32) -> Option<&mut P::Component> { if !self.inner.in_bounds(channel, x, y) { return None; } @@ -1293,15 +1293,15 @@ where /// /// While this can not fail–the validity of all coordinates has been validated during the /// conversion from `FlatSamples`–the resulting slice may still contain holes. - pub fn image_slice(&self) -> &[P::Subpixel] + pub fn image_slice(&self) -> &[P::Component] where - Buffer: AsRef<[P::Subpixel]>, + Buffer: AsRef<[P::Component]>, { &self.inner.samples.as_ref()[..self.min_length()] } /// Return the mutable buffer that holds sample values. - pub fn image_mut_slice(&mut self) -> &mut [P::Subpixel] { + pub fn image_mut_slice(&mut self) -> &mut [P::Component] { let length = self.min_length(); &mut self.inner.samples.as_mut()[..length] } @@ -1380,9 +1380,10 @@ where } } -impl GenericImageView for View +impl GenericImageView for View where - Buffer: AsRef<[P::Subpixel]>, + P: ContiguousPixel, + Buffer: AsRef<[P::Component]>, { type Pixel = P; @@ -1397,7 +1398,7 @@ where let image = self.inner.samples.as_ref(); let base_index = self.inner.in_bounds_index(0, x, y); - let channels = P::CHANNEL_COUNT as usize; + let channels = P::COMPONENT_COUNT as usize; let mut buffer = [Zero::zero(); 256]; buffer @@ -1409,13 +1410,14 @@ where *to = image[index]; }); - *P::from_slice(&buffer[..channels]) + *P::from_component_slice_ref(&buffer[..channels]) } } -impl GenericImageView for ViewMut +impl GenericImageView for ViewMut where - Buffer: AsMut<[P::Subpixel]> + AsRef<[P::Subpixel]>, + P: ContiguousPixel, + Buffer: AsMut<[P::Component]> + AsRef<[P::Component]>, { type Pixel = P; @@ -1430,7 +1432,7 @@ where let image = self.inner.samples.as_ref(); let base_index = self.inner.in_bounds_index(0, x, y); - let channels = P::CHANNEL_COUNT as usize; + let channels = P::COMPONENT_COUNT as usize; let mut buffer = [Zero::zero(); 256]; buffer @@ -1442,13 +1444,14 @@ where *to = image[index]; }); - *P::from_slice(&buffer[..channels]) + *P::from_component_slice_ref(&buffer[..channels]) } } -impl GenericImage for ViewMut +impl GenericImage for ViewMut where - Buffer: AsMut<[P::Subpixel]> + AsRef<[P::Subpixel]>, + P: ContiguousPixel + Blend, + Buffer: AsMut<[P::Component]> + AsRef<[P::Component]>, { fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel { if !self.inner.in_bounds(0, x, y) { @@ -1456,9 +1459,9 @@ where } let base_index = self.inner.in_bounds_index(0, x, y); - let channel_count =

::CHANNEL_COUNT as usize; + let channel_count =

::COMPONENT_COUNT as usize; let pixel_range = base_index..base_index + channel_count; - P::from_slice_mut(&mut self.inner.samples.as_mut()[pixel_range]) + P::from_component_slice_mut(&mut self.inner.samples.as_mut()[pixel_range]) } #[allow(deprecated)] @@ -1576,9 +1579,10 @@ impl PartialOrd for NormalForm { #[cfg(test)] mod tests { + use pixeli::{GrayAlpha, Rgb}; + use super::*; use crate::buffer_::GrayAlphaImage; - use crate::color::{LumaA, Rgb}; #[test] fn aliasing_view() { @@ -1598,7 +1602,16 @@ mod tests { let view = buffer.as_view::>().expect("This is a valid view"); let pixel_count = view .pixels() - .inspect(|pixel| assert!(pixel.2 == Rgb([42, 42, 42]))) + .inspect(|pixel| { + assert!( + pixel.2 + == Rgb { + r: 42, + g: 42, + b: 42 + } + ) + }) .count(); assert_eq!(pixel_count, 100 * 100); } @@ -1620,12 +1633,15 @@ mod tests { { let mut view = buffer - .as_view_mut::>() + .as_view_mut::>() .expect("This should be a valid mutable buffer"); assert_eq!(view.dimensions(), (3, 3)); #[allow(deprecated)] for i in 0..9 { - *view.get_pixel_mut(i % 3, i / 3) = LumaA([2 * i as u16, 2 * i as u16 + 1]); + *view.get_pixel_mut(i % 3, i / 3) = GrayAlpha { + gray: 2 * i as u16, + a: 2 * i as u16 + 1, + }; } } diff --git a/src/image.rs b/src/image.rs index b8cf0d71b5..6665ef240e 100644 --- a/src/image.rs +++ b/src/image.rs @@ -4,13 +4,14 @@ use std::io::{self, Write}; use std::ops::{Deref, DerefMut}; use std::path::Path; +use pixeli::{ContiguousPixel, Pixel, PixelComponent}; + use crate::color::{ColorType, ExtendedColorType}; use crate::error::{ ImageError, ImageFormatHint, ImageResult, LimitError, LimitErrorKind, ParameterError, ParameterErrorKind, }; use crate::math::Rect; -use crate::traits::Pixel; use crate::ImageBuffer; use crate::animation::Frames; @@ -588,7 +589,7 @@ where /// Panics if there isn't enough memory to decode the image. pub(crate) fn decoder_to_vec(decoder: impl ImageDecoder) -> ImageResult> where - T: crate::traits::Primitive + bytemuck::Pod, + T: PixelComponent + bytemuck::Pod, { let total_bytes = usize::try_from(decoder.total_bytes()); if total_bytes.is_err() || total_bytes.unwrap() > isize::MAX as usize { @@ -813,14 +814,15 @@ impl Clone for Pixels<'_, I> { /// Trait to inspect an image. /// /// ``` -/// use image::{GenericImageView, Rgb, RgbImage}; +/// use image::{GenericImageView, RgbImage}; +/// use pixeli::Rgb; /// /// let buffer = RgbImage::new(10, 10); /// let image: &dyn GenericImageView> = &buffer; /// ``` pub trait GenericImageView { /// The type of pixel. - type Pixel: Pixel; + type Pixel: ContiguousPixel; /// The width and height of this image. fn dimensions(&self) -> (u32, u32); @@ -1082,8 +1084,8 @@ pub struct SubImageInner { /// Alias to access Pixel behind a reference type DerefPixel = <::Target as GenericImageView>::Pixel; -/// Alias to access Subpixel behind a reference -type DerefSubpixel = as Pixel>::Subpixel; +/// Alias to access Component behind a reference +type DerefComponent = as Pixel>::Component; impl SubImage { /// Construct a new subimage @@ -1114,7 +1116,7 @@ impl SubImage { } /// Convert this subimage to an ImageBuffer - pub fn to_image(&self) -> ImageBuffer, Vec>> + pub fn to_image(&self) -> ImageBuffer, Vec>> where I: Deref, I::Target: GenericImageView + 'static, @@ -1264,11 +1266,12 @@ mod tests { use std::io; use std::path::Path; + use pixeli::Rgba; + use super::{ load_rect, ColorType, GenericImage, GenericImageView, ImageDecoder, ImageFormat, ImageResult, }; - use crate::color::Rgba; use crate::math::Rect; use crate::{GrayImage, ImageBuffer}; @@ -1277,25 +1280,111 @@ mod tests { /// Test that alpha blending works as expected fn test_image_alpha_blending() { let mut target = ImageBuffer::new(1, 1); - target.put_pixel(0, 0, Rgba([255u8, 0, 0, 255])); - assert!(*target.get_pixel(0, 0) == Rgba([255, 0, 0, 255])); - target.blend_pixel(0, 0, Rgba([0, 255, 0, 255])); - assert!(*target.get_pixel(0, 0) == Rgba([0, 255, 0, 255])); + target.put_pixel( + 0, + 0, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); + assert!( + *target.get_pixel(0, 0) + == Rgba { + r: 255, + g: 0, + b: 0, + a: 255 + } + ); + target.blend_pixel( + 0, + 0, + Rgba { + r: 0, + g: 255, + b: 0, + a: 255, + }, + ); + assert!( + *target.get_pixel(0, 0) + == Rgba { + r: 0, + g: 255, + b: 0, + a: 255 + } + ); // Blending an alpha channel onto a solid background - target.blend_pixel(0, 0, Rgba([255, 0, 0, 127])); - assert!(*target.get_pixel(0, 0) == Rgba([127, 127, 0, 255])); + target.blend_pixel( + 0, + 0, + Rgba { + r: 255, + g: 0, + b: 0, + a: 127, + }, + ); + assert!( + *target.get_pixel(0, 0) + == Rgba { + r: 127, + g: 127, + b: 0, + a: 255 + } + ); // Blending two alpha channels - target.put_pixel(0, 0, Rgba([0, 255, 0, 127])); - target.blend_pixel(0, 0, Rgba([255, 0, 0, 127])); - assert!(*target.get_pixel(0, 0) == Rgba([169, 85, 0, 190])); + target.put_pixel( + 0, + 0, + Rgba { + r: 0, + g: 255, + b: 0, + a: 127, + }, + ); + target.blend_pixel( + 0, + 0, + Rgba { + r: 255, + g: 0, + b: 0, + a: 127, + }, + ); + assert!( + *target.get_pixel(0, 0) + == Rgba { + r: 169, + g: 85, + b: 0, + a: 190 + } + ); } #[test] fn test_in_bounds() { let mut target = ImageBuffer::new(2, 2); - target.put_pixel(0, 0, Rgba([255u8, 0, 0, 255])); + target.put_pixel( + 0, + 0, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); assert!(target.in_bounds(0, 0)); assert!(target.in_bounds(1, 0)); @@ -1310,7 +1399,16 @@ mod tests { #[test] fn test_can_subimage_clone_nonmut() { let mut source = ImageBuffer::new(3, 3); - source.put_pixel(1, 1, Rgba([255u8, 0, 0, 255])); + source.put_pixel( + 1, + 1, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); // A non-mutable copy of the source image let source = source.clone(); @@ -1323,15 +1421,41 @@ mod tests { #[test] fn test_can_nest_views() { - let mut source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let mut source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); { let mut sub1 = source.sub_image(0, 0, 2, 2); let mut sub2 = sub1.sub_image(1, 1, 1, 1); - sub2.put_pixel(0, 0, Rgba([0, 0, 0, 0])); + sub2.put_pixel( + 0, + 0, + Rgba { + r: 0, + g: 0, + b: 0, + a: 0, + }, + ); } - assert_eq!(*source.get_pixel(1, 1), Rgba([0, 0, 0, 0])); + assert_eq!( + *source.get_pixel(1, 1), + Rgba { + r: 0, + g: 0, + b: 0, + a: 0 + } + ); let view1 = source.view(0, 0, 2, 2); assert_eq!(*source.get_pixel(1, 1), view1.get_pixel(1, 1)); @@ -1343,48 +1467,111 @@ mod tests { #[test] #[should_panic] fn test_view_out_of_bounds() { - let source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); source.view(1, 1, 3, 3); } #[test] #[should_panic] fn test_view_coordinates_out_of_bounds() { - let source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); source.view(3, 3, 3, 3); } #[test] #[should_panic] fn test_view_width_out_of_bounds() { - let source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); source.view(1, 1, 3, 2); } #[test] #[should_panic] fn test_view_height_out_of_bounds() { - let source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); source.view(1, 1, 2, 3); } #[test] #[should_panic] fn test_view_x_out_of_bounds() { - let source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); source.view(3, 1, 3, 3); } #[test] #[should_panic] fn test_view_y_out_of_bounds() { - let source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); source.view(1, 3, 3, 3); } #[test] fn test_view_in_bounds() { - let source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); source.view(0, 0, 3, 3); source.view(1, 1, 2, 2); source.view(2, 2, 0, 0); @@ -1392,7 +1579,16 @@ mod tests { #[test] fn test_copy_sub_image() { - let source = ImageBuffer::from_pixel(3, 3, Rgba([255u8, 0, 0, 255])); + let source = ImageBuffer::from_pixel( + 3, + 3, + Rgba { + r: 255u8, + g: 0, + b: 0, + a: 255, + }, + ); let view = source.view(0, 0, 3, 3); let _view2 = view; view.to_image(); diff --git a/src/imageops/affine.rs b/src/imageops/affine.rs index 6e4f14581f..40e95c3de6 100644 --- a/src/imageops/affine.rs +++ b/src/imageops/affine.rs @@ -1,14 +1,15 @@ //! Functions for performing affine transformations. +use pixeli::Pixel; + 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>> +) -> ImageBuffer::Component>> where I::Pixel: 'static, { @@ -21,7 +22,7 @@ where /// Rotate an image 180 degrees clockwise. pub fn rotate180( image: &I, -) -> ImageBuffer::Subpixel>> +) -> ImageBuffer::Component>> where I::Pixel: 'static, { @@ -34,7 +35,7 @@ where /// Rotate an image 270 degrees clockwise. pub fn rotate270( image: &I, -) -> ImageBuffer::Subpixel>> +) -> ImageBuffer::Component>> where I::Pixel: 'static, { @@ -52,7 +53,7 @@ pub fn rotate90_in( where I: GenericImageView, I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, + Container: std::ops::DerefMut::Component]>, { let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); if w0 != h1 || h0 != w1 { @@ -78,7 +79,7 @@ pub fn rotate180_in( where I: GenericImageView, I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, + Container: std::ops::DerefMut::Component]>, { let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); if w0 != w1 || h0 != h1 { @@ -104,7 +105,7 @@ pub fn rotate270_in( where I: GenericImageView, I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, + Container: std::ops::DerefMut::Component]>, { let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); if w0 != h1 || h0 != w1 { @@ -125,7 +126,7 @@ where /// Flip an image horizontally pub fn flip_horizontal( image: &I, -) -> ImageBuffer::Subpixel>> +) -> ImageBuffer::Component>> where I::Pixel: 'static, { @@ -138,7 +139,7 @@ where /// Flip an image vertically pub fn flip_vertical( image: &I, -) -> ImageBuffer::Subpixel>> +) -> ImageBuffer::Component>> where I::Pixel: 'static, { @@ -156,7 +157,7 @@ pub fn flip_horizontal_in( where I: GenericImageView, I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, + Container: std::ops::DerefMut::Component]>, { let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); if w0 != w1 || h0 != h1 { @@ -182,7 +183,7 @@ pub fn flip_vertical_in( where I: GenericImageView, I::Pixel: 'static, - Container: std::ops::DerefMut::Subpixel]>, + Container: std::ops::DerefMut::Component]>, { let ((w0, h0), (w1, h1)) = (image.dimensions(), destination.dimensions()); if w0 != w1 || h0 != h1 { @@ -263,12 +264,13 @@ pub fn flip_vertical_in_place(image: &mut I) { #[cfg(test)] mod test { + use pixeli::Pixel; + 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 { diff --git a/src/imageops/colorops.rs b/src/imageops/colorops.rs index 86d53ecaf5..6ed1ece02b 100644 --- a/src/imageops/colorops.rs +++ b/src/imageops/colorops.rs @@ -1,65 +1,75 @@ //! Functions for altering and converting the color of pixelbufs use num_traits::NumCast; +use pixeli::{ContiguousPixel, FromPixelCommon, Gray, GrayAlpha, Pixel, PixelComponent, Rgba}; use std::f64::consts::PI; -use crate::color::{FromColor, IntoColor, Luma, LumaA}; +use crate::color::Invert; use crate::image::{GenericImage, GenericImageView}; -use crate::traits::{Pixel, Primitive}; use crate::utils::clamp; use crate::ImageBuffer; -type Subpixel = <::Pixel as Pixel>::Subpixel; +type Component = <::Pixel as Pixel>::Component; /// Convert the supplied image to grayscale. Alpha channel is discarded. +#[deprecated(note = "use image::imageops::convert_generic_image() instead")] pub fn grayscale( image: &I, -) -> ImageBuffer>, Vec>> { - grayscale_with_type(image) +) -> ImageBuffer>, Vec>> +where + Gray<<::Pixel as Pixel>::Component>: + FromPixelCommon<::Pixel>, +{ + convert_generic_image(image) } /// Convert the supplied image to grayscale. Alpha channel is preserved. +#[deprecated(note = "use image::imageops::convert_generic_image() instead")] pub fn grayscale_alpha( image: &I, -) -> ImageBuffer>, Vec>> { - grayscale_with_type_alpha(image) +) -> ImageBuffer>, Vec>> +where + GrayAlpha<<::Pixel as Pixel>::Component>: + FromPixelCommon<::Pixel>, +{ + convert_generic_image(image) } /// Convert the supplied image to a grayscale image with the specified pixel type. Alpha channel is discarded. +#[deprecated(note = "use image::imageops::convert_generic_image() instead")] pub fn grayscale_with_type( image: &I, -) -> ImageBuffer> +) -> ImageBuffer> where - NewPixel: Pixel + FromColor>>, + NewPixel: ContiguousPixel + FromPixelCommon<::Pixel>, { - 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_generic_image::(image) } /// Convert the supplied image to a grayscale image with the specified pixel type. Alpha channel is preserved. +#[deprecated(note = "use image::imageops::convert_generic_image() instead")] pub fn grayscale_with_type_alpha( image: &I, -) -> ImageBuffer> +) -> ImageBuffer> +where + NewPixel: ContiguousPixel + FromPixelCommon<::Pixel>, +{ + convert_generic_image::(image) +} + +/// Convert the supplied image to an image with a different pixel type. +pub fn convert_generic_image( + image: &I, +) -> ImageBuffer> where - NewPixel: Pixel + FromColor>>, + I: GenericImageView, + NewPixel: ContiguousPixel + FromPixelCommon, { 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.put_pixel(x, y, NewPixel::from_pixel_common(pixel)); } out @@ -67,7 +77,10 @@ where /// Invert each pixel within the supplied image. /// This function operates in place. -pub fn invert(image: &mut I) { +pub fn invert(image: &mut I) +where + I::Pixel: Invert, +{ // TODO find a way to use pixels? let (width, height) = image.dimensions(); @@ -89,19 +102,19 @@ pub fn invert(image: &mut I) { pub fn contrast(image: &I, contrast: f32) -> ImageBuffer> where I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, + P: Pixel = P> + ContiguousPixel + 'static, + S: PixelComponent + 'static, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, height); - let max = S::DEFAULT_MAX_VALUE; + let max = S::COMPONENT_MAX; 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 f = pixel.map_components(|b| -> S { let c: f32 = NumCast::from(b).unwrap(); let d = ((c / max - 0.5) * percent + 0.5) * max; @@ -123,10 +136,11 @@ where pub fn contrast_in_place(image: &mut I, contrast: f32) where I: GenericImage, + ::Pixel: Pixel::Component> = I::Pixel>, { let (width, height) = image.dimensions(); - let max = ::Subpixel::DEFAULT_MAX_VALUE; + let max = <::Component as PixelComponent>::COMPONENT_MAX; let max: f32 = NumCast::from(max).unwrap(); let percent = ((100.0 + contrast) / 100.0).powi(2); @@ -134,14 +148,16 @@ where // 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 f = image + .get_pixel(x, y) + .map_components(|b| -> ::Component { + let c: f32 = NumCast::from(b).unwrap(); - let d = ((c / max - 0.5) * percent + 0.5) * max; - let e = clamp(d, 0.0, max); + let d = ((c / max - 0.5) * percent + 0.5) * max; + let e = clamp(d, 0.0, max); - NumCast::from(e).unwrap() - }); + NumCast::from(e).unwrap() + }); image.put_pixel(x, y, f); } @@ -156,25 +172,22 @@ where pub fn brighten(image: &I, value: i32) -> ImageBuffer> where I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, + P: Pixel + ContiguousPixel + 'static, + S: PixelComponent + 'static, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, height); - let max = S::DEFAULT_MAX_VALUE; + let max = S::COMPONENT_MAX; 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); + let e = pixel.map_colors(|b| { + let c: i32 = NumCast::from(b).unwrap(); + let d = clamp(c + value, 0, max); - NumCast::from(d).unwrap() - }, - |alpha| alpha, - ); + NumCast::from(d).unwrap() + }); out.put_pixel(x, y, e); } @@ -192,21 +205,18 @@ where { let (width, height) = image.dimensions(); - let max = ::Subpixel::DEFAULT_MAX_VALUE; + let max = ::Component::COMPONENT_MAX; 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); + let e = image.get_pixel(x, y).map_colors(|b| { + let c: i32 = NumCast::from(b).unwrap(); + let d = clamp(c + value, 0, max); - NumCast::from(d).unwrap() - }, - |alpha| alpha, - ); + NumCast::from(d).unwrap() + }); image.put_pixel(x, y, e); } @@ -222,8 +232,10 @@ where pub fn huerotate(image: &I, value: i32) -> ImageBuffer> where I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, + P: Pixel + ContiguousPixel + 'static, + S: PixelComponent + 'static, + Rgba: FromPixelCommon

, + P: FromPixelCommon>, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, height); @@ -249,31 +261,19 @@ where 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(), - ); + let p = Rgba::::from_pixel_common(p); + + let new_r = matrix[0] * p.r + matrix[1] * p.g + matrix[2] * p.b; + let new_g = matrix[3] * p.r + matrix[4] * p.g + matrix[5] * p.b; + let new_b = matrix[6] * p.r + matrix[7] * p.g + matrix[8] * p.b; + + let outpixel = P::from_pixel_common(Rgba { + r: new_r, + g: new_g, + b: new_b, + a: p.a, + }); + *pixel = outpixel; } out @@ -288,6 +288,8 @@ where pub fn huerotate_in_place(image: &mut I, value: i32) where I: GenericImage, + Rgba: FromPixelCommon<::Pixel>, + ::Pixel: FromPixelCommon>, { let (width, height) = image.dimensions(); @@ -313,34 +315,20 @@ where // 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(), - ); + let p = image.get_pixel(x, y); + + let p = Rgba::::from_pixel_common(p); + + let new_r = matrix[0] * p.r + matrix[1] * p.g + matrix[2] * p.b; + let new_g = matrix[3] * p.r + matrix[4] * p.g + matrix[5] * p.b; + let new_b = matrix[6] * p.r + matrix[7] * p.g + matrix[8] * p.b; + + let outpixel = ::Pixel::from_pixel_common(Rgba { + r: new_r, + g: new_g, + b: new_b, + a: p.a, + }); image.put_pixel(x, y, outpixel); } @@ -373,22 +361,23 @@ pub trait ColorMap { /// # Examples /// ``` /// use image::imageops::colorops::{index_colors, BiLevel, ColorMap}; -/// use image::{ImageBuffer, Luma}; +/// use image::ImageBuffer; +/// use pixeli::Gray; /// /// 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() }); +/// let gray = ImageBuffer::from_fn(w, h, |x, y| -> Gray { [(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) +/// cmap.lookup(p.gray 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 { +/// let bw = ImageBuffer::from_fn(w, h, |x, y| -> Gray { /// if x <= (w / 2) { /// [0].into() /// } else { @@ -401,12 +390,11 @@ pub trait ColorMap { pub struct BiLevel; impl ColorMap for BiLevel { - type Color = Luma; + type Color = Gray; #[inline(always)] - fn index_of(&self, color: &Luma) -> usize { - let luma = color.0; - if luma[0] > 127 { + fn index_of(&self, color: &Gray) -> usize { + if color.gray > 127 { 1 } else { 0 @@ -416,8 +404,8 @@ impl ColorMap for BiLevel { #[inline(always)] fn lookup(&self, idx: usize) -> Option { match idx { - 0 => Some([0].into()), - 1 => Some([255].into()), + 0 => Some(Gray { gray: u8::MIN }), + 1 => Some(Gray { gray: u8::MAX }), _ => None, } } @@ -428,20 +416,19 @@ impl ColorMap for BiLevel { } #[inline(always)] - fn map_color(&self, color: &mut Luma) { + fn map_color(&self, color: &mut Gray) { let new_color = 0xFF * self.index_of(color) as u8; - let luma = &mut color.0; - luma[0] = new_color; + color.gray = new_color; } } #[cfg(feature = "color_quant")] impl ColorMap for color_quant::NeuQuant { - type Color = crate::color::Rgba; + type Color = Rgba; #[inline(always)] fn index_of(&self, color: &Self::Color) -> usize { - self.index_of(color.channels()) + self.index_of(color.component_array().as_slice()) } #[inline(always)] @@ -456,19 +443,22 @@ impl ColorMap for color_quant::NeuQuant { #[inline(always)] fn map_color(&self, color: &mut Self::Color) { - self.map_pixel(color.channels_mut()) + self.map_pixel(color.component_array().as_mut_slice()) } } /// 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, - } - } +fn diffuse_err>(pixel: &mut P, error: [i16; 3], factor: i16) { + *pixel = P::from_components( + error + .into_iter() + .zip(pixel.component_array()) + .map(|(e, 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( @@ -477,9 +467,9 @@ macro_rules! do_dithering( 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()) + for ((e, old), new) in $err.iter_mut() + .zip(old_pixel.component_array().into_iter()) + .zip(new_pixel.component_array().into_iter()) { *e = >::from(old) - >::from(new) } @@ -492,7 +482,7 @@ macro_rules! do_dithering( pub fn dither(image: &mut ImageBuffer>, color_map: &Map) where Map: ColorMap + ?Sized, - Pix: Pixel + 'static, + Pix: Pixel + ContiguousPixel + 'static, { let (width, height) = image.dimensions(); let mut err: [i16; 3] = [0; 3]; @@ -530,14 +520,16 @@ where pub fn index_colors( image: &ImageBuffer>, color_map: &Map, -) -> ImageBuffer, Vec> +) -> ImageBuffer, Vec> where Map: ColorMap + ?Sized, - Pix: Pixel + 'static, + Pix: Pixel + ContiguousPixel + '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]) + *idx = Gray { + gray: color_map.index_of(pixel) as u8, + } } indices } @@ -596,7 +588,7 @@ mod test { let expected: GrayImage = ImageBuffer::from_raw(3, 2, vec![0u8, 1u8, 2u8, 10u8, 11u8, 12u8]).unwrap(); - assert_pixels_eq!(&grayscale(&image), &expected); + assert_pixels_eq!(&convert_generic_image::, _>(&image), &expected); } #[test] diff --git a/src/imageops/mod.rs b/src/imageops/mod.rs index 9b296100b0..8de4975269 100644 --- a/src/imageops/mod.rs +++ b/src/imageops/mod.rs @@ -1,8 +1,11 @@ //! Image Processing Functions use std::cmp; +use pixeli::{Pixel, PixelComponent}; + +use crate::color::Blend; use crate::image::{GenericImage, GenericImageView, SubImage}; -use crate::traits::{Lerp, Pixel, Primitive}; +use crate::traits::Lerp; pub use self::sample::FilterType; @@ -22,9 +25,11 @@ pub use self::sample::{ }; /// Color operations +#[allow(deprecated)] pub use self::colorops::{ - brighten, contrast, dither, grayscale, grayscale_alpha, grayscale_with_type, - grayscale_with_type_alpha, huerotate, index_colors, invert, BiLevel, ColorMap, + brighten, contrast, convert_generic_image, dither, grayscale, grayscale_alpha, + grayscale_with_type, grayscale_with_type_alpha, huerotate, index_colors, invert, BiLevel, + ColorMap, }; mod affine; @@ -219,6 +224,7 @@ pub fn overlay(bottom: &mut I, top: &J, x: i64, y: i64) where I: GenericImage, J: GenericImageView, + I::Pixel: Blend, { let bottom_dims = bottom.dimensions(); let top_dims = top.dimensions(); @@ -242,7 +248,7 @@ where /// /// # Examples /// ```no_run -/// use image::{RgbaImage}; +/// use image::RgbaImage; /// /// let mut img = RgbaImage::new(1920, 1080); /// let tile = image::open("tile.png").unwrap(); @@ -254,6 +260,7 @@ pub fn tile(bottom: &mut I, top: &J) where I: GenericImage, J: GenericImageView, + I::Pixel: Blend, { for x in (0..bottom.width()).step_by(top.width() as usize) { for y in (0..bottom.height()).step_by(top.height() as usize) { @@ -268,26 +275,33 @@ where /// /// # Examples /// ```no_run -/// use image::{Rgba, RgbaImage, Pixel}; +/// use image::RgbaImage; +/// use pixeli::{Rgba, 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]); +/// let start = Rgba{r:0, g:128, b:0, a:0}; +/// let end = Rgba{r:255, g:255, b:255, a:255}; /// -/// image::imageops::vertical_gradient(&mut img, start, end); +/// 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, + P: Pixel + 'static, + S: PixelComponent + 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) - }); + let pixel = P::from_components( + start + .component_array() + .into_iter() + .zip(stop.component_array()) + .map(|(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); @@ -301,26 +315,33 @@ where /// /// # Examples /// ```no_run -/// use image::{Rgba, RgbaImage, Pixel}; +/// use image::RgbaImage; +/// use pixeli::{Rgba, 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]); +/// let start = Rgba{r:0, g:128, b:0, a:0}; +/// let end = Rgba{r:255, g:255, b:255, a:255}; /// -/// image::imageops::horizontal_gradient(&mut img, start, end); +/// 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, + P: Pixel + 'static, + S: PixelComponent + 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) - }); + let pixel = P::from_components( + start + .component_array() + .into_iter() + .zip(stop.component_array()) + .map(|(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); @@ -352,8 +373,9 @@ where #[cfg(test)] mod tests { + use pixeli::Rgb; + use super::{overlay, overlay_bounds_ext}; - use crate::color::Rgb; use crate::ImageBuffer; use crate::RgbaImage; @@ -397,24 +419,75 @@ mod tests { /// 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])); + let source = ImageBuffer::from_pixel( + 16, + 16, + Rgb { + r: 255u8, + g: 0, + b: 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])); + assert!( + *target.get_pixel(0, 0) + == Rgb { + r: 255u8, + g: 0, + b: 0 + } + ); + assert!( + *target.get_pixel(15, 0) + == Rgb { + r: 255u8, + g: 0, + b: 0 + } + ); + assert!(*target.get_pixel(16, 0) == Rgb { r: 0u8, g: 0, b: 0 }); + assert!( + *target.get_pixel(0, 15) + == Rgb { + r: 255u8, + g: 0, + b: 0 + } + ); + assert!(*target.get_pixel(0, 16) == Rgb { r: 0u8, g: 0, b: 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])); + let source = ImageBuffer::from_pixel( + 32, + 32, + Rgb { + r: 255u8, + g: 0, + b: 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])); + assert!(*target.get_pixel(0, 0) == Rgb { r: 0, g: 0, b: 0 }); + assert!( + *target.get_pixel(1, 1) + == Rgb { + r: 255u8, + g: 0, + b: 0 + } + ); + assert!( + *target.get_pixel(31, 31) + == Rgb { + r: 255u8, + g: 0, + b: 0 + } + ); } #[test] @@ -422,18 +495,34 @@ mod tests { /// (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])); + let source = ImageBuffer::from_pixel( + 32, + 32, + Rgb { + r: 255u8, + g: 0, + b: 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])); + assert!(*target.get_pixel(0, 0) == Rgb { r: 0, g: 0, b: 0 }); + assert!(*target.get_pixel(1, 1) == Rgb { r: 0, g: 0, b: 0 }); + assert!(*target.get_pixel(31, 31) == Rgb { r: 0, g: 0, b: 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])); + let source = ImageBuffer::from_pixel( + 32, + 32, + Rgb { + r: 255u8, + g: 0, + b: 0, + }, + ); // Overflows to 'sane' coordinates but top is larger than bot. overlay( &mut target, @@ -441,9 +530,9 @@ mod tests { i64::from(u32::MAX - 31), i64::from(u32::MAX - 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])); + assert!(*target.get_pixel(0, 0) == Rgb { r: 0, g: 0, b: 0 }); + assert!(*target.get_pixel(1, 1) == Rgb { r: 0, g: 0, b: 0 }); + assert!(*target.get_pixel(15, 15) == Rgb { r: 0, g: 0, b: 0 }); } use super::{horizontal_gradient, vertical_gradient}; @@ -453,8 +542,16 @@ mod tests { 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]); + let start = Rgb { + r: 0u8, + g: 128, + b: 0, + }; + let end = Rgb { + r: 255u8, + g: 255, + b: 255, + }; horizontal_gradient(&mut img, &start, &end); @@ -467,8 +564,16 @@ mod tests { 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]); + let start = Rgb { + r: 0u8, + g: 128, + b: 0, + }; + let end = Rgb { + r: 255u8, + g: 255, + b: 255, + }; vertical_gradient(&mut img, &start, &end); diff --git a/src/imageops/sample.rs b/src/imageops/sample.rs index d0f18999e8..941410a225 100644 --- a/src/imageops/sample.rs +++ b/src/imageops/sample.rs @@ -5,10 +5,13 @@ use std::f32; -use num_traits::{NumCast, ToPrimitive, Zero}; +use num_traits::Zero; +use pixeli::{ + ContiguousPixel, Enlargeable, FromComponentCommon, FromPixelCommon, Pixel, PixelComponent, Rgba, +}; +use crate::color::Blend; use crate::image::{GenericImage, GenericImageView}; -use crate::traits::{Enlargeable, Pixel, Primitive}; use crate::utils::clamp; use crate::{ImageBuffer, Rgba32FImage}; @@ -105,36 +108,6 @@ pub(crate) struct Filter<'a> { 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; @@ -221,21 +194,18 @@ pub(crate) fn box_kernel(_x: f32) -> f32 { // ```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( +fn horizontal_sample

( image: &Rgba32FImage, new_width: u32, filter: &mut Filter, -) -> ImageBuffer> +) -> ImageBuffer> where - P: Pixel + 'static, - S: Primitive + 'static, + P: ContiguousPixel + FromPixelCommon>, { 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; @@ -275,27 +245,23 @@ where ws.iter_mut().for_each(|w| *w /= sum); for y in 0..height { - let mut t = (0.0, 0.0, 0.0, 0.0); + let mut t = Rgba:: { + r: 0.0, + g: 0.0, + b: 0.0, + a: 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; + t.r += p.r * w; + t.g += p.g * w; + t.b += p.b * w; + t.a += p.a * 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(), - ); + let t = P::from_pixel_common(t); out.put_pixel(outx, y, t); } @@ -305,11 +271,12 @@ where } /// Linearly sample from an image using coordinates in [0, 1]. -pub fn sample_bilinear( - img: &impl GenericImageView, - u: f32, - v: f32, -) -> Option

{ +pub fn sample_bilinear

(img: &impl GenericImageView, u: f32, v: f32) -> Option

+where + P: ContiguousPixel, + f32: FromComponentCommon, + P::Component: FromComponentCommon, +{ if ![u, v].iter().all(|c| (0.0..=1.0).contains(c)) { return None; } @@ -373,13 +340,14 @@ pub fn interpolate_nearest( } /// 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

{ +pub fn interpolate_bilinear

(img: &impl GenericImageView, x: f32, y: f32) -> Option

+where + P: Pixel, + f32: FromComponentCommon, + P::Component: FromComponentCommon, +{ // assumption needed for correctness of pixel creation - assert!(P::CHANNEL_COUNT <= 4); + assert!(P::COMPONENT_COUNT <= 4); let (w, h) = img.dimensions(); if w == 0 || h == 0 { @@ -409,15 +377,15 @@ pub fn interpolate_bilinear( // so just store as many items as necessary, // because there's not a simple way to be generic over all of them. let mut compute = |u: u32, v: u32, i| { - let s = img.get_pixel(u, v); - for (j, c) in s.channels().iter().enumerate() { - sxx[j][i] = c.to_f32().unwrap(); + let p = img.get_pixel(u, v); + for (j, c) in p.component_array().into_iter().enumerate() { + sxx[j][i] = f32::from_component_common(c); } - s + p }; // hacky reuse since cannot construct a generic Pixel - let mut out: P = compute(uf, vf, 0); + let out: P = compute(uf, vf, 0); compute(uf, vc, 1); compute(uc, vf, 2); compute(uc, vc, 3); @@ -438,21 +406,19 @@ pub fn interpolate_bilinear( debug_assert!(f32::abs((wff + wfc + wcf + wcc) - 1.) < 1e-3); // hack to see if primitive is an integer or a float - let is_float = P::Subpixel::DEFAULT_MAX_VALUE.to_f32().unwrap() == 1.0; + let is_float = f32::from_component_common(P::Component::COMPONENT_MAX) == 1.0; - for (i, c) in out.channels_mut().iter_mut().enumerate() { + let out = P::from_components(out.component_array().into_iter().enumerate().map(|(i, _)| { let v = wff * sxx[i][0] + wfc * sxx[i][1] + wcf * sxx[i][2] + wcc * sxx[i][3]; // this rounding may introduce quantization errors, // Specifically what is meant is that many samples may deviate // from the mean value of the originals, but it's not possible to fix that. - *c = ::from(if is_float { v } else { v.round() }).unwrap_or({ - if v < 0.0 { - P::Subpixel::DEFAULT_MIN_VALUE - } else { - P::Subpixel::DEFAULT_MAX_VALUE - } - }); - } + >::from_component_common(if is_float { + v + } else { + v.round() + }) + })); Some(out) } @@ -463,11 +429,11 @@ pub fn interpolate_bilinear( // ```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 +fn vertical_sample(image: &I, new_height: u32, filter: &mut Filter) -> Rgba32FImage where I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, + P: ContiguousPixel, + Rgba: FromPixelCommon

, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, new_height); @@ -504,30 +470,23 @@ where ws.iter_mut().for_each(|w| *w /= sum); for x in 0..width { - let mut t = (0.0, 0.0, 0.0, 0.0); + let mut t = Rgba:: { + r: 0.0, + g: 0.0, + b: 0.0, + a: 0.0, + }; for (i, w) in ws.iter().enumerate() { let p = image.get_pixel(x, left + i as u32); + let p = Rgba::::from_pixel_common(p); - #[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; + t.r += p.r * w; + t.g += p.g * w; + t.b += p.b * w; + t.a += p.a * 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); } } @@ -536,9 +495,13 @@ where } /// Local struct for keeping track of pixel sums for fast thumbnail averaging -struct ThumbnailSum(S::Larger, S::Larger, S::Larger, S::Larger); +struct ThumbnailSum(S::Larger, S::Larger, S::Larger, S::Larger); -impl ThumbnailSum { +impl ThumbnailSum +where + S: Enlargeable, + S::Larger: FromComponentCommon, +{ fn zeroed() -> Self { ThumbnailSum( S::Larger::zero(), @@ -549,16 +512,18 @@ impl ThumbnailSum { } fn sample_val(val: S) -> S::Larger { - ::from(val).unwrap() + S::Larger::from_component_common(val) } - 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); + fn add_pixel

(&mut self, pixel: P) + where + P: Pixel, + { + let mut iter = pixel.component_array().into_iter(); + self.0 += Self::sample_val(iter.next().unwrap()); + self.1 += Self::sample_val(iter.next().unwrap()); + self.2 += Self::sample_val(iter.next().unwrap()); + self.3 += Self::sample_val(iter.next().unwrap()); } } @@ -577,8 +542,13 @@ impl ThumbnailSum { pub fn thumbnail(image: &I, new_width: u32, new_height: u32) -> ImageBuffer> where I: GenericImageView, - P: Pixel + 'static, - S: Primitive + Enlargeable + 'static, + P: Pixel + ContiguousPixel + 'static, + S: PixelComponent + Enlargeable + FromComponentCommon + 'static, + f32: FromComponentCommon, + S::Larger: FromComponentCommon, + S::Larger: FromComponentCommon, + S: FromComponentCommon, + f32: FromComponentCommon, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(new_width, new_height); @@ -603,7 +573,7 @@ where 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 { + let pixel = if bottom != top && left != right { thumbnail_sample_block(image, left, right, bottom, top) } else if bottom != top { // && left == right @@ -638,7 +608,7 @@ where let fraction_horizontal = (topf.fract() + bottomf.fract()) / 2.; let fraction_vertical = (leftf.fract() + rightf.fract()) / 2.; - thumbnail_sample_fraction_both( + thumbnail_sample_fraction_both::<_, _, S>( image, right - 1, fraction_horizontal, @@ -647,8 +617,6 @@ where ) }; - #[allow(deprecated)] - let pixel = Pixel::from_channels(avg.0, avg.1, avg.2, avg.3); out.put_pixel(outx, outy, pixel); } } @@ -657,17 +625,13 @@ where } /// 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) +fn thumbnail_sample_block(image: &I, left: u32, right: u32, bottom: u32, top: u32) -> P where I: GenericImageView, - P: Pixel, - S: Primitive + Enlargeable, + P: Pixel, + S: PixelComponent + Enlargeable, + S::Larger: FromComponentCommon, + S::Larger: FromComponentCommon, { let mut sum = ThumbnailSum::zeroed(); @@ -678,14 +642,14 @@ where } } - let n = ::from((right - left) * (top - bottom)).unwrap(); - let round = ::from(n / NumCast::from(2).unwrap()).unwrap(); - ( + let n = S::Larger::from_component_common((right - left) * (top - bottom)); + let round = n / S::Larger::from_component_common(2); + P::from_components([ 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. @@ -695,11 +659,14 @@ fn thumbnail_sample_fraction_horizontal( fraction_horizontal: f32, bottom: u32, top: u32, -) -> (S, S, S, S) +) -> P where I: GenericImageView, - P: Pixel, - S: Primitive + Enlargeable, + P: Pixel, + S: PixelComponent + Enlargeable, + S: FromComponentCommon, + f32: FromComponentCommon, + S::Larger: FromComponentCommon, { let fract = fraction_horizontal; @@ -718,18 +685,18 @@ where 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(), + S::from_component_common( + fact_left * f32::from_component_common(leftv) + + fact_right * f32::from_component_common(rightv), ) - .expect("Average sample value should fit into sample type") }; - ( + P::from_components([ 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. @@ -739,11 +706,14 @@ fn thumbnail_sample_fraction_vertical( right: u32, bottom: u32, fraction_vertical: f32, -) -> (S, S, S, S) +) -> P where I: GenericImageView, - P: Pixel, - S: Primitive + Enlargeable, + P: Pixel, + S: PixelComponent + Enlargeable, + S: FromComponentCommon, + f32: FromComponentCommon, + S::Larger: FromComponentCommon, { let fract = fraction_vertical; @@ -762,16 +732,18 @@ where 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") + S::from_component_common( + fact_bot * f32::from_component_common(botv) + + fact_top * f32::from_component_common(topv), + ) }; - ( + P::from_components([ 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. @@ -781,20 +753,18 @@ fn thumbnail_sample_fraction_both( fraction_vertical: f32, bottom: u32, fraction_horizontal: f32, -) -> (S, S, S, S) +) -> P where I: GenericImageView, - P: Pixel, - S: Primitive + Enlargeable, + P: Pixel, + S: PixelComponent + Enlargeable, + S: FromComponentCommon, + f32: FromComponentCommon, { - #[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 k_bl = image.get_pixel(left, bottom); + let k_tl = image.get_pixel(left, bottom + 1); + let k_br = image.get_pixel(left + 1, bottom); + let k_tr = image.get_pixel(left + 1, bottom + 1); let frac_v = fraction_vertical; let frac_h = fraction_horizontal; @@ -804,21 +774,23 @@ where let fact_br = (1. - frac_v) * frac_h; let fact_bl = (1. - frac_v) * (1. - frac_h); + let to_f32 = |x| f32::from_component_common(x); 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(), + S::from_component_common( + fact_br * to_f32(br) + + fact_tr * to_f32(tr) + + fact_bl * to_f32(bl) + + fact_tl * to_f32(tl), ) - .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), + P::from_components( + k_br.component_array() + .into_iter() + .zip(k_tr.component_array()) + .zip(k_bl.component_array()) + .zip(k_tl.component_array()) + .map(|(((k_br, k_tr), k_bl), k_tl)| mix(k_br, k_tr, k_bl, k_tl)), ) } @@ -827,8 +799,10 @@ where pub fn filter3x3(image: &I, kernel: &[f32]) -> ImageBuffer> where I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, + P: Pixel + ContiguousPixel + 'static, + S: PixelComponent + 'static, + f32: FromComponentCommon, + P::Component: FromComponentCommon, { // The kernel's input positions relative to the current pixel. let taps: &[(isize, isize)] = &[ @@ -847,56 +821,37 @@ where 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); + 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); + let mut t = vec![0.0; usize::from(P::COMPONENT_COUNT)]; // 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; + for (t, c) in t.iter_mut().zip(p.component_array()) { + *t += k * f32::from_component_common(c) + } } - 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(), + let outpixel = P::from_components( + t.into_iter() + .zip(sum) + .map(|(t, sum)| P::Component::from_component_common(t / sum)), ); - out.put_pixel(x, y, t); + out.put_pixel(x, y, outpixel); } } @@ -911,10 +866,12 @@ pub fn resize( nwidth: u32, nheight: u32, filter: FilterType, -) -> ImageBuffer::Subpixel>> +) -> ImageBuffer::Component>> where I::Pixel: 'static, - ::Subpixel: 'static, + ::Component: 'static, + Rgba: FromPixelCommon, + I::Pixel: FromPixelCommon> + Blend, { // 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() { @@ -956,9 +913,11 @@ where pub fn blur( image: &I, sigma: f32, -) -> ImageBuffer::Subpixel>> +) -> ImageBuffer::Component>> where I::Pixel: 'static, + Rgba: FromPixelCommon, + I::Pixel: FromPixelCommon>, { let sigma = if sigma <= 0.0 { 1.0 } else { sigma }; @@ -984,13 +943,17 @@ where pub fn unsharpen(image: &I, sigma: f32, threshold: i32) -> ImageBuffer> where I: GenericImageView, - P: Pixel + 'static, - S: Primitive + 'static, + P: Pixel + ContiguousPixel + 'static, + S: PixelComponent + 'static, + Rgba: FromPixelCommon, + I::Pixel: FromPixelCommon>, + i32: FromComponentCommon, + P::Component: FromComponentCommon, { let mut tmp = blur(image, sigma); - let max = S::DEFAULT_MAX_VALUE; - let max: i32 = NumCast::from(max).unwrap(); + let max = S::COMPONENT_MAX; + let max: i32 = i32::from_component_common(max); let (width, height) = image.dimensions(); for y in 0..height { @@ -998,22 +961,26 @@ where 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 new_components = a + .component_array() + .into_iter() + .zip(b.component_array()) + .map(|(a, b)| { + let ia: i32 = i32::from_component_common(a); + let ib: i32 = i32::from_component_common(b); - let diff = ic - id; + let diff = ia - ib; - if diff.abs() > threshold { - let e = clamp(ic + diff, 0, max); // FIXME what does this do for f32? clamp 0-1 integers?? + if diff.abs() > threshold { + let e = clamp(ia + diff, 0, max); // FIXME what does this do for f32? clamp 0-1 integers?? - NumCast::from(e).unwrap() - } else { - c - } - }); + P::Component::from_component_common(e) + } else { + a + } + }); - *b = p; + *b = P::from_components(new_components); } } @@ -1024,6 +991,7 @@ where mod tests { use super::{resize, sample_bilinear, sample_nearest, FilterType}; use crate::{GenericImageView, ImageBuffer, RgbImage}; + use pixeli::{Pixel, Rgba}; #[cfg(feature = "benchmarks")] use test; @@ -1087,46 +1055,141 @@ mod tests { } #[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]), + (0, 0) => Rgba { + r: 255_u8, + g: 0, + b: 0, + a: 0, + }, + (0, 1) => Rgba { + r: 0, + g: 255, + b: 0, + a: 0, + }, + (1, 0) => Rgba { + r: 0, + g: 0, + b: 255, + a: 0, + }, + (1, 1) => Rgba { + r: 0, + g: 0, + b: 0, + a: 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.5), + Some(Rgba::from_components([64; 4])) + ); + assert_eq!( + sample_bilinear(&img, 0.0, 0.0), + Some(Rgba { + r: 255, + g: 0, + b: 0, + a: 0 + }) + ); + assert_eq!( + sample_bilinear(&img, 0.0, 1.0), + Some(Rgba { + r: 0, + g: 255, + b: 0, + a: 0 + }) + ); + assert_eq!( + sample_bilinear(&img, 1.0, 0.0), + Some(Rgba { + r: 0, + g: 0, + b: 255, + a: 0 + }) + ); + assert_eq!( + sample_bilinear(&img, 1.0, 1.0), + Some(Rgba { + r: 0, + g: 0, + b: 0, + a: 255 + }) + ); assert_eq!( sample_bilinear(&img, 0.5, 0.0), - Some(Rgba([128, 0, 128, 0])) + Some(Rgba { + r: 128, + g: 0, + b: 128, + a: 0 + }) ); assert_eq!( sample_bilinear(&img, 0.0, 0.5), - Some(Rgba([128, 128, 0, 0])) + Some(Rgba { + r: 128, + g: 128, + b: 0, + a: 0 + }) ); assert_eq!( sample_bilinear(&img, 0.5, 1.0), - Some(Rgba([0, 128, 0, 128])) + Some(Rgba { + r: 0, + g: 128, + b: 0, + a: 128 + }) ); assert_eq!( sample_bilinear(&img, 1.0, 0.5), - Some(Rgba([0, 0, 128, 128])) + Some(Rgba { + r: 0, + g: 0, + b: 128, + a: 128 + }) ); } #[bench] #[cfg(feature = "benchmarks")] fn bench_sample_bilinear(b: &mut test::Bencher) { - use crate::Rgba; + use pixeli::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]), + (0, 0) => Rgba { + r: 255, + g: 0, + b: 0, + a: 0, + }, + (0, 1) => Rgba { + r: 0, + g: 255, + b: 0, + a: 0, + }, + (1, 0) => Rgba { + r: 0, + g: 0, + b: 255, + a: 0, + }, + (1, 1) => Rgba { + r: 0, + g: 0, + b: 0, + a: 255, + }, _ => panic!(), }); b.iter(|| { @@ -1135,25 +1198,116 @@ mod tests { } #[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]), + (0, 0) => Rgba { + r: 255, + g: 0, + b: 0, + a: 0, + }, + (0, 1) => Rgba { + r: 0, + g: 255, + b: 0, + a: 0, + }, + (1, 0) => Rgba { + r: 0, + g: 0, + b: 255, + a: 0, + }, + (1, 1) => Rgba { + r: 0, + g: 0, + b: 0, + a: 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.0, 0.0), + Some(Rgba { + r: 255, + g: 0, + b: 0, + a: 0 + }) + ); + assert_eq!( + sample_nearest(&img, 0.0, 1.0), + Some(Rgba { + r: 0, + g: 255, + b: 0, + a: 0 + }) + ); + assert_eq!( + sample_nearest(&img, 1.0, 0.0), + Some(Rgba { + r: 0, + g: 0, + b: 255, + a: 0 + }) + ); + assert_eq!( + sample_nearest(&img, 1.0, 1.0), + Some(Rgba { + r: 0, + g: 0, + b: 0, + a: 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]))); + assert_eq!( + sample_nearest(&img, 0.5, 0.5), + Some(Rgba { + r: 0, + g: 0, + b: 0, + a: 255 + }) + ); + assert_eq!( + sample_nearest(&img, 0.5, 0.0), + Some(Rgba { + r: 0, + g: 0, + b: 255, + a: 0 + }) + ); + assert_eq!( + sample_nearest(&img, 0.0, 0.5), + Some(Rgba { + r: 0, + g: 255, + b: 0, + a: 0 + }) + ); + assert_eq!( + sample_nearest(&img, 0.5, 1.0), + Some(Rgba { + r: 0, + g: 0, + b: 0, + a: 255 + }) + ); + assert_eq!( + sample_nearest(&img, 1.0, 0.5), + Some(Rgba { + r: 0, + g: 0, + b: 0, + a: 255 + }) + ); } #[bench] @@ -1229,11 +1383,10 @@ mod tests { 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, + pixel.a != 254 && pixel.a != 253, "alpha value: {}, {:?}", - alpha, + pixel.a, filter ); } diff --git a/src/lib.rs b/src/lib.rs index 6a9293f3c3..b0e8badb4e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -126,9 +126,9 @@ extern crate test; #[macro_use] extern crate quickcheck; -pub use crate::color::{ColorType, ExtendedColorType}; +pub use crate::color::{Blend, ColorType, ExtendedColorType, Invert}; -pub use crate::color::{Luma, LumaA, Rgb, Rgba}; +pub use pixeli; pub use crate::error::{ImageError, ImageResult}; @@ -146,6 +146,8 @@ pub use crate::image::{ }; pub use crate::buffer_::{ + Gray32FImage, + GrayAlpha32FImage, GrayAlphaImage, GrayImage, // Image types @@ -159,7 +161,7 @@ pub use crate::buffer_::{ pub use crate::flat::FlatSamples; // Traits -pub use crate::traits::{EncodableLayout, Pixel, PixelWithColorType, Primitive}; +pub use crate::traits::{EncodableLayout, PixelWithColorType}; // Opening and loading images pub use crate::dynimage::{ diff --git a/src/traits.rs b/src/traits.rs index a993a3350c..d71d8bb4bd 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -2,17 +2,16 @@ // Note copied from the stdlib under MIT license -use num_traits::{Bounded, Num, NumCast}; -use std::ops::AddAssign; +use num_traits::{Bounded, NumCast}; +use pixeli::{Gray, GrayAlpha, Pixel, PixelComponent, Rgb, Rgba}; -use crate::{ - color::{Luma, LumaA, Rgb, Rgba}, - ExtendedColorType, -}; +use crate::ExtendedColorType; + +use self::sealed::Sealed; /// Types which are safe to treat as an immutable byte slice in a pixel layout /// for image encoding. -pub trait EncodableLayout: seals::EncodableLayout { +pub trait EncodableLayout: Sealed { /// Get the bytes of this value. fn as_bytes(&self) -> &[u8]; } @@ -35,103 +34,9 @@ impl EncodableLayout for [f32] { } } -/// The type of each channel in a pixel. For example, this can be `u8`, `u16`, `f32`. -// TODO rename to `PixelComponent`? Split up into separate traits? Seal? -pub trait Primitive: Copy + NumCast + Num + PartialOrd + Clone + Bounded { - /// The maximum value for this type of primitive within the context of color. - /// For floats, the maximum is `1.0`, whereas the integer types inherit their usual maximum values. - const DEFAULT_MAX_VALUE: Self; - - /// The minimum value for this type of primitive within the context of color. - /// For floats, the minimum is `0.0`, whereas the integer types inherit their usual minimum values. - const DEFAULT_MIN_VALUE: Self; -} - -macro_rules! declare_primitive { - ($base:ty: ($from:expr)..$to:expr) => { - impl Primitive for $base { - const DEFAULT_MAX_VALUE: Self = $to; - const DEFAULT_MIN_VALUE: Self = $from; - } - }; -} - -declare_primitive!(usize: (0)..Self::MAX); -declare_primitive!(u8: (0)..Self::MAX); -declare_primitive!(u16: (0)..Self::MAX); -declare_primitive!(u32: (0)..Self::MAX); -declare_primitive!(u64: (0)..Self::MAX); - -declare_primitive!(isize: (Self::MIN)..Self::MAX); -declare_primitive!(i8: (Self::MIN)..Self::MAX); -declare_primitive!(i16: (Self::MIN)..Self::MAX); -declare_primitive!(i32: (Self::MIN)..Self::MAX); -declare_primitive!(i64: (Self::MIN)..Self::MAX); -declare_primitive!(f32: (0.0)..1.0); -declare_primitive!(f64: (0.0)..1.0); - -/// An Enlargable::Larger value should be enough to calculate -/// the sum (average) of a few hundred or thousand Enlargeable values. -pub trait Enlargeable: Sized + Bounded + NumCast { - type Larger: Copy + NumCast + Num + PartialOrd + Clone + Bounded + AddAssign; - - fn clamp_from(n: Self::Larger) -> Self { - if n > Self::max_value().to_larger() { - Self::max_value() - } else if n < Self::min_value().to_larger() { - Self::min_value() - } else { - NumCast::from(n).unwrap() - } - } - - fn to_larger(self) -> Self::Larger { - NumCast::from(self).unwrap() - } -} - -impl Enlargeable for u8 { - type Larger = u32; -} -impl Enlargeable for u16 { - type Larger = u32; -} -impl Enlargeable for u32 { - type Larger = u64; -} -impl Enlargeable for u64 { - type Larger = u128; -} -impl Enlargeable for usize { - // Note: On 32-bit architectures, u64 should be enough here. - type Larger = u128; -} -impl Enlargeable for i8 { - type Larger = i32; -} -impl Enlargeable for i16 { - type Larger = i32; -} -impl Enlargeable for i32 { - type Larger = i64; -} -impl Enlargeable for i64 { - type Larger = i128; -} -impl Enlargeable for isize { - // Note: On 32-bit architectures, i64 should be enough here. - type Larger = i128; -} -impl Enlargeable for f32 { - type Larger = f64; -} -impl Enlargeable for f64 { - type Larger = f64; -} - /// Linear interpolation without involving floating numbers. pub trait Lerp: Bounded + NumCast { - type Ratio: Primitive; + type Ratio: PixelComponent; fn lerp(a: Self, b: Self, ratio: Self::Ratio) -> Self { let a = ::from(a).unwrap(); @@ -171,7 +76,7 @@ impl Lerp for f32 { /// The pixel with an associated `ColorType`. /// Not all possible pixels represent one of the predefined `ColorType`s. -pub trait PixelWithColorType: Pixel + private::SealedPixelWithColorType { +pub trait PixelWithColorType: Pixel + Sealed { /// This pixel has the format of one of the predefined `ColorType`s, /// such as `Rgb8`, `La16` or `Rgba32F`. /// This is needed for automatically detecting @@ -199,175 +104,49 @@ impl PixelWithColorType for Rgba { const COLOR_TYPE: ExtendedColorType = ExtendedColorType::Rgba32F; } -impl PixelWithColorType for Luma { +impl PixelWithColorType for Gray { const COLOR_TYPE: ExtendedColorType = ExtendedColorType::L8; } -impl PixelWithColorType for Luma { +impl PixelWithColorType for Gray { const COLOR_TYPE: ExtendedColorType = ExtendedColorType::L16; } -impl PixelWithColorType for LumaA { +impl PixelWithColorType for Gray { + const COLOR_TYPE: ExtendedColorType = ExtendedColorType::Gray32F; +} + +impl PixelWithColorType for GrayAlpha { const COLOR_TYPE: ExtendedColorType = ExtendedColorType::La8; } -impl PixelWithColorType for LumaA { +impl PixelWithColorType for GrayAlpha { const COLOR_TYPE: ExtendedColorType = ExtendedColorType::La16; } - -/// Prevents down-stream users from implementing the `Primitive` trait -mod private { - use crate::color::*; - - pub trait SealedPixelWithColorType {} - impl SealedPixelWithColorType for Rgb {} - impl SealedPixelWithColorType for Rgb {} - impl SealedPixelWithColorType for Rgb {} - - impl SealedPixelWithColorType for Rgba {} - impl SealedPixelWithColorType for Rgba {} - impl SealedPixelWithColorType for Rgba {} - - impl SealedPixelWithColorType for Luma {} - impl SealedPixelWithColorType for LumaA {} - - impl SealedPixelWithColorType for Luma {} - impl SealedPixelWithColorType for LumaA {} +impl PixelWithColorType for GrayAlpha { + const COLOR_TYPE: ExtendedColorType = ExtendedColorType::GrayAlpha32F; } -/// A generalized pixel. -/// -/// A pixel object is usually not used standalone but as a view into an image buffer. -pub trait Pixel: Copy + Clone { - /// The scalar type that is used to store each channel in this pixel. - type Subpixel: Primitive; - - /// The number of channels of this pixel type. - const CHANNEL_COUNT: u8; - - /// Returns the components as a slice. - fn channels(&self) -> &[Self::Subpixel]; - - /// Returns the components as a mutable slice - fn channels_mut(&mut self) -> &mut [Self::Subpixel]; - - /// A string that can help to interpret the meaning each channel - /// See [gimp babl](http://gegl.org/babl/). - const COLOR_MODEL: &'static str; - - /// Returns the channels of this pixel as a 4 tuple. If the pixel - /// has less than 4 channels the remainder is filled with the maximum value - #[deprecated(since = "0.24.0", note = "Use `channels()` or `channels_mut()`")] - fn channels4( - &self, - ) -> ( - Self::Subpixel, - Self::Subpixel, - Self::Subpixel, - Self::Subpixel, - ); - - /// Construct a pixel from the 4 channels a, b, c and d. - /// If the pixel does not contain 4 channels the extra are ignored. - #[deprecated( - since = "0.24.0", - note = "Use the constructor of the pixel, for example `Rgba([r,g,b,a])` or `Pixel::from_slice`" - )] - fn from_channels( - a: Self::Subpixel, - b: Self::Subpixel, - c: Self::Subpixel, - d: Self::Subpixel, - ) -> Self; - - /// Returns a view into a slice. - /// - /// Note: The slice length is not checked on creation. Thus the caller has to ensure - /// that the slice is long enough to prevent panics if the pixel is used later on. - fn from_slice(slice: &[Self::Subpixel]) -> &Self; - - /// Returns mutable view into a mutable slice. - /// - /// Note: The slice length is not checked on creation. Thus the caller has to ensure - /// that the slice is long enough to prevent panics if the pixel is used later on. - fn from_slice_mut(slice: &mut [Self::Subpixel]) -> &mut Self; - - /// Convert this pixel to RGB - fn to_rgb(&self) -> Rgb; - - /// Convert this pixel to RGB with an alpha channel - fn to_rgba(&self) -> Rgba; - - /// Convert this pixel to luma - fn to_luma(&self) -> Luma; - - /// Convert this pixel to luma with an alpha channel - fn to_luma_alpha(&self) -> LumaA; - - /// Apply the function ```f``` to each channel of this pixel. - fn map(&self, f: F) -> Self - where - F: FnMut(Self::Subpixel) -> Self::Subpixel; - - /// Apply the function ```f``` to each channel of this pixel. - fn apply(&mut self, f: F) - where - F: FnMut(Self::Subpixel) -> Self::Subpixel; - - /// Apply the function ```f``` to each channel except the alpha channel. - /// Apply the function ```g``` to the alpha channel. - fn map_with_alpha(&self, f: F, g: G) -> Self - where - F: FnMut(Self::Subpixel) -> Self::Subpixel, - G: FnMut(Self::Subpixel) -> Self::Subpixel; - - /// Apply the function ```f``` to each channel except the alpha channel. - /// Apply the function ```g``` to the alpha channel. Works in-place. - fn apply_with_alpha(&mut self, f: F, g: G) - where - F: FnMut(Self::Subpixel) -> Self::Subpixel, - G: FnMut(Self::Subpixel) -> Self::Subpixel; - - /// Apply the function ```f``` to each channel except the alpha channel. - fn map_without_alpha(&self, f: F) -> Self - where - F: FnMut(Self::Subpixel) -> Self::Subpixel, - { - let mut this = *self; - this.apply_with_alpha(f, |x| x); - this - } - - /// Apply the function ```f``` to each channel except the alpha channel. - /// Works in place. - fn apply_without_alpha(&mut self, f: F) - where - F: FnMut(Self::Subpixel) -> Self::Subpixel, - { - self.apply_with_alpha(f, |x| x); - } +/// Private module for supertraits of sealed traits. +mod sealed { + use super::*; - /// Apply the function ```f``` to each channel of this pixel and - /// ```other``` pairwise. - fn map2(&self, other: &Self, f: F) -> Self - where - F: FnMut(Self::Subpixel, Self::Subpixel) -> Self::Subpixel; + pub trait Sealed {} - /// Apply the function ```f``` to each channel of this pixel and - /// ```other``` pairwise. Works in-place. - fn apply2(&mut self, other: &Self, f: F) - where - F: FnMut(Self::Subpixel, Self::Subpixel) -> Self::Subpixel; + impl Sealed for Rgb {} + impl Sealed for Rgb {} + impl Sealed for Rgb {} - /// Invert this pixel - fn invert(&mut self); + impl Sealed for Rgba {} + impl Sealed for Rgba {} + impl Sealed for Rgba {} - /// Blend the color of a given pixel into ourself, taking into account alpha channels - fn blend(&mut self, other: &Self); -} + impl Sealed for Gray {} + impl Sealed for Gray {} + impl Sealed for Gray {} -/// Private module for supertraits of sealed traits. -mod seals { - pub trait EncodableLayout {} + impl Sealed for GrayAlpha {} + impl Sealed for GrayAlpha {} + impl Sealed for GrayAlpha {} - impl EncodableLayout for [u8] {} - impl EncodableLayout for [u16] {} - impl EncodableLayout for [f32] {} + impl Sealed for [u8] {} + impl Sealed for [u16] {} + impl Sealed for [f32] {} } diff --git a/tests/conversions.rs b/tests/conversions.rs index cd09f7c834..317c0a0101 100644 --- a/tests/conversions.rs +++ b/tests/conversions.rs @@ -1,15 +1,31 @@ use image::buffer::ConvertBuffer; -use image::{ImageBuffer, Rgb, Rgba}; +use image::ImageBuffer; +use pixeli::{Rgb, Rgba}; #[test] fn test_rgbu8_to_rgbu16() { // Create an all white image using Rgbs for pixel values - let image_u16 = - ImageBuffer::from_pixel(2, 2, image::Rgb::([u16::MAX, u16::MAX, u16::MAX])); + let image_u16 = ImageBuffer::from_pixel( + 2, + 2, + Rgb:: { + r: u16::MAX, + g: u16::MAX, + b: u16::MAX, + }, + ); // Create an all white image using Rgbs for pixel values and convert it // to Rgbs. - let image_u8 = ImageBuffer::from_pixel(2, 2, image::Rgb::([u8::MAX, u8::MAX, u8::MAX])); + let image_u8 = ImageBuffer::from_pixel( + 2, + 2, + Rgb:: { + r: u8::MAX, + g: u8::MAX, + b: u8::MAX, + }, + ); let image_converted: ImageBuffer, _> = image_u8.convert(); assert_eq!(image_u16, image_converted); @@ -20,13 +36,23 @@ fn test_rgbau8_to_rgbau16() { let image_u16 = ImageBuffer::from_pixel( 2, 2, - image::Rgba::([u16::MAX, u16::MAX, u16::MAX, u16::MAX]), + Rgba:: { + r: u16::MAX, + g: u16::MAX, + b: u16::MAX, + a: u16::MAX, + }, ); let image_u8 = ImageBuffer::from_pixel( 2, 2, - image::Rgba::([u8::MAX, u8::MAX, u8::MAX, u8::MAX]), + Rgba:: { + r: u8::MAX, + g: u8::MAX, + b: u8::MAX, + a: u8::MAX, + }, ); let image_converted: ImageBuffer, _> = image_u8.convert(); diff --git a/tests/reference_images.rs b/tests/reference_images.rs index 02ef47d1d5..1a3f44a938 100644 --- a/tests/reference_images.rs +++ b/tests/reference_images.rs @@ -275,12 +275,12 @@ fn check_references() { let test_crc_actual = { let mut hasher = Crc32::new(); match test_img { - DynamicImage::ImageLuma8(_) - | DynamicImage::ImageLumaA8(_) + DynamicImage::ImageGray8(_) + | DynamicImage::ImageGrayAlpha8(_) | DynamicImage::ImageRgb8(_) | DynamicImage::ImageRgba8(_) => hasher.update(test_img.as_bytes()), - DynamicImage::ImageLuma16(_) - | DynamicImage::ImageLumaA16(_) + DynamicImage::ImageGray16(_) + | DynamicImage::ImageGrayAlpha16(_) | DynamicImage::ImageRgb16(_) | DynamicImage::ImageRgba16(_) => { for v in test_img.as_bytes().chunks(2) {