1use serde::{Deserialize, Serialize};
4
5use super::{BBox, Keypoint, Keypoints, Mask, Point2, Polygon, Shape};
6use crate::error::{Result, VisionError};
7
8#[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 Crop {
17 x: u32,
19 y: u32,
21 width: u32,
23 height: u32,
25 },
26 Resize {
28 width: u32,
30 height: u32,
32 },
33 Pad {
35 left: u32,
37 top: u32,
39 right: u32,
41 bottom: u32,
43 },
44 Rotate {
46 quarter_turns: u8,
48 },
49 Redact,
51}
52
53#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76pub struct TransformChain {
77 pub source_width: u32,
79 pub source_height: u32,
81 pub steps: Vec<Transform>,
83}
84
85impl TransformChain {
86 pub fn new(source_width: u32, source_height: u32) -> Self {
88 Self { source_width, source_height, steps: Vec::new() }
89 }
90
91 pub fn then(mut self, step: Transform) -> Result<Self> {
98 self.push(step)?;
99 Ok(self)
100 }
101
102 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 pub fn is_identity(&self) -> bool {
136 self.steps.iter().all(|s| matches!(s, Transform::Redact))
137 }
138
139 pub fn output_size(&self) -> (u32, u32) {
141 self.sizes().last().copied().unwrap_or((self.source_width, self.source_height))
142 }
143
144 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 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 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 pub fn bbox_to_source(&self, bbox: &BBox) -> BBox {
215 map_box(bbox, |p| self.to_source(p))
216 }
217
218 pub fn bbox_to_target(&self, bbox: &BBox) -> BBox {
220 map_box(bbox, |p| self.to_target(p))
221 }
222
223 pub fn shape_to_source(&self, shape: &Shape) -> Result<Shape> {
230 self.map_shape(shape, |p| self.to_source(p))
231 }
232
233 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
309pub(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 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}