Skip to main content

pltrs_render/
filter.rs

1//! Image filters applied to what an artist draws (matplotlib's agg
2//! filters: `Artist.set_agg_filter` with `RendererAgg.start_filter` and
3//! `stop_filter`).
4
5use crate::image::{ImageSizeError, RgbaImage};
6
7/// The pixels an image filter works on: straight-alpha RGBA, nominally in
8/// `[0, 1]`, row-major with the top row first (matplotlib's
9/// `(height, width, 4)` float array).
10#[derive(Clone, Debug, PartialEq)]
11pub struct FilterImage {
12    width: usize,
13    height: usize,
14    pixels: Vec<[f64; 4]>,
15}
16
17impl FilterImage {
18    /// Wraps `pixels` (`width * height` of them, top row first).
19    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    /// An image of one colour.
35    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    /// Width in pixels.
44    pub const fn width(&self) -> usize {
45        self.width
46    }
47
48    /// Height in pixels.
49    pub const fn height(&self) -> usize {
50        self.height
51    }
52
53    /// The pixels, top row first.
54    pub fn pixels(&self) -> &[[f64; 4]] {
55        &self.pixels
56    }
57
58    /// The pixels, mutably.
59    pub fn pixels_mut(&mut self) -> &mut [[f64; 4]] {
60        &mut self.pixels
61    }
62
63    /// The pixel in column `x` of row `y` (from the top), if in bounds.
64    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    /// The 8-bit image as fractions of 255.
69    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    /// The image in 8 bits, truncating `value * 255` as numpy's
85    /// `astype(uint8)` does; values outside `[0, 1]` are clamped.
86    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/// What an image filter returns: the new image, and where its bottom-left
97/// corner goes in pixels from the bottom-left corner of the image it was
98/// given.
99#[derive(Clone, Debug, PartialEq)]
100pub struct Filtered {
101    /// The filtered image (of any size).
102    pub image: FilterImage,
103    /// The offset of its bottom-left corner.
104    pub offset: (f64, f64),
105}
106
107/// An image filter (matplotlib's agg filter function): it receives what an
108/// artist drew, cropped to its visible pixels, and the resolution in dots
109/// per inch.
110pub type FilterFn<'a> = dyn Fn(&FilterImage, f64) -> Filtered + 'a;
111
112/// An image filter the renderer may keep (see
113/// [`Renderer::stop_shared_filter`](crate::Renderer::stop_shared_filter)).
114pub 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}