1use 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#[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 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 pub fn with_manifest(mut self, manifest: Option<String>) -> Self {
60 self.manifest = manifest;
61 self
62 }
63
64 pub fn chain(&self) -> &TransformChain {
66 &self.chain
67 }
68
69 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 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 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 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}