Skip to main content

adk_vision/geometry/
transform.rs

1//! [`TransformChain`]: what happened between the source image and what a backend saw.
2
3use serde::{Deserialize, Serialize};
4
5use super::{BBox, Keypoint, Keypoints, Mask, Point2, Polygon, Shape};
6use crate::error::{Result, VisionError};
7
8/// One step between the source image and what a backend saw.
9///
10/// Serialized with an `op` tag: `{"op": "resize", "width": 1568, "height": 1018}`.
11#[non_exhaustive]
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "op")]
14pub enum Transform {
15    /// Keep the whole-pixel rectangle at `(x, y)` of `width` × `height`.
16    Crop {
17        /// Left edge.
18        x: u32,
19        /// Top edge.
20        y: u32,
21        /// Width.
22        width: u32,
23        /// Height.
24        height: u32,
25    },
26    /// Scale to `width` × `height`.
27    Resize {
28        /// New width.
29        width: u32,
30        /// New height.
31        height: u32,
32    },
33    /// Add padding on each side.
34    Pad {
35        /// Pixels added on the left.
36        left: u32,
37        /// Pixels added on top.
38        top: u32,
39        /// Pixels added on the right.
40        right: u32,
41        /// Pixels added at the bottom.
42        bottom: u32,
43    },
44    /// Rotate clockwise by `quarter_turns` × 90°.
45    Rotate {
46        /// Clockwise quarter turns, taken modulo 4.
47        quarter_turns: u8,
48    },
49    /// Pixels changed, coordinates did not.
50    Redact,
51}
52
53/// The transforms from a source image of `source_width` × `source_height` to the image a
54/// backend saw, in order.
55///
56/// Mapping a point to the backend's image and back returns it within floating-point error;
57/// the property tests hold it within 0.5 px for random chains.
58///
59/// # Example
60///
61/// ```
62/// use adk_vision::{Transform, TransformChain};
63///
64/// // A 3024x1964 screenshot, cropped, then resized to half size.
65/// let chain = TransformChain::new(3024, 1964)
66///     .then(Transform::Crop { x: 1000, y: 500, width: 800, height: 600 })
67///     .unwrap()
68///     .then(Transform::Resize { width: 400, height: 300 })
69///     .unwrap();
70/// assert_eq!(chain.output_size(), (400, 300));
71/// assert_eq!(chain.to_target([1200.0, 700.0]), [100.0, 100.0]);
72/// assert_eq!(chain.to_source([100.0, 100.0]), [1200.0, 700.0]);
73/// ```
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76pub struct TransformChain {
77    /// The source image's width.
78    pub source_width: u32,
79    /// The source image's height.
80    pub source_height: u32,
81    /// The steps, in the order they were applied.
82    pub steps: Vec<Transform>,
83}
84
85impl TransformChain {
86    /// The empty chain of a source image: the backend sees the image as it is.
87    pub fn new(source_width: u32, source_height: u32) -> Self {
88        Self { source_width, source_height, steps: Vec::new() }
89    }
90
91    /// Appends a step.
92    ///
93    /// # Errors
94    ///
95    /// Returns [`VisionError::InvalidInput`] for a crop outside the current image, an empty
96    /// crop or a resize to zero.
97    pub fn then(mut self, step: Transform) -> Result<Self> {
98        self.push(step)?;
99        Ok(self)
100    }
101
102    /// Appends a step in place. See [`then`](Self::then).
103    ///
104    /// # Errors
105    ///
106    /// As [`then`](Self::then).
107    pub fn push(&mut self, step: Transform) -> Result<()> {
108        let (w, h) = self.output_size();
109        match step {
110            Transform::Crop { x, y, width, height } => {
111                if width == 0
112                    || height == 0
113                    || u64::from(x) + u64::from(width) > u64::from(w)
114                    || u64::from(y) + u64::from(height) > u64::from(h)
115                {
116                    return Err(VisionError::InvalidInput(format!(
117                        "crop {width}x{height} at ({x}, {y}) does not fit in the {w}x{h} image"
118                    )));
119                }
120            }
121            Transform::Resize { width, height } => {
122                if width == 0 || height == 0 {
123                    return Err(VisionError::InvalidInput(format!(
124                        "resize to {width}x{height} leaves no pixels"
125                    )));
126                }
127            }
128            Transform::Pad { .. } | Transform::Rotate { .. } | Transform::Redact => {}
129        }
130        self.steps.push(step);
131        Ok(())
132    }
133
134    /// `true` when the chain has no step that moves coordinates.
135    pub fn is_identity(&self) -> bool {
136        self.steps.iter().all(|s| matches!(s, Transform::Redact))
137    }
138
139    /// The size of the image after every step.
140    pub fn output_size(&self) -> (u32, u32) {
141        self.sizes().last().copied().unwrap_or((self.source_width, self.source_height))
142    }
143
144    /// The image size before each step, then the output size.
145    fn sizes(&self) -> Vec<(u32, u32)> {
146        let mut sizes = Vec::with_capacity(self.steps.len() + 1);
147        let mut size = (self.source_width, self.source_height);
148        sizes.push(size);
149        for step in &self.steps {
150            size = match *step {
151                Transform::Crop { width, height, .. } => (width, height),
152                Transform::Resize { width, height } => (width, height),
153                Transform::Pad { left, top, right, bottom } => (
154                    size.0.saturating_add(left).saturating_add(right),
155                    size.1.saturating_add(top).saturating_add(bottom),
156                ),
157                Transform::Rotate { quarter_turns } if quarter_turns % 2 == 1 => (size.1, size.0),
158                Transform::Rotate { .. } | Transform::Redact => size,
159            };
160            sizes.push(size);
161        }
162        sizes
163    }
164
165    /// Maps a point in source pixels to the backend's image.
166    pub fn to_target(&self, point: [f64; 2]) -> [f64; 2] {
167        let sizes = self.sizes();
168        let mut p = point;
169        for (step, &(w, h)) in self.steps.iter().zip(&sizes) {
170            let (w, h) = (f64::from(w), f64::from(h));
171            p = match *step {
172                Transform::Crop { x, y, .. } => [p[0] - f64::from(x), p[1] - f64::from(y)],
173                Transform::Resize { width, height } => {
174                    [p[0] * f64::from(width) / w, p[1] * f64::from(height) / h]
175                }
176                Transform::Pad { left, top, .. } => [p[0] + f64::from(left), p[1] + f64::from(top)],
177                Transform::Rotate { quarter_turns } => match quarter_turns % 4 {
178                    1 => [h - p[1], p[0]],
179                    2 => [w - p[0], h - p[1]],
180                    3 => [p[1], w - p[0]],
181                    _ => p,
182                },
183                Transform::Redact => p,
184            };
185        }
186        p
187    }
188
189    /// Maps a point in the backend's image back to source pixels.
190    pub fn to_source(&self, point: [f64; 2]) -> [f64; 2] {
191        let sizes = self.sizes();
192        let mut p = point;
193        for (step, &(w, h)) in self.steps.iter().zip(&sizes).rev() {
194            let (w, h) = (f64::from(w), f64::from(h));
195            p = match *step {
196                Transform::Crop { x, y, .. } => [p[0] + f64::from(x), p[1] + f64::from(y)],
197                Transform::Resize { width, height } => {
198                    [p[0] * w / f64::from(width), p[1] * h / f64::from(height)]
199                }
200                Transform::Pad { left, top, .. } => [p[0] - f64::from(left), p[1] - f64::from(top)],
201                Transform::Rotate { quarter_turns } => match quarter_turns % 4 {
202                    1 => [p[1], h - p[0]],
203                    2 => [w - p[0], h - p[1]],
204                    3 => [w - p[1], p[0]],
205                    _ => p,
206                },
207                Transform::Redact => p,
208            };
209        }
210        p
211    }
212
213    /// Maps a box in the backend's image to source pixels; a rotation keeps it axis-aligned.
214    pub fn bbox_to_source(&self, bbox: &BBox) -> BBox {
215        map_box(bbox, |p| self.to_source(p))
216    }
217
218    /// Maps a box in source pixels to the backend's image.
219    pub fn bbox_to_target(&self, bbox: &BBox) -> BBox {
220        map_box(bbox, |p| self.to_target(p))
221    }
222
223    /// Maps a shape in the backend's image to source pixels. A mask must be the size of the
224    /// backend's image and comes back resampled to the source size.
225    ///
226    /// # Errors
227    ///
228    /// Returns [`VisionError::InvalidInput`] for a mask whose size is not the target size.
229    pub fn shape_to_source(&self, shape: &Shape) -> Result<Shape> {
230        self.map_shape(shape, |p| self.to_source(p))
231    }
232
233    /// Maps a shape in source pixels to the backend's image, resampling a mask to the target
234    /// size.
235    ///
236    /// # Errors
237    ///
238    /// Returns [`VisionError::InvalidInput`] for a mask whose size is not the source size.
239    pub fn shape_to_target(&self, shape: &Shape) -> Result<Shape> {
240        match shape {
241            Shape::Mask(mask) => {
242                if (mask.width, mask.height) != (self.source_width, self.source_height) {
243                    return Err(VisionError::InvalidInput(format!(
244                        "a {}x{} mask is not in the {}x{} source image's pixels",
245                        mask.width, mask.height, self.source_width, self.source_height
246                    )));
247                }
248                let (tw, th) = self.output_size();
249                Ok(Shape::Mask(resample(
250                    mask,
251                    (tw, th),
252                    |p| self.to_source(p),
253                    |p| self.to_target(p),
254                )))
255            }
256            other => self.map_shape(other, |p| self.to_target(p)),
257        }
258    }
259
260    fn map_shape(&self, shape: &Shape, f: impl Fn([f64; 2]) -> [f64; 2]) -> Result<Shape> {
261        let pt = |x: f32, y: f32| {
262            let q = f([f64::from(x), f64::from(y)]);
263            [q[0] as f32, q[1] as f32]
264        };
265        Ok(match shape {
266            Shape::Point(p) => {
267                let [x, y] = pt(p.x, p.y);
268                Shape::Point(Point2 { x, y })
269            }
270            Shape::Box(b) => Shape::Box(map_box(b, &f)),
271            Shape::Polygon(poly) => Shape::Polygon(Polygon {
272                points: poly.points.iter().map(|p| pt(p[0], p[1])).collect(),
273            }),
274            Shape::Keypoints(k) => Shape::Keypoints(Keypoints {
275                skeleton: k.skeleton.clone(),
276                points: k
277                    .points
278                    .iter()
279                    .map(|kp| {
280                        let [x, y] = pt(kp.x, kp.y);
281                        Keypoint { x, y, ..*kp }
282                    })
283                    .collect(),
284            }),
285            Shape::Mask(mask) => {
286                let target = self.output_size();
287                if (mask.width, mask.height) != target {
288                    return Err(VisionError::InvalidInput(format!(
289                        "a {}x{} mask is not in the {}x{} image the backend saw",
290                        mask.width, mask.height, target.0, target.1
291                    )));
292                }
293                let source = (self.source_width, self.source_height);
294                Shape::Mask(resample(mask, source, |p| self.to_target(p), |p| self.to_source(p)))
295            }
296        })
297    }
298}
299
300fn map_box(bbox: &BBox, f: impl Fn([f64; 2]) -> [f64; 2]) -> BBox {
301    let corners = [[bbox.x0, bbox.y0], [bbox.x1, bbox.y0], [bbox.x0, bbox.y1], [bbox.x1, bbox.y1]];
302    let mapped = corners.map(|[x, y]| {
303        let q = f([f64::from(x), f64::from(y)]);
304        [q[0] as f32, q[1] as f32]
305    });
306    BBox::covering(mapped).unwrap_or(*bbox)
307}
308
309/// Resamples `mask` into a raster of `size`: a pixel is set when its centre, mapped into the
310/// mask's frame with `into_mask`, lands on a set pixel. `out_of_mask` maps the mask's frame
311/// to the new one, to bound the pixels visited.
312pub(crate) fn resample(
313    mask: &Mask,
314    size: (u32, u32),
315    into_mask: impl Fn([f64; 2]) -> [f64; 2],
316    out_of_mask: impl Fn([f64; 2]) -> [f64; 2],
317) -> Mask {
318    let Some(bounds) = mask.bbox() else {
319        return Mask::empty(size.0, size.1);
320    };
321    let region = map_box(&bounds, out_of_mask).expanded(1.0);
322    let (x0, y0, w, h) = region.pixel_bounds(size.0, size.1);
323    let bits = mask.decode();
324    let mut out = vec![false; size.0 as usize * size.1 as usize];
325    for y in y0..y0 + h {
326        for x in x0..x0 + w {
327            let p = into_mask([f64::from(x) + 0.5, f64::from(y) + 0.5]);
328            if p[0] < 0.0 || p[1] < 0.0 {
329                continue;
330            }
331            let (mx, my) = (p[0].floor() as u64, p[1].floor() as u64);
332            if mx < u64::from(mask.width)
333                && my < u64::from(mask.height)
334                && bits[my as usize * mask.width as usize + mx as usize]
335            {
336                out[y as usize * size.0 as usize + x as usize] = true;
337            }
338        }
339    }
340    Mask::encode(size.0, size.1, &out)
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    #[test]
348    fn rotations_swap_dimensions_and_invert() {
349        for q in 0..4u8 {
350            let chain =
351                TransformChain::new(300, 200).then(Transform::Rotate { quarter_turns: q }).unwrap();
352            let expected = if q % 2 == 1 { (200, 300) } else { (300, 200) };
353            assert_eq!(chain.output_size(), expected);
354            let p = [17.0, 43.0];
355            let back = chain.to_source(chain.to_target(p));
356            assert!((back[0] - p[0]).abs() < 1e-9 && (back[1] - p[1]).abs() < 1e-9, "q={q}");
357        }
358    }
359
360    #[test]
361    fn a_crop_must_fit() {
362        let err = TransformChain::new(100, 100)
363            .then(Transform::Crop { x: 50, y: 0, width: 60, height: 10 })
364            .unwrap_err();
365        assert!(err.to_string().contains("does not fit"));
366    }
367
368    #[test]
369    fn masks_resample_to_the_source() {
370        // A 4x4 block in a half-size image becomes an 8x8 block in the source.
371        let chain =
372            TransformChain::new(40, 40).then(Transform::Resize { width: 20, height: 20 }).unwrap();
373        let mut bits = vec![false; 400];
374        for y in 5..9 {
375            for x in 5..9 {
376                bits[y * 20 + x] = true;
377            }
378        }
379        let sent = Mask::encode(20, 20, &bits);
380        let Shape::Mask(source) = chain.shape_to_source(&Shape::Mask(sent)).unwrap() else {
381            panic!("not a mask")
382        };
383        assert_eq!((source.width, source.height), (40, 40));
384        assert_eq!(source.area(), 64);
385        assert_eq!(source.bbox(), Some(BBox::new(10.0, 10.0, 18.0, 18.0)));
386    }
387}