1use crate::image::{ImageSizeError, RgbaImage};
6
7#[derive(Clone, Debug, PartialEq)]
11pub struct FilterImage {
12 width: usize,
13 height: usize,
14 pixels: Vec<[f64; 4]>,
15}
16
17impl FilterImage {
18 pub fn new(width: usize, height: usize, pixels: Vec<[f64; 4]>) -> Result<Self, ImageSizeError> {
20 if pixels.len() == width * height {
21 Ok(Self {
22 width,
23 height,
24 pixels,
25 })
26 } else {
27 Err(ImageSizeError {
28 expected: width * height * 4,
29 actual: pixels.len() * 4,
30 })
31 }
32 }
33
34 pub fn filled(width: usize, height: usize, pixel: [f64; 4]) -> Self {
36 Self {
37 width,
38 height,
39 pixels: vec![pixel; width * height],
40 }
41 }
42
43 pub const fn width(&self) -> usize {
45 self.width
46 }
47
48 pub const fn height(&self) -> usize {
50 self.height
51 }
52
53 pub fn pixels(&self) -> &[[f64; 4]] {
55 &self.pixels
56 }
57
58 pub fn pixels_mut(&mut self) -> &mut [[f64; 4]] {
60 &mut self.pixels
61 }
62
63 pub fn pixel(&self, x: usize, y: usize) -> Option<[f64; 4]> {
65 (x < self.width && y < self.height).then(|| self.pixels[y * self.width + x])
66 }
67
68 pub(crate) fn from_rgba(image: &RgbaImage) -> Self {
70 let pixels = image
71 .data()
72 .as_chunks::<4>()
73 .0
74 .iter()
75 .map(|p| p.map(|c| f64::from(c) / 255.0))
76 .collect();
77 Self {
78 width: image.width(),
79 height: image.height(),
80 pixels,
81 }
82 }
83
84 pub(crate) fn to_rgba(&self) -> RgbaImage {
87 let data = self
88 .pixels
89 .iter()
90 .flat_map(|pixel| pixel.map(|c| (c * 255.0).clamp(0.0, 255.0) as u8))
91 .collect();
92 RgbaImage::new(self.width, self.height, data).expect("one RGBA quadruple per pixel")
93 }
94}
95
96#[derive(Clone, Debug, PartialEq)]
100pub struct Filtered {
101 pub image: FilterImage,
103 pub offset: (f64, f64),
105}
106
107pub type FilterFn<'a> = dyn Fn(&FilterImage, f64) -> Filtered + 'a;
111
112pub type SharedFilter = std::rc::Rc<FilterFn<'static>>;
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 #[test]
121 fn eight_bit_round_trips_truncate_like_numpy() {
122 let image = RgbaImage::new(1, 1, vec![0, 128, 255, 7]).unwrap();
123 let filter = FilterImage::from_rgba(&image);
124 assert_eq!(filter.to_rgba(), image);
125 let odd = FilterImage::new(2, 1, vec![[0.999, -0.5, 1.5, f64::NAN], [0.5; 4]]).unwrap();
126 assert_eq!(odd.to_rgba().data(), &[254, 0, 255, 0, 127, 127, 127, 127]);
127 assert!(FilterImage::new(2, 2, vec![[0.0; 4]]).is_err());
128 assert_eq!(
129 FilterImage::filled(2, 1, [1.0; 4]).pixel(1, 0),
130 Some([1.0; 4])
131 );
132 }
133}