Skip to main content

adk_vision/geometry/
normalize.rs

1//! [`RegionNormalizer`]: a backend's [`RawRegion`]s to [`Region`]s in source pixels.
2
3use super::transform::resample;
4use super::{
5    BBox, CoordFrame, Keypoint, Keypoints, Point2, Polygon, RawRegion, Region, RegionOrigin, Shape,
6    TransformChain,
7};
8use crate::backend::BackendId;
9use crate::digest::Digest;
10use crate::error::{Result, VisionError};
11
12/// Turns a backend's answers into regions of the source image.
13///
14/// A raw shape is mapped from the backend's [`CoordFrame`] to the pixels of the image it was
15/// sent, back through the [`TransformChain`] to source pixels, and clamped to the source
16/// image. A box or mask left with no area is dropped.
17///
18/// # Example
19///
20/// ```
21/// use adk_vision::{
22///     AxisOrder, BBox, BackendId, CoordFrame, Digest, RawRegion, RegionNormalizer, Shape,
23///     Transform, TransformChain,
24/// };
25///
26/// // The source was halved before it was sent; Gemini answered on 0-1000.
27/// let chain = TransformChain::new(2000, 1000)
28///     .then(Transform::Resize { width: 1000, height: 500 })
29///     .unwrap();
30/// let frame = CoordFrame::Normalized { scale: 1000, order: AxisOrder::Yx };
31/// let normalizer =
32///     RegionNormalizer::new(Digest::of(b"source"), chain, frame, BackendId::new("gemini"));
33/// let raw = RawRegion::boxed(frame.box_from_raw([100.0, 250.0, 500.0, 750.0]), "cat", 0.9);
34/// let region = normalizer.region(raw).unwrap().unwrap();
35/// assert_eq!(region.shape, Shape::Box(BBox::new(500.0, 100.0, 1500.0, 500.0)));
36/// ```
37#[derive(Clone, Debug)]
38pub struct RegionNormalizer {
39    image: Digest,
40    chain: TransformChain,
41    frame: CoordFrame,
42    backend: BackendId,
43    manifest: Option<String>,
44}
45
46impl RegionNormalizer {
47    /// A normalizer for answers about the source image `image`, seen through `chain`, given
48    /// in `frame` by `backend`.
49    pub fn new(
50        image: Digest,
51        chain: TransformChain,
52        frame: CoordFrame,
53        backend: BackendId,
54    ) -> Self {
55        Self { image, chain, frame, backend, manifest: None }
56    }
57
58    /// Names the model manifest entry the backend ran.
59    pub fn with_manifest(mut self, manifest: Option<String>) -> Self {
60        self.manifest = manifest;
61        self
62    }
63
64    /// The transform chain.
65    pub fn chain(&self) -> &TransformChain {
66        &self.chain
67    }
68
69    /// The origin every region from this normalizer carries.
70    pub fn origin(&self) -> RegionOrigin {
71        RegionOrigin {
72            backend: self.backend.clone(),
73            manifest: self.manifest.clone(),
74            frame: self.frame,
75            chain: self.chain.clone(),
76            escalated_from: None,
77        }
78    }
79
80    /// Maps a shape from the backend's frame to source pixels, clamped to the source image.
81    ///
82    /// # Errors
83    ///
84    /// Returns [`VisionError::Parse`] for a mask in a frame with no raster, or of the wrong
85    /// size, and for a non-finite coordinate.
86    pub fn shape(&self, raw: &Shape) -> Result<Shape> {
87        let sent = self.chain.output_size();
88        let parse =
89            |message: String| VisionError::Parse { backend: self.backend.to_string(), message };
90        let to_sent = |x: f32, y: f32| -> Result<[f32; 2]> {
91            if !x.is_finite() || !y.is_finite() {
92                return Err(parse(format!("coordinate ({x}, {y}) is not finite")));
93            }
94            let p = self.frame.point_to_sent([f64::from(x), f64::from(y)], sent);
95            Ok([p[0] as f32, p[1] as f32])
96        };
97        let in_sent = match raw {
98            Shape::Point(p) => {
99                let [x, y] = to_sent(p.x, p.y)?;
100                Shape::Point(Point2 { x, y })
101            }
102            Shape::Box(b) => {
103                let a = to_sent(b.x0, b.y0)?;
104                let c = to_sent(b.x1, b.y1)?;
105                Shape::Box(BBox::new(a[0], a[1], c[0], c[1]))
106            }
107            Shape::Polygon(poly) => Shape::Polygon(Polygon {
108                points: poly.points.iter().map(|p| to_sent(p[0], p[1])).collect::<Result<_>>()?,
109            }),
110            Shape::Keypoints(k) => Shape::Keypoints(Keypoints {
111                skeleton: k.skeleton.clone(),
112                points: k
113                    .points
114                    .iter()
115                    .map(|kp| {
116                        let [x, y] = to_sent(kp.x, kp.y)?;
117                        Ok(Keypoint { x, y, ..*kp })
118                    })
119                    .collect::<Result<_>>()?,
120            }),
121            Shape::Mask(mask) => {
122                let Some(raster) = self.frame.mask_raster(sent) else {
123                    return Err(parse(format!(
124                        "a mask cannot be given in the {:?} frame; convert it to sent pixels first",
125                        self.frame
126                    )));
127                };
128                if (mask.width, mask.height) != raster {
129                    return Err(parse(format!(
130                        "a {}x{} mask does not match the {}x{} raster of its frame",
131                        mask.width, mask.height, raster.0, raster.1
132                    )));
133                }
134                match self.frame {
135                    CoordFrame::SentPixels => Shape::Mask(mask.clone()),
136                    frame => Shape::Mask(resample(
137                        mask,
138                        sent,
139                        |p| frame.point_from_sent(p, sent),
140                        |p| frame.point_to_sent(p, sent),
141                    )),
142                }
143            }
144        };
145        let source = self.chain.shape_to_source(&in_sent)?;
146        Ok(clamp(source, self.chain.source_width, self.chain.source_height))
147    }
148
149    /// Turns one raw region into a region of the source image, or `None` when nothing of it
150    /// lies inside the image.
151    ///
152    /// # Errors
153    ///
154    /// As [`shape`](Self::shape).
155    pub fn region(&self, raw: RawRegion) -> Result<Option<Region>> {
156        let shape = self.shape(&raw.shape)?;
157        let empty = match &shape {
158            Shape::Box(b) => b.is_empty(),
159            Shape::Mask(m) => m.area() == 0,
160            _ => false,
161        };
162        if empty {
163            return Ok(None);
164        }
165        Ok(Some(Region {
166            image: self.image,
167            shape,
168            label: raw.label,
169            score: raw.score,
170            track: raw.track,
171            origin: self.origin(),
172        }))
173    }
174
175    /// Turns raw regions into regions of the source image, dropping those outside it.
176    ///
177    /// # Errors
178    ///
179    /// As [`shape`](Self::shape).
180    pub fn regions(&self, raw: Vec<RawRegion>) -> Result<Vec<Region>> {
181        let mut regions = Vec::with_capacity(raw.len());
182        for r in raw {
183            if let Some(region) = self.region(r)? {
184                regions.push(region);
185            }
186        }
187        Ok(regions)
188    }
189}
190
191fn clamp(shape: Shape, width: u32, height: u32) -> Shape {
192    let (w, h) = (width as f32, height as f32);
193    let pt = |x: f32, y: f32| [x.clamp(0.0, w), y.clamp(0.0, h)];
194    match shape {
195        Shape::Point(p) => {
196            let [x, y] = pt(p.x, p.y);
197            Shape::Point(Point2 { x, y })
198        }
199        Shape::Box(b) => Shape::Box(b.clamped(width, height)),
200        Shape::Polygon(poly) => {
201            Shape::Polygon(Polygon { points: poly.points.iter().map(|p| pt(p[0], p[1])).collect() })
202        }
203        Shape::Keypoints(k) => Shape::Keypoints(Keypoints {
204            skeleton: k.skeleton,
205            points: k
206                .points
207                .into_iter()
208                .map(|kp| {
209                    let [x, y] = pt(kp.x, kp.y);
210                    Keypoint { x, y, ..kp }
211                })
212                .collect(),
213        }),
214        mask @ Shape::Mask(_) => mask,
215    }
216}