Skip to main content

image_ndarray/
traits.rs

1//! Conversions between `image::ImageBuffer` and `ndarray` arrays, and the
2//! normalized float trait used to move between integer and float channel values.
3
4#[cfg(feature = "image")]
5use crate::error::{Error, Result};
6#[cfg(feature = "image")]
7use image::{ImageBuffer, Pixel};
8#[cfg(feature = "image")]
9use ndarray::{Array, Array3, ArrayView3, ArrayViewMut, ArrayViewMut3, Dimension};
10use num_traits::{AsPrimitive, ToPrimitive};
11
12#[cfg(feature = "image")]
13/// Conversion methods for working with ndarrays.
14///
15/// Views and standard-layout ownership conversions reuse the original allocation.
16/// Non-standard layouts are copied into image row order.
17pub trait ImageArray<P: image::Pixel, ImageContainer> {
18    /// Cast the `ImageBuffer` as an `ArrayView3`.
19    ///
20    /// * `Y` index is the row
21    /// * `X` index is the columns
22    /// * `Z` index is the channel
23    ///
24    /// So when referencing:
25    /// `array[[y, x, z]]`
26    ///
27    /// This does not copy the data, as it is a reference to the actual data in the buffer.
28    fn as_ndarray(&self) -> ArrayView3<'_, ImageContainer>;
29
30    /// Cast the `ImageBuffer` as an `ArrayViewMut3`.
31    ///
32    /// * `Y` index is the row
33    /// * `X` index is the columns
34    /// * `Z` index is the channel
35    ///
36    /// So when referencing:
37    /// `array[[y, x, z]]`
38    ///
39    /// This does not copy the data, as it is a reference to the actual data in the buffer.
40    fn as_ndarray_mut(&mut self) -> ArrayViewMut3<'_, ImageContainer>;
41
42    /// Interpret the `ImageBuffer` as an Array3.
43    ///
44    /// * `Y` index is the row
45    /// * `X` index is the columns
46    /// * `Z` index is the channel
47    ///
48    /// So when referencing:
49    /// `array[[y, x, z]]`
50    ///
51    /// This does not copy the data, but it does consume the buffer.
52    fn to_ndarray(self) -> Array3<ImageContainer>;
53
54    /// Convert the provided array into the `ImageBuffer`
55    ///
56    /// * `Y` index is the row
57    /// * `X` index is the columns
58    /// * `Z` index is the channel
59    ///
60    /// So when referencing:
61    /// `array[[y, x, z]]`
62    ///
63    /// This consumes the array. Standard layouts reuse its allocation; other
64    /// layouts are copied into row-major pixel order.
65    ///
66    /// # Errors
67    ///
68    /// Returns [`Error::Dimensions`] if the array is not 2D or 3D, or its size does not fit
69    /// into the image dimensions, [`Error::ChannelMismatch`] if the channel count differs from
70    /// the pixel type, and [`Error::ImageConstructFailed`] if the buffer cannot back an image.
71    fn from_ndarray<D: Dimension>(
72        array: Array<ImageContainer, D>,
73    ) -> Result<ImageBuffer<P, Vec<ImageContainer>>>;
74}
75
76#[cfg(feature = "image")]
77impl<P, C> ImageArray<P, C> for ImageBuffer<P, Vec<C>>
78where
79    P: Pixel<Subpixel = C>,
80    C: Clone + Copy,
81{
82    fn as_ndarray(&self) -> ArrayView3<'_, C> {
83        let (width, height) = self.dimensions();
84        // SAFETY: `as_raw` holds at least `width * height * CHANNEL_COUNT` elements (an
85        // `ImageBuffer` invariant), which is exactly the shape passed here. The returned view
86        // borrows `self`, so the buffer outlives it and is not mutated while it is read.
87        unsafe {
88            ArrayView3::from_shape_ptr(
89                (height as usize, width as usize, P::CHANNEL_COUNT as usize),
90                self.as_raw().as_ptr(),
91            )
92        }
93    }
94
95    #[allow(
96        clippy::expect_used,
97        reason = "the trait method is infallible and the shape is derived from the buffer's own dimensions after truncation"
98    )]
99    fn to_ndarray(self) -> Array3<C> {
100        let (width, height) = self.dimensions();
101        let shape = (height as usize, width as usize, P::CHANNEL_COUNT as usize);
102        let mut data = self.into_raw();
103        // ImageBuffer permits extra backing elements outside its pixel dimensions.
104        data.truncate(shape.0 * shape.1 * shape.2);
105        Array3::from_shape_vec(shape, data).expect("ImageBuffer dimensions match its pixel buffer")
106    }
107    fn from_ndarray<D: Dimension>(array: Array<C, D>) -> Result<ImageBuffer<P, Vec<C>>> {
108        let shape = array.shape();
109        if shape.len() < 2 {
110            return Err(Error::Dimensions);
111        }
112
113        let (width, height) = (shape[1], shape[0]);
114        let channels = match shape.len() {
115            2 => 1,
116            3 => shape[2],
117            _ => return Err(Error::Dimensions),
118        };
119
120        if channels != P::CHANNEL_COUNT.into() {
121            return Err(Error::ChannelMismatch);
122        }
123
124        let width = u32::try_from(width).map_err(|_| Error::Dimensions)?;
125        let height = u32::try_from(height).map_err(|_| Error::Dimensions)?;
126        let size = array.len();
127        let array = if array.is_standard_layout() {
128            array
129        } else {
130            array.as_standard_layout().into_owned()
131        };
132        let (mut data, offset) = array.into_raw_vec_and_offset();
133        // Owned slices can retain an offset and a larger backing allocation.
134        if let Some(offset) = offset.filter(|offset| *offset != 0) {
135            data.drain(..offset);
136        }
137        data.truncate(size);
138        Self::from_raw(width, height, data).ok_or(Error::ImageConstructFailed)
139    }
140
141    fn as_ndarray_mut(&mut self) -> ArrayViewMut3<'_, C> {
142        let (width, height) = self.dimensions();
143
144        // SAFETY: the buffer holds at least `width * height * CHANNEL_COUNT` elements (an
145        // `ImageBuffer` invariant), matching the shape passed here. Taking `&mut self` gives
146        // exclusive access for the lifetime of the returned view.
147        unsafe {
148            ArrayViewMut::from_shape_ptr(
149                (height as usize, width as usize, P::CHANNEL_COUNT as usize),
150                self.as_mut_ptr(),
151            )
152        }
153    }
154}
155
156/// Trait for converting the provided value to a normalized float.
157///
158/// This is used for image processing where a lot of operations rely on floating values.
159pub trait NormalizedFloat<T>
160where
161    T: AsPrimitive<f32> + AsPrimitive<f64>,
162{
163    /// Convert the value to a 32 bit float.
164    ///
165    /// The value will be in a normalized range according to color depths.
166    ///
167    /// For example in u8, a value of 255 would be represented as 1.0.
168    ///
169    /// Returns None if it overflows and could not be represented.
170    fn to_f32_normalized(&self) -> Option<f32>;
171    /// Convert the value to a 64 bit float
172    ///
173    /// The value will be in a normalized range according to color depths.
174    ///
175    /// For example in u8, a value of 255 would be represented as 1.0.
176    ///
177    /// Returns None if it overflows and could not be represented.
178    fn to_f64_normalized(&self) -> Option<f64>;
179
180    /// Converts the f32 value to the provided type
181    ///
182    /// Returns None if it overflows and could not be represented.
183    fn from_f32_normalized(value: f32) -> Option<T>;
184
185    /// Converts the f64 value to the provided type
186    ///
187    /// Returns None if it overflows and could not be represented.
188    fn from_f64_normalized(value: f64) -> Option<T>;
189}
190
191impl NormalizedFloat<f32> for f32 {
192    fn to_f32_normalized(&self) -> Option<f32> {
193        Some(*self)
194    }
195
196    fn to_f64_normalized(&self) -> Option<f64> {
197        self.to_f64()
198    }
199    fn from_f32_normalized(value: f32) -> Option<f32> {
200        Some(value)
201    }
202
203    fn from_f64_normalized(value: f64) -> Option<f32> {
204        value.to_f32()
205    }
206}
207
208impl NormalizedFloat<f64> for f64 {
209    fn to_f32_normalized(&self) -> Option<f32> {
210        self.to_f32()
211    }
212
213    fn to_f64_normalized(&self) -> Option<f64> {
214        Some(*self)
215    }
216    fn from_f32_normalized(value: f32) -> Option<f64> {
217        value.to_f64()
218    }
219
220    fn from_f64_normalized(value: f64) -> Option<f64> {
221        Some(value)
222    }
223}
224
225/// Implements [`NormalizedFloat`] for an integer type, scaling by its `MAX` value.
226///
227/// Converted values are multiplied or divided by `<$type>::MAX`, so `MAX` maps to 1.0.
228#[macro_export]
229macro_rules! impl_as_float {
230    ($type:ty) => {
231        impl NormalizedFloat<$type> for $type {
232            fn to_f32_normalized(&self) -> Option<f32> {
233                self.to_f32()
234                    .map(|converted| converted / <$type>::MAX as f32)
235            }
236
237            fn to_f64_normalized(&self) -> Option<f64> {
238                self.to_f64()
239                    .map(|converted| converted / <$type>::MAX as f64)
240            }
241
242            fn from_f32_normalized(value: f32) -> Option<$type> {
243                Some((value * <$type>::MAX as f32).as_())
244            }
245
246            fn from_f64_normalized(value: f64) -> Option<$type> {
247                Some((value * <$type>::MAX as f64).as_())
248            }
249        }
250    };
251}
252
253impl_as_float!(i32);
254impl_as_float!(u32);
255impl_as_float!(i16);
256impl_as_float!(u16);
257impl_as_float!(i8);
258impl_as_float!(u8);
259
260#[cfg(feature = "image")]
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use image::{Luma, Rgb, Rgb32FImage, Rgba32FImage};
265    use ndarray::{Array1, Array2, Array4};
266    use rstest::*;
267
268    /// Checks that an RGBA float image viewed as an array indexes the same values as its pixels.
269    #[test]
270    fn test_as_ndarray_rgba() {
271        let (width, height, channels) = (256, 128, 4);
272        let data = create_test_data(width, height, channels);
273        let test_image = Rgba32FImage::from_vec(256, 128, data).unwrap();
274
275        let array = test_image.as_ndarray();
276
277        for ((y, x, channel), value) in array.indexed_iter() {
278            assert_eq!(test_image.get_pixel(x as u32, y as u32)[channel], *value);
279        }
280    }
281
282    /// Checks that a single-channel float image viewed as an array matches its pixels.
283    #[test]
284    fn test_as_ndarray_luma() {
285        let (width, height, channels) = (256, 128, 1);
286        let data = create_test_data(width, height, channels);
287        let test_image: ImageBuffer<Luma<f32>, Vec<f32>> =
288            ImageBuffer::from_vec(256, 128, data).unwrap();
289
290        let array = test_image.as_ndarray();
291
292        for ((y, x, channel), value) in array.indexed_iter() {
293            assert_eq!(test_image.get_pixel(x as u32, y as u32)[channel], *value);
294        }
295    }
296
297    /// Checks that writes through the mutable array view update the image pixels.
298    #[test]
299    fn test_as_ndarray_mut() {
300        let (width, height, channels) = (256, 128, 4);
301        let data = create_test_data(width, height, channels);
302        let mut test_image = Rgba32FImage::from_vec(256, 128, data).unwrap();
303        let compare = test_image.clone();
304
305        let mut array = test_image.as_ndarray_mut();
306        array += 1.0;
307
308        for (x, y, pixel) in test_image.enumerate_pixels() {
309            let compare_pixel = compare.get_pixel(x, y);
310            for (channel, value) in pixel.channels().iter().enumerate() {
311                assert_eq!(*value, compare_pixel[channel] + 1.0);
312            }
313        }
314    }
315
316    /// Checks that consuming an image into an array keeps every pixel value in place.
317    #[test]
318    fn test_to_ndarray() {
319        let (width, height, channels) = (256, 128, 4);
320        let data = create_test_data(width, height, channels);
321        let test_image = Rgba32FImage::from_vec(256, 128, data).unwrap();
322
323        let mut array = test_image.clone().to_ndarray();
324
325        array += 1.0;
326        for ((y, x, channel), value) in array.indexed_iter() {
327            assert_eq!(
328                test_image.get_pixel(x as u32, y as u32)[channel] + 1.0,
329                *value
330            );
331        }
332    }
333
334    /// Checks that a 3D array converts into an RGBA image with matching pixel values.
335    #[test]
336    fn test_from_ndarray() {
337        let (width, height, channels) = (256, 128, 4);
338        let data = create_test_data(width, height, channels);
339        let test_image = Array3::from_shape_vec((height, width, channels), data).unwrap();
340        let compare_data = test_image.clone();
341
342        let result = Rgba32FImage::from_ndarray(test_image).unwrap();
343
344        for (x, y, pixel) in result.enumerate_pixels() {
345            for (channel, value) in pixel.channels().iter().enumerate() {
346                assert_eq!(*value, compare_data[[y as usize, x as usize, channel]]);
347            }
348        }
349    }
350
351    /// Checks that a 2D array converts into a single-channel image.
352    #[test]
353    fn test_from_ndarray_2d() {
354        let (width, height, channels) = (256, 128, 1);
355        let data = create_test_data(width, height, channels);
356        let test_image = Array2::from_shape_vec((height, width), data).unwrap();
357        let compare_data = test_image.clone();
358
359        let result = ImageBuffer::<Luma<f32>, Vec<f32>>::from_ndarray(test_image).unwrap();
360
361        for (x, y, pixel) in result.enumerate_pixels() {
362            for value in pixel.channels() {
363                assert_eq!(*value, compare_data[[y as usize, x as usize]]);
364            }
365        }
366    }
367
368    /// Returns `width * height * channels` ascending values starting at 1.
369    fn create_test_data(width: usize, height: usize, channels: usize) -> Vec<f32> {
370        let total_elements = width * height * channels;
371        (0..total_elements).map(|x| (x + 1) as f32).collect()
372    }
373
374    /// Checks that converting an array whose channel count differs from the pixel type fails with `ChannelMismatch`.
375    #[test]
376    fn test_from_ndarray_with_invalid_channels() {
377        let channels = 4;
378        let (width, height) = (256.0, 128.0);
379        let total_elements = (width * height * 4.0) as usize;
380        let data: Vec<f32> = (0..total_elements).map(|x| (x + 1) as f32).collect();
381        let test_image =
382            Array3::from_shape_vec((height as usize, width as usize, channels), data).unwrap();
383
384        let result = Rgb32FImage::from_ndarray(test_image.into_dyn())
385            .err()
386            .unwrap();
387
388        assert_eq!(result, Error::ChannelMismatch);
389    }
390
391    /// Checks that an RGB `u8` image viewed as an array maps `[y, x, channel]` to the stored bytes.
392    #[test]
393    fn test_as_ndarray_u8_hand_values() {
394        let image = ImageBuffer::<Rgb<u8>, Vec<u8>>::from_raw(3, 2, (0..18).collect()).unwrap();
395
396        let array = image.as_ndarray();
397
398        assert_eq!(array.shape(), &[2, 3, 3]);
399        assert_eq!(array[[0, 0, 0]], 0);
400        assert_eq!(array[[0, 1, 0]], 3);
401        assert_eq!(array[[1, 2, 2]], 17);
402    }
403
404    /// Checks that a write through `as_ndarray_mut` lands at the expected byte of a grayscale image.
405    #[test]
406    fn test_as_ndarray_mut_luma_hand_values() {
407        let mut image =
408            ImageBuffer::<Luma<u8>, Vec<u8>>::from_raw(2, 2, vec![10, 20, 30, 40]).unwrap();
409
410        image.as_ndarray_mut()[[1, 0, 0]] = 99;
411
412        assert_eq!(image.as_raw().as_slice(), &[10, 20, 99, 40]);
413    }
414
415    /// Checks that a `(height, width, 1)` array becomes a grayscale image with row-major pixels.
416    #[test]
417    fn test_from_ndarray_3d_single_channel_hand_values() {
418        let array = Array3::from_shape_vec((2, 3, 1), vec![1_u8, 2, 3, 4, 5, 6]).unwrap();
419
420        let image = ImageBuffer::<Luma<u8>, Vec<u8>>::from_ndarray(array).unwrap();
421
422        assert_eq!(image.dimensions(), (3, 2));
423        assert_eq!(image.get_pixel(2, 0)[0], 3);
424        assert_eq!(image.get_pixel(0, 1)[0], 4);
425    }
426
427    /// Checks that 1D and 4D arrays are rejected with `Dimensions`, since images are 2D or 3D.
428    #[test]
429    fn test_from_ndarray_rejects_1d_and_4d_arrays() {
430        let one_d = Array1::from_vec(vec![1_u8, 2, 3, 4]);
431        assert_eq!(
432            ImageBuffer::<Luma<u8>, Vec<u8>>::from_ndarray(one_d).err(),
433            Some(Error::Dimensions)
434        );
435
436        let four_d = Array4::from_shape_vec((1, 2, 2, 1), vec![1_u8, 2, 3, 4]).unwrap();
437        assert_eq!(
438            ImageBuffer::<Luma<u8>, Vec<u8>>::from_ndarray(four_d).err(),
439            Some(Error::Dimensions)
440        );
441    }
442
443    /// Checks that a 2D array cannot back a three-channel image, because it has one implicit channel.
444    #[test]
445    fn test_from_ndarray_2d_into_rgb_channel_mismatch() {
446        let array = Array2::from_shape_vec((2, 3), vec![1_u8; 6]).unwrap();
447
448        assert_eq!(
449            ImageBuffer::<Rgb<u8>, Vec<u8>>::from_ndarray(array).err(),
450            Some(Error::ChannelMismatch)
451        );
452    }
453
454    /// Checks the exact scale factors: `MAX` maps to 1.0, and the truncating cast back to an integer.
455    #[test]
456    fn test_normalized_ints_hand_values() {
457        assert_eq!(200_u8.to_f32_normalized(), Some(200.0 / 255.0));
458        assert_eq!((-128_i8).to_f32_normalized(), Some(-128.0 / 127.0));
459        assert_eq!(u16::MAX.to_f64_normalized(), Some(1.0));
460        assert_eq!(u8::from_f32_normalized(0.5), Some(127));
461        assert_eq!(i8::from_f32_normalized(-1.0), Some(-127));
462    }
463
464    /// Checks that out-of-range normalized values saturate at the integer limits instead of wrapping.
465    #[test]
466    fn test_from_normalized_saturates_at_limits() {
467        assert_eq!(u8::from_f32_normalized(2.0), Some(u8::MAX));
468        assert_eq!(u8::from_f64_normalized(-0.5), Some(0));
469        assert_eq!(i8::from_f64_normalized(-2.0), Some(i8::MIN));
470    }
471
472    #[rstest]
473    #[case(1.0)]
474    #[case(255.0)]
475    #[case(0.5)]
476    #[case(-1.0)]
477    #[case(-255.0)]
478    /// Checks that `f32` and `f64` normalization are identity conversions and that they round-trip.
479    fn test_f32(#[case] float: f32) {
480        assert_eq!(float.to_f32_normalized().unwrap(), float);
481        assert_eq!(f32::from_f32_normalized(float).unwrap(), float);
482
483        let float_64: f64 = float.as_();
484        assert_eq!(float_64.to_f64_normalized().unwrap(), float_64);
485        assert_eq!(f64::from_f64_normalized(float_64).unwrap(), float_64);
486
487        let converted_to_float64 = float.to_f64_normalized().unwrap();
488        assert_eq!(converted_to_float64, float as f64);
489
490        let converted_back_to_float32 = float_64.to_f32_normalized().unwrap();
491        assert_eq!(converted_back_to_float32, float);
492    }
493
494    /// Generates a test that normalizes and denormalizes unsigned integers of the given type.
495    #[macro_export]
496    macro_rules! test_unsigned_ints {
497        ($name:ident, $type:ty) => {
498            #[rstest]
499            #[case(0)]
500            #[case(1)]
501            #[case($type::MAX)]
502            #[case($type::MIN)]
503            fn $name(#[case] int: $type) {
504                let normalized_f32 = int.to_f32_normalized().unwrap();
505                let expected_normalized_f32 = int as f32 / <$type>::MAX as f32;
506                assert_eq!(normalized_f32, expected_normalized_f32);
507
508                let int_from_float32 =
509                    <$type>::from_f32_normalized(expected_normalized_f32).unwrap();
510                let expected_int_from_float32 =
511                    (expected_normalized_f32 * <$type>::MAX as f32) as $type;
512                assert_eq!(int_from_float32, expected_int_from_float32);
513
514                let normalized_f64 = int.to_f64_normalized().unwrap();
515                let expected_normalized_f64 = int as f64 / <$type>::MAX as f64;
516                assert_eq!(normalized_f64, expected_normalized_f64);
517
518                let int_from_float64 =
519                    <$type>::from_f64_normalized(expected_normalized_f64).unwrap();
520                let expected_int_from_float64 =
521                    (expected_normalized_f64 * <$type>::MAX as f64) as $type;
522                assert_eq!(int_from_float64, expected_int_from_float64);
523            }
524        };
525    }
526
527    /// Generates a test that normalizes and denormalizes signed integers of the given type.
528    #[macro_export]
529    macro_rules! test_signed_ints {
530        ($name:ident, $type:ty) => {
531            #[rstest]
532            #[case(0)]
533            #[case(1)]
534            #[case($type::MAX)]
535            #[case($type::MIN)]
536            #[case(-1)]
537            #[case(-$type::MAX)]
538            fn $name(#[case] int: $type) {
539                let normalized_f32 = int.to_f32_normalized().unwrap();
540                let expected_normalized_f32 = int as f32 / <$type>::MAX as f32;
541                assert_eq!(normalized_f32, expected_normalized_f32);
542
543                let int_from_float32 =
544                    <$type>::from_f32_normalized(expected_normalized_f32).unwrap();
545                let expected_int_from_float32 =
546                    (expected_normalized_f32 * <$type>::MAX as f32) as $type;
547                assert_eq!(int_from_float32, expected_int_from_float32);
548
549                let normalized_f64 = int.to_f64_normalized().unwrap();
550                let expected_normalized_f64 = int as f64 / <$type>::MAX as f64;
551                assert_eq!(normalized_f64, expected_normalized_f64);
552
553                let int_from_float64 =
554                    <$type>::from_f64_normalized(expected_normalized_f64).unwrap();
555                let expected_int_from_float64 =
556                    (expected_normalized_f64 * <$type>::MAX as f64) as $type;
557                assert_eq!(int_from_float64, expected_int_from_float64);
558            }
559        };
560    }
561    test_signed_ints!(test_i32, i32);
562    test_signed_ints!(test_i16, i16);
563    test_signed_ints!(test_i8, i8);
564    test_unsigned_ints!(test_u32, u32);
565    test_unsigned_ints!(test_u16, u16);
566    test_unsigned_ints!(test_u8, u8);
567}