mod frame;
mod mask;
mod normalize;
mod screen;
mod transform;
use serde::{Deserialize, Serialize};
pub use frame::{AxisOrder, CoordFrame, Letterbox, LetterboxGeometry};
pub use mask::Mask;
pub use normalize::RegionNormalizer;
pub use screen::ScreenSpace;
pub(crate) use transform::resample;
pub use transform::{Transform, TransformChain};
use crate::backend::BackendId;
use crate::digest::Digest;
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct BBox {
pub x0: f32,
pub y0: f32,
pub x1: f32,
pub y1: f32,
}
impl BBox {
pub fn new(x0: f32, y0: f32, x1: f32, y1: f32) -> Self {
Self { x0: x0.min(x1), y0: y0.min(y1), x1: x0.max(x1), y1: y0.max(y1) }
}
pub fn from_xywh(x: f32, y: f32, width: f32, height: f32) -> Self {
Self::new(x, y, x + width, y + height)
}
pub fn width(&self) -> f32 {
(self.x1 - self.x0).max(0.0)
}
pub fn height(&self) -> f32 {
(self.y1 - self.y0).max(0.0)
}
pub fn area(&self) -> f32 {
self.width() * self.height()
}
pub fn center(&self) -> [f32; 2] {
[(self.x0 + self.x1) / 2.0, (self.y0 + self.y1) / 2.0]
}
pub fn is_empty(&self) -> bool {
self.width() <= 0.0 || self.height() <= 0.0
}
pub fn intersection(&self, other: &Self) -> Option<Self> {
let b = Self {
x0: self.x0.max(other.x0),
y0: self.y0.max(other.y0),
x1: self.x1.min(other.x1),
y1: self.y1.min(other.y1),
};
(!b.is_empty()).then_some(b)
}
pub fn iou(&self, other: &Self) -> f32 {
let inter = self.intersection(other).map_or(0.0, |b| b.area());
let union = self.area() + other.area() - inter;
if union <= 0.0 { 0.0 } else { inter / union }
}
pub fn clamped(&self, width: u32, height: u32) -> Self {
let (w, h) = (width as f32, height as f32);
Self {
x0: self.x0.clamp(0.0, w),
y0: self.y0.clamp(0.0, h),
x1: self.x1.clamp(0.0, w),
y1: self.y1.clamp(0.0, h),
}
}
pub fn expanded(&self, margin: f32) -> Self {
Self::new(self.x0 - margin, self.y0 - margin, self.x1 + margin, self.y1 + margin)
}
pub fn contains(&self, point: [f32; 2]) -> bool {
point[0] >= self.x0 && point[0] < self.x1 && point[1] >= self.y0 && point[1] < self.y1
}
pub fn is_within(&self, width: u32, height: u32) -> bool {
self.x0 >= 0.0
&& self.y0 >= 0.0
&& self.x1 <= width as f32
&& self.y1 <= height as f32
&& self.x0 <= self.x1
&& self.y0 <= self.y1
}
pub fn pixel_bounds(&self, width: u32, height: u32) -> (u32, u32, u32, u32) {
let c = self.clamped(width, height);
let x0 = c.x0.floor() as u32;
let y0 = c.y0.floor() as u32;
let x1 = (c.x1.ceil() as u32).min(width);
let y1 = (c.y1.ceil() as u32).min(height);
(x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
}
pub fn covering(points: impl IntoIterator<Item = [f32; 2]>) -> Option<Self> {
let mut iter = points.into_iter();
let first = iter.next()?;
let mut b = Self { x0: first[0], y0: first[1], x1: first[0], y1: first[1] };
for [x, y] in iter {
b.x0 = b.x0.min(x);
b.y0 = b.y0.min(y);
b.x1 = b.x1.max(x);
b.y1 = b.y1.max(y);
}
Some(b)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Point2 {
pub x: f32,
pub y: f32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Polygon {
pub points: Vec<[f32; 2]>,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Keypoint {
pub x: f32,
pub y: f32,
pub visible: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub score: Option<f32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Keypoints {
pub skeleton: String,
pub points: Vec<Keypoint>,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum Shape {
Point(Point2),
Box(BBox),
Polygon(Polygon),
Mask(Mask),
Keypoints(Keypoints),
}
impl Shape {
pub fn bbox(&self) -> Option<BBox> {
match self {
Self::Point(p) => Some(BBox { x0: p.x, y0: p.y, x1: p.x, y1: p.y }),
Self::Box(b) => Some(*b),
Self::Polygon(p) => BBox::covering(p.points.iter().copied()),
Self::Mask(m) => m.bbox(),
Self::Keypoints(k) => BBox::covering(k.points.iter().map(|p| [p.x, p.y])),
}
}
pub fn is_within(&self, width: u32, height: u32) -> bool {
let inside = |[x, y]: [f32; 2]| {
(0.0..=width as f32).contains(&x) && (0.0..=height as f32).contains(&y)
};
match self {
Self::Point(p) => inside([p.x, p.y]),
Self::Box(b) => b.is_within(width, height),
Self::Polygon(p) => p.points.iter().copied().all(inside),
Self::Mask(m) => m.width == width && m.height == height,
Self::Keypoints(k) => k.points.iter().all(|p| inside([p.x, p.y])),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TrackId(pub u64);
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum EscalationReason {
LowConfidence {
threshold: f32,
},
NoResult,
Disagreement {
with: BackendId,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EscalatedFrom {
pub backend: BackendId,
pub reason: EscalationReason,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub score: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegionOrigin {
pub backend: BackendId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manifest: Option<String>,
pub frame: CoordFrame,
pub chain: TransformChain,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub escalated_from: Option<EscalatedFrom>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Region {
pub image: Digest,
pub shape: Shape,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub score: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub track: Option<TrackId>,
pub origin: RegionOrigin,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RawRegion {
pub shape: Shape,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub score: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub track: Option<TrackId>,
}
impl RawRegion {
pub fn boxed(bbox: BBox, label: impl Into<String>, score: f32) -> Self {
Self { shape: Shape::Box(bbox), label: Some(label.into()), score: Some(score), track: None }
}
pub fn shape(shape: Shape) -> Self {
Self { shape, label: None, score: None, track: None }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegionSet {
pub image: Digest,
pub width: u32,
pub height: u32,
pub regions: Vec<Region>,
}
impl RegionSet {
pub fn new(image: Digest, width: u32, height: u32, regions: Vec<Region>) -> Self {
Self { image, width, height, regions }
}
pub fn validate(&self) -> crate::Result<()> {
for (index, region) in self.regions.iter().enumerate() {
if region.image != self.image {
return Err(crate::VisionError::InvalidInput(format!(
"region {index} belongs to image {}, not {}",
region.image, self.image
)));
}
if !region.shape.is_within(self.width, self.height) {
return Err(crate::VisionError::InvalidInput(format!(
"region {index} lies outside the {}x{} image",
self.width, self.height
)));
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Track {
pub id: TrackId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
pub observations: Vec<(u64, Region)>,
}