Skip to main content

adk_vision/geometry/
mod.rs

1//! Geometry and regions (spec 3.7 §7.3).
2//!
3//! Every [`Region`] is in source-image pixels — origin top-left, x right, y down — and
4//! carries its [`RegionOrigin`]: the backend, the [`CoordFrame`] it answered in, and the
5//! [`TransformChain`] between the source image and what the backend saw. Backends answer
6//! with [`RawRegion`]s in their own frame; only the runtime turns them into `Region`s
7//! ([`RegionNormalizer`]), so no region crosses a component boundary in a provider's frame
8//! (V-I13).
9
10mod frame;
11mod mask;
12mod normalize;
13mod screen;
14mod transform;
15
16use serde::{Deserialize, Serialize};
17
18pub use frame::{AxisOrder, CoordFrame, Letterbox, LetterboxGeometry};
19pub use mask::Mask;
20pub use normalize::RegionNormalizer;
21pub use screen::ScreenSpace;
22pub(crate) use transform::resample;
23pub use transform::{Transform, TransformChain};
24
25use crate::backend::BackendId;
26use crate::digest::Digest;
27
28/// An axis-aligned box: origin top-left, x right, y down; `x1` and `y1` exclusive.
29///
30/// # Example
31///
32/// ```
33/// use adk_vision::BBox;
34///
35/// let a = BBox::new(0.0, 0.0, 10.0, 10.0);
36/// let b = BBox::new(5.0, 0.0, 15.0, 10.0);
37/// assert_eq!(a.area(), 100.0);
38/// assert!((a.iou(&b) - 1.0 / 3.0).abs() < 1e-6);
39/// assert_eq!(BBox::new(-5.0, 2.0, 50.0, 8.0).clamped(20, 20), BBox::new(0.0, 2.0, 20.0, 8.0));
40/// ```
41#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
42pub struct BBox {
43    /// Left edge.
44    pub x0: f32,
45    /// Top edge.
46    pub y0: f32,
47    /// Right edge, exclusive.
48    pub x1: f32,
49    /// Bottom edge, exclusive.
50    pub y1: f32,
51}
52
53impl BBox {
54    /// A box from its edges; the edges are reordered so `x0 <= x1` and `y0 <= y1`.
55    pub fn new(x0: f32, y0: f32, x1: f32, y1: f32) -> Self {
56        Self { x0: x0.min(x1), y0: y0.min(y1), x1: x0.max(x1), y1: y0.max(y1) }
57    }
58
59    /// A box from its top-left corner and size.
60    pub fn from_xywh(x: f32, y: f32, width: f32, height: f32) -> Self {
61        Self::new(x, y, x + width, y + height)
62    }
63
64    /// Width, zero for an inverted box.
65    pub fn width(&self) -> f32 {
66        (self.x1 - self.x0).max(0.0)
67    }
68
69    /// Height, zero for an inverted box.
70    pub fn height(&self) -> f32 {
71        (self.y1 - self.y0).max(0.0)
72    }
73
74    /// Area in square pixels.
75    pub fn area(&self) -> f32 {
76        self.width() * self.height()
77    }
78
79    /// The centre point.
80    pub fn center(&self) -> [f32; 2] {
81        [(self.x0 + self.x1) / 2.0, (self.y0 + self.y1) / 2.0]
82    }
83
84    /// `true` when the box has no area.
85    pub fn is_empty(&self) -> bool {
86        self.width() <= 0.0 || self.height() <= 0.0
87    }
88
89    /// The overlap of two boxes, if any.
90    pub fn intersection(&self, other: &Self) -> Option<Self> {
91        let b = Self {
92            x0: self.x0.max(other.x0),
93            y0: self.y0.max(other.y0),
94            x1: self.x1.min(other.x1),
95            y1: self.y1.min(other.y1),
96        };
97        (!b.is_empty()).then_some(b)
98    }
99
100    /// Intersection over union, `0.0` for disjoint boxes.
101    pub fn iou(&self, other: &Self) -> f32 {
102        let inter = self.intersection(other).map_or(0.0, |b| b.area());
103        let union = self.area() + other.area() - inter;
104        if union <= 0.0 { 0.0 } else { inter / union }
105    }
106
107    /// The box clamped to an image of `width` × `height`.
108    pub fn clamped(&self, width: u32, height: u32) -> Self {
109        let (w, h) = (width as f32, height as f32);
110        Self {
111            x0: self.x0.clamp(0.0, w),
112            y0: self.y0.clamp(0.0, h),
113            x1: self.x1.clamp(0.0, w),
114            y1: self.y1.clamp(0.0, h),
115        }
116    }
117
118    /// The box grown by `margin` pixels on every side.
119    pub fn expanded(&self, margin: f32) -> Self {
120        Self::new(self.x0 - margin, self.y0 - margin, self.x1 + margin, self.y1 + margin)
121    }
122
123    /// `true` when the point lies inside the box.
124    pub fn contains(&self, point: [f32; 2]) -> bool {
125        point[0] >= self.x0 && point[0] < self.x1 && point[1] >= self.y0 && point[1] < self.y1
126    }
127
128    /// `true` when the box lies within an image of `width` × `height`.
129    pub fn is_within(&self, width: u32, height: u32) -> bool {
130        self.x0 >= 0.0
131            && self.y0 >= 0.0
132            && self.x1 <= width as f32
133            && self.y1 <= height as f32
134            && self.x0 <= self.x1
135            && self.y0 <= self.y1
136    }
137
138    /// The smallest whole-pixel rectangle covering the box, clamped to the image:
139    /// `(x, y, width, height)`.
140    pub fn pixel_bounds(&self, width: u32, height: u32) -> (u32, u32, u32, u32) {
141        let c = self.clamped(width, height);
142        let x0 = c.x0.floor() as u32;
143        let y0 = c.y0.floor() as u32;
144        let x1 = (c.x1.ceil() as u32).min(width);
145        let y1 = (c.y1.ceil() as u32).min(height);
146        (x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
147    }
148
149    /// The smallest box covering every point, or `None` for no points.
150    pub fn covering(points: impl IntoIterator<Item = [f32; 2]>) -> Option<Self> {
151        let mut iter = points.into_iter();
152        let first = iter.next()?;
153        let mut b = Self { x0: first[0], y0: first[1], x1: first[0], y1: first[1] };
154        for [x, y] in iter {
155            b.x0 = b.x0.min(x);
156            b.y0 = b.y0.min(y);
157            b.x1 = b.x1.max(x);
158            b.y1 = b.y1.max(y);
159        }
160        Some(b)
161    }
162}
163
164/// A point in pixels.
165#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
166pub struct Point2 {
167    /// Horizontal position.
168    pub x: f32,
169    /// Vertical position.
170    pub y: f32,
171}
172
173/// A closed polygon, vertices in order.
174#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
175pub struct Polygon {
176    /// The vertices as `[x, y]`.
177    pub points: Vec<[f32; 2]>,
178}
179
180/// One keypoint of a skeleton.
181#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
182pub struct Keypoint {
183    /// Horizontal position.
184    pub x: f32,
185    /// Vertical position.
186    pub y: f32,
187    /// Whether the point is visible.
188    pub visible: bool,
189    /// The model's confidence, when it gives one.
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub score: Option<f32>,
192}
193
194/// Keypoints of a named skeleton, such as `coco-17`.
195#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
196pub struct Keypoints {
197    /// The skeleton the points follow.
198    pub skeleton: String,
199    /// The points, in the skeleton's order.
200    pub points: Vec<Keypoint>,
201}
202
203/// The geometry of something found in an image.
204///
205/// Serialized with a `kind` tag: `{"kind": "box", "x0": 1, ...}`.
206#[non_exhaustive]
207#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase", tag = "kind")]
209pub enum Shape {
210    /// A single point.
211    Point(Point2),
212    /// An axis-aligned box.
213    Box(BBox),
214    /// A polygon.
215    Polygon(Polygon),
216    /// A binary mask at the resolution of the frame it is in.
217    Mask(Mask),
218    /// Keypoints of a skeleton.
219    Keypoints(Keypoints),
220}
221
222impl Shape {
223    /// The smallest box covering the shape, or `None` for an empty one.
224    pub fn bbox(&self) -> Option<BBox> {
225        match self {
226            Self::Point(p) => Some(BBox { x0: p.x, y0: p.y, x1: p.x, y1: p.y }),
227            Self::Box(b) => Some(*b),
228            Self::Polygon(p) => BBox::covering(p.points.iter().copied()),
229            Self::Mask(m) => m.bbox(),
230            Self::Keypoints(k) => BBox::covering(k.points.iter().map(|p| [p.x, p.y])),
231        }
232    }
233
234    /// `true` when every coordinate lies within an image of `width` × `height`.
235    pub fn is_within(&self, width: u32, height: u32) -> bool {
236        let inside = |[x, y]: [f32; 2]| {
237            (0.0..=width as f32).contains(&x) && (0.0..=height as f32).contains(&y)
238        };
239        match self {
240            Self::Point(p) => inside([p.x, p.y]),
241            Self::Box(b) => b.is_within(width, height),
242            Self::Polygon(p) => p.points.iter().copied().all(inside),
243            Self::Mask(m) => m.width == width && m.height == height,
244            Self::Keypoints(k) => k.points.iter().all(|p| inside([p.x, p.y])),
245        }
246    }
247}
248
249/// An anonymous track identifier; identifiers reset with their source session (V-I8).
250#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
251#[serde(transparent)]
252pub struct TrackId(pub u64);
253
254/// Why a region or value came from an escalation backend.
255#[non_exhaustive]
256#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase", tag = "kind")]
258pub enum EscalationReason {
259    /// The primary's score was below the route's threshold.
260    LowConfidence {
261        /// The threshold.
262        threshold: f32,
263    },
264    /// The primary found nothing.
265    NoResult,
266    /// A second local backend disagreed with the primary.
267    Disagreement {
268        /// The backend that disagreed.
269        with: BackendId,
270    },
271}
272
273/// The primary backend's answer an escalation replaced.
274#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276pub struct EscalatedFrom {
277    /// The primary backend.
278    pub backend: BackendId,
279    /// Why the runtime escalated.
280    pub reason: EscalationReason,
281    /// The primary's label, when it gave one.
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub label: Option<String>,
284    /// The primary's score, when it gave one.
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub score: Option<f32>,
287    /// The primary's text, for document blocks.
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub text: Option<String>,
290}
291
292/// Where a region came from: backend, model, the frame it answered in, the transforms
293/// between the source image and what the backend saw, and any escalation.
294#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
295#[serde(rename_all = "camelCase")]
296pub struct RegionOrigin {
297    /// The backend that produced the region.
298    pub backend: BackendId,
299    /// The model manifest entry, for model-backed backends.
300    #[serde(default, skip_serializing_if = "Option::is_none")]
301    pub manifest: Option<String>,
302    /// The coordinate frame the backend answered in.
303    pub frame: CoordFrame,
304    /// The transforms from the source image to the image the backend saw.
305    pub chain: TransformChain,
306    /// The primary answer this region replaced, when it came from an escalation.
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub escalated_from: Option<EscalatedFrom>,
309}
310
311/// Something found in one image, always in that image's pixels.
312#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct Region {
315    /// The source image this region belongs to.
316    pub image: Digest,
317    /// The geometry, in source pixels.
318    pub shape: Shape,
319    /// The class or concept, when there is one.
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    pub label: Option<String>,
322    /// The backend's confidence in `[0, 1]`, when it gives one.
323    #[serde(default, skip_serializing_if = "Option::is_none")]
324    pub score: Option<f32>,
325    /// The track this region belongs to, across frames.
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub track: Option<TrackId>,
328    /// Backend, model manifest entry, frame and transform chain.
329    pub origin: RegionOrigin,
330}
331
332/// What a backend answers: a shape in its descriptor's [`CoordFrame`], with x horizontal
333/// and y vertical whatever the provider's wire order.
334///
335/// The runtime turns every `RawRegion` into a [`Region`] in source pixels
336/// ([`RegionNormalizer`]); a raw region never leaves the call that produced it.
337#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
338#[serde(rename_all = "camelCase")]
339pub struct RawRegion {
340    /// The geometry, in the backend's frame. A mask's size is the frame's raster: the sent
341    /// image for `SentPixels`, `scale` × `scale` for `Normalized`, the model input for
342    /// `ModelInput`.
343    pub shape: Shape,
344    /// The class or concept.
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub label: Option<String>,
347    /// The backend's confidence in `[0, 1]`.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub score: Option<f32>,
350    /// A track identifier the backend assigned.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub track: Option<TrackId>,
353}
354
355impl RawRegion {
356    /// A box with a label and score.
357    ///
358    /// # Example
359    ///
360    /// ```
361    /// use adk_vision::{BBox, RawRegion};
362    ///
363    /// let raw = RawRegion::boxed(BBox::new(1.0, 2.0, 3.0, 4.0), "seal", 0.9);
364    /// assert_eq!(raw.label.as_deref(), Some("seal"));
365    /// ```
366    pub fn boxed(bbox: BBox, label: impl Into<String>, score: f32) -> Self {
367        Self { shape: Shape::Box(bbox), label: Some(label.into()), score: Some(score), track: None }
368    }
369
370    /// A region with this shape and nothing else.
371    pub fn shape(shape: Shape) -> Self {
372        Self { shape, label: None, score: None, track: None }
373    }
374}
375
376/// The wire form of an image's regions: the image's digest and dimensions, and its regions.
377///
378/// Published as a JSON Schema in `adk-vision/schema/region-set.json`; approval evidence,
379/// eval cases and surfaces use it, and `adk-surface` draws it without depending on this
380/// crate.
381///
382/// # Example
383///
384/// ```
385/// use adk_vision::{Digest, RegionSet};
386///
387/// let set = RegionSet::new(Digest::of(b"png bytes"), 640, 480, Vec::new());
388/// let json = serde_json::to_value(&set).unwrap();
389/// assert_eq!(json["width"], 640);
390/// assert!(set.validate().is_ok());
391/// ```
392#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
393#[serde(rename_all = "camelCase")]
394pub struct RegionSet {
395    /// The source image's digest.
396    pub image: Digest,
397    /// The source image's width in pixels.
398    pub width: u32,
399    /// The source image's height in pixels.
400    pub height: u32,
401    /// The regions, each in the source image's pixels.
402    pub regions: Vec<Region>,
403}
404
405impl RegionSet {
406    /// A region set for an image.
407    pub fn new(image: Digest, width: u32, height: u32, regions: Vec<Region>) -> Self {
408        Self { image, width, height, regions }
409    }
410
411    /// Checks that every region belongs to the image and lies within it.
412    ///
413    /// # Errors
414    ///
415    /// Returns [`VisionError::InvalidInput`](crate::VisionError::InvalidInput) naming the
416    /// first region that does not.
417    pub fn validate(&self) -> crate::Result<()> {
418        for (index, region) in self.regions.iter().enumerate() {
419            if region.image != self.image {
420                return Err(crate::VisionError::InvalidInput(format!(
421                    "region {index} belongs to image {}, not {}",
422                    region.image, self.image
423                )));
424            }
425            if !region.shape.is_within(self.width, self.height) {
426                return Err(crate::VisionError::InvalidInput(format!(
427                    "region {index} lies outside the {}x{} image",
428                    self.width, self.height
429                )));
430            }
431        }
432        Ok(())
433    }
434}
435
436/// One object across frames. Identifiers are anonymous and reset with the source session.
437#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
438#[serde(rename_all = "camelCase")]
439pub struct Track {
440    /// The track's identifier.
441    pub id: TrackId,
442    /// The object's label.
443    #[serde(default, skip_serializing_if = "Option::is_none")]
444    pub label: Option<String>,
445    /// `(frame index, region)` pairs, in frame order.
446    pub observations: Vec<(u64, Region)>,
447}