1mod 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#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
42pub struct BBox {
43 pub x0: f32,
45 pub y0: f32,
47 pub x1: f32,
49 pub y1: f32,
51}
52
53impl BBox {
54 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 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 pub fn width(&self) -> f32 {
66 (self.x1 - self.x0).max(0.0)
67 }
68
69 pub fn height(&self) -> f32 {
71 (self.y1 - self.y0).max(0.0)
72 }
73
74 pub fn area(&self) -> f32 {
76 self.width() * self.height()
77 }
78
79 pub fn center(&self) -> [f32; 2] {
81 [(self.x0 + self.x1) / 2.0, (self.y0 + self.y1) / 2.0]
82 }
83
84 pub fn is_empty(&self) -> bool {
86 self.width() <= 0.0 || self.height() <= 0.0
87 }
88
89 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 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 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 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 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 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
166pub struct Point2 {
167 pub x: f32,
169 pub y: f32,
171}
172
173#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
175pub struct Polygon {
176 pub points: Vec<[f32; 2]>,
178}
179
180#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
182pub struct Keypoint {
183 pub x: f32,
185 pub y: f32,
187 pub visible: bool,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub score: Option<f32>,
192}
193
194#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
196pub struct Keypoints {
197 pub skeleton: String,
199 pub points: Vec<Keypoint>,
201}
202
203#[non_exhaustive]
207#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase", tag = "kind")]
209pub enum Shape {
210 Point(Point2),
212 Box(BBox),
214 Polygon(Polygon),
216 Mask(Mask),
218 Keypoints(Keypoints),
220}
221
222impl Shape {
223 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
251#[serde(transparent)]
252pub struct TrackId(pub u64);
253
254#[non_exhaustive]
256#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase", tag = "kind")]
258pub enum EscalationReason {
259 LowConfidence {
261 threshold: f32,
263 },
264 NoResult,
266 Disagreement {
268 with: BackendId,
270 },
271}
272
273#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276pub struct EscalatedFrom {
277 pub backend: BackendId,
279 pub reason: EscalationReason,
281 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub label: Option<String>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
286 pub score: Option<f32>,
287 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub text: Option<String>,
290}
291
292#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
295#[serde(rename_all = "camelCase")]
296pub struct RegionOrigin {
297 pub backend: BackendId,
299 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub manifest: Option<String>,
302 pub frame: CoordFrame,
304 pub chain: TransformChain,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub escalated_from: Option<EscalatedFrom>,
309}
310
311#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct Region {
315 pub image: Digest,
317 pub shape: Shape,
319 #[serde(default, skip_serializing_if = "Option::is_none")]
321 pub label: Option<String>,
322 #[serde(default, skip_serializing_if = "Option::is_none")]
324 pub score: Option<f32>,
325 #[serde(default, skip_serializing_if = "Option::is_none")]
327 pub track: Option<TrackId>,
328 pub origin: RegionOrigin,
330}
331
332#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
338#[serde(rename_all = "camelCase")]
339pub struct RawRegion {
340 pub shape: Shape,
344 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub label: Option<String>,
347 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub score: Option<f32>,
350 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub track: Option<TrackId>,
353}
354
355impl RawRegion {
356 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 pub fn shape(shape: Shape) -> Self {
372 Self { shape, label: None, score: None, track: None }
373 }
374}
375
376#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
393#[serde(rename_all = "camelCase")]
394pub struct RegionSet {
395 pub image: Digest,
397 pub width: u32,
399 pub height: u32,
401 pub regions: Vec<Region>,
403}
404
405impl RegionSet {
406 pub fn new(image: Digest, width: u32, height: u32, regions: Vec<Region>) -> Self {
408 Self { image, width, height, regions }
409 }
410
411 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
438#[serde(rename_all = "camelCase")]
439pub struct Track {
440 pub id: TrackId,
442 #[serde(default, skip_serializing_if = "Option::is_none")]
444 pub label: Option<String>,
445 pub observations: Vec<(u64, Region)>,
447}