Skip to main content

adk_vision/measure/
mod.rs

1//! Calibration and measurement in one plane (spec 3.7 §7.13).
2//!
3//! A fiducial of known size lying in the measured plane gives the image's scale in pixels per
4//! millimetre ([`Calibration::from_fiducial`]); [`Calibration::measure`] then reports a
5//! region's maximum length (its maximum Feret diameter) and its area in millimetres, each
6//! with an uncertainty propagated from the calibration's.
7//!
8//! A single image holds no depth, so a measurement is valid only for an object lying in the
9//! fiducial's plane, seen by the same camera at the same image size ([`MEASUREMENT_VALIDITY`]).
10//! Depth arrives with the spatial outputs of phase D.
11//!
12//! # Uncertainty
13//!
14//! Each figure is one standard uncertainty, from these sources added in quadrature:
15//!
16//! | Quantity | Sources |
17//! |----------|---------|
18//! | Scale `k` (px/mm) | Each fiducial side located within ±1 px; the fiducial's printed tolerance; the difference between the scales its two sides give, which perspective and a tilted plane produce |
19//! | Maximum length | Each end located within half a pixel (±1 px over the length), and the scale's uncertainty |
20//! | Area | Half a pixel along the whole boundary, and twice the scale's relative uncertainty |
21//!
22//! # Example
23//!
24//! ```
25//! use adk_vision::{BBox, Calibration, FiducialSpec, Mask, Shape};
26//!
27//! // A 20 mm fiducial drawn 150 px wide at 7.5 px/mm in a 1600x1000 frame.
28//! let fiducial = Shape::Mask(Mask::from_box(1600, 1000, &BBox::new(100.0, 100.0, 250.0, 250.0)));
29//! let calibration = Calibration::from_fiducial(&fiducial, FiducialSpec::square(20.0), (1600, 1000)).unwrap();
30//! assert!((calibration.px_per_mm - 7.5).abs() < 1e-9);
31//!
32//! // A 3 px wide scratch 300 px long: 40 mm.
33//! let scratch = Shape::Mask(Mask::from_box(1600, 1000, &BBox::new(400.0, 500.0, 700.0, 503.0)));
34//! let measured = calibration.measure(&scratch, (1600, 1000)).unwrap();
35//! assert!((measured.longest_mm - 40.0).abs() < 0.05);
36//! assert!(measured.longest_uncertainty_mm > 0.0);
37//! assert!((measured.area_mm2 - 900.0 / 56.25).abs() < 1e-6);
38//! ```
39
40mod geometry;
41
42use serde::{Deserialize, Serialize};
43
44use crate::digest::Digest;
45use crate::error::{Result, VisionError};
46use crate::geometry::Shape;
47
48use geometry::{Outline, max_feret, min_area_rect};
49
50/// The words every measurement result carries: where it holds.
51pub const MEASUREMENT_VALIDITY: &str = "Valid only for objects lying in the plane of the \
52    calibration fiducial, seen by the same camera at the same image size: one image holds no \
53    depth, so anything nearer to or farther from the camera than the fiducial measures wrongly.";
54
55/// The fewest pixels a fiducial side may span: below it the ±1 px of locating each side is
56/// more than a tenth of the scale.
57const MIN_FIDUCIAL_PX: f64 = 10.0;
58
59/// The largest relative difference between the scales a fiducial's two sides give before
60/// the region is refused as not the fiducial, or the plane as tilted too far.
61const MAX_ANISOTROPY: f64 = 0.2;
62
63/// The physical size of a calibration fiducial: a printed square or rectangle.
64///
65/// # Example
66///
67/// ```
68/// use adk_vision::FiducialSpec;
69///
70/// let card = FiducialSpec::rectangle(85.6, 54.0).with_tolerance(0.1);
71/// assert!(card.validate().is_ok());
72/// assert!(FiducialSpec::square(-1.0).validate().is_err());
73/// ```
74#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76pub struct FiducialSpec {
77    /// Width in millimetres.
78    pub width_mm: f64,
79    /// Height in millimetres.
80    pub height_mm: f64,
81    /// The printed size's tolerance in millimetres, one standard uncertainty.
82    #[serde(default)]
83    pub tolerance_mm: f64,
84}
85
86impl FiducialSpec {
87    /// A square fiducial with sides of `size_mm`.
88    pub fn square(size_mm: f64) -> Self {
89        Self { width_mm: size_mm, height_mm: size_mm, tolerance_mm: 0.0 }
90    }
91
92    /// A rectangular fiducial.
93    pub fn rectangle(width_mm: f64, height_mm: f64) -> Self {
94        Self { width_mm, height_mm, tolerance_mm: 0.0 }
95    }
96
97    /// Sets the printed size's tolerance.
98    #[must_use]
99    pub fn with_tolerance(mut self, tolerance_mm: f64) -> Self {
100        self.tolerance_mm = tolerance_mm;
101        self
102    }
103
104    /// Checks the sizes: positive and finite, the tolerance smaller than either side.
105    ///
106    /// # Errors
107    ///
108    /// [`VisionError::InvalidInput`] naming the field.
109    pub fn validate(&self) -> Result<()> {
110        let positive = |v: f64| v.is_finite() && v > 0.0;
111        if !positive(self.width_mm) || !positive(self.height_mm) {
112            return Err(VisionError::InvalidInput(format!(
113                "a fiducial's size must be positive millimetres, not {} x {}",
114                self.width_mm, self.height_mm
115            )));
116        }
117        if !self.tolerance_mm.is_finite()
118            || self.tolerance_mm < 0.0
119            || self.tolerance_mm >= self.width_mm.min(self.height_mm)
120        {
121            return Err(VisionError::InvalidInput(format!(
122                "a fiducial's tolerance must be zero or more and smaller than its sides, not {}",
123                self.tolerance_mm
124            )));
125        }
126        Ok(())
127    }
128
129    fn sides(&self) -> [f64; 2] {
130        [self.width_mm.max(self.height_mm), self.width_mm.min(self.height_mm)]
131    }
132}
133
134/// Where a [`Calibration`]'s scale came from.
135#[non_exhaustive]
136#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
138pub enum CalibrationSource {
139    /// A fiducial of known size measured in the image.
140    Fiducial {
141        /// The fiducial's physical size.
142        spec: FiducialSpec,
143        /// Its sides as measured, in pixels, the longer first.
144        measured_px: [f64; 2],
145        /// The image it was measured in.
146        #[serde(default, skip_serializing_if = "Option::is_none")]
147        image: Option<Digest>,
148    },
149    /// A scale given directly, such as one an earlier fiducial gave.
150    Scale,
151}
152
153/// An image's scale in its measured plane: pixels per millimetre with its uncertainty, for
154/// images of one size.
155///
156/// The `measure` module documentation describes the uncertainty model and has an example.
157#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase")]
159pub struct Calibration {
160    /// Pixels per millimetre in the measured plane.
161    pub px_per_mm: f64,
162    /// One standard uncertainty of `px_per_mm`.
163    pub uncertainty_px_per_mm: f64,
164    /// The width of the images the calibration holds for.
165    pub image_width: u32,
166    /// The height of the images the calibration holds for.
167    pub image_height: u32,
168    /// Where the scale came from.
169    pub source: CalibrationSource,
170}
171
172impl Calibration {
173    /// The scale a fiducial of `spec`'s size gives, from its region in an image of
174    /// `image_size`: the sides of the smallest rectangle enclosing the region, matched long
175    /// to long, so a fiducial at any rotation calibrates.
176    ///
177    /// # Errors
178    ///
179    /// [`VisionError::InvalidInput`] for an invalid spec, a region outside the image or with
180    /// no area, a side under 10 px, or sides whose scales differ by more than 20% (the
181    /// region is not the fiducial, or the plane is tilted too far to measure in).
182    pub fn from_fiducial(
183        shape: &Shape,
184        spec: FiducialSpec,
185        image_size: (u32, u32),
186    ) -> Result<Self> {
187        spec.validate()?;
188        within(shape, image_size)?;
189        let outline = Outline::of(shape)?;
190        let [long_px, short_px] = min_area_rect(&outline.hull);
191        if short_px < MIN_FIDUCIAL_PX {
192            return Err(VisionError::InvalidInput(format!(
193                "the fiducial spans {short_px:.1} px on its short side; it needs at least \
194                 {MIN_FIDUCIAL_PX} px to calibrate: move the camera closer or use a larger fiducial"
195            )));
196        }
197        let [long_mm, short_mm] = spec.sides();
198        let (k_long, k_short) = (long_px / long_mm, short_px / short_mm);
199        let k = (k_long + k_short) / 2.0;
200        let anisotropy = (k_long - k_short).abs() / k;
201        if anisotropy > MAX_ANISOTROPY {
202            return Err(VisionError::InvalidInput(format!(
203                "the fiducial measures {long_px:.1} x {short_px:.1} px, which does not match its \
204                 {long_mm} x {short_mm} mm shape within {}%: the region is not the fiducial, or \
205                 the plane is tilted too far to measure in",
206                MAX_ANISOTROPY * 100.0
207            )));
208        }
209        let quantisation = 0.5 * ((1.0 / long_mm).powi(2) + (1.0 / short_mm).powi(2)).sqrt();
210        let tolerance = k * spec.tolerance_mm / ((long_mm + short_mm) / 2.0);
211        let perspective = (k_long - k_short).abs() / 2.0;
212        let uncertainty = (quantisation.powi(2) + tolerance.powi(2) + perspective.powi(2)).sqrt();
213        Ok(Self {
214            px_per_mm: k,
215            uncertainty_px_per_mm: uncertainty,
216            image_width: image_size.0,
217            image_height: image_size.1,
218            source: CalibrationSource::Fiducial {
219                spec,
220                measured_px: [long_px, short_px],
221                image: None,
222            },
223        })
224    }
225
226    /// A scale given directly, such as one an earlier fiducial gave for this camera.
227    ///
228    /// # Errors
229    ///
230    /// [`VisionError::InvalidInput`] for a scale that is not positive and finite, or an
231    /// uncertainty that is negative or not finite.
232    pub fn from_scale(
233        px_per_mm: f64,
234        uncertainty_px_per_mm: f64,
235        image_size: (u32, u32),
236    ) -> Result<Self> {
237        if !px_per_mm.is_finite() || px_per_mm <= 0.0 {
238            return Err(VisionError::InvalidInput(format!(
239                "a scale must be positive pixels per millimetre, not {px_per_mm}"
240            )));
241        }
242        if !uncertainty_px_per_mm.is_finite() || uncertainty_px_per_mm < 0.0 {
243            return Err(VisionError::InvalidInput(format!(
244                "a scale's uncertainty must be zero or more, not {uncertainty_px_per_mm}"
245            )));
246        }
247        Ok(Self {
248            px_per_mm,
249            uncertainty_px_per_mm,
250            image_width: image_size.0,
251            image_height: image_size.1,
252            source: CalibrationSource::Scale,
253        })
254    }
255
256    /// Records the image a fiducial was measured in.
257    #[must_use]
258    pub fn with_image(mut self, digest: Digest) -> Self {
259        if let CalibrationSource::Fiducial { image, .. } = &mut self.source {
260            *image = Some(digest);
261        }
262        self
263    }
264
265    /// The scale's relative uncertainty.
266    pub fn relative_uncertainty(&self) -> f64 {
267        self.uncertainty_px_per_mm / self.px_per_mm
268    }
269
270    /// The reference the scale rests on, `(millimetres, pixels)`: the fiducial's long side
271    /// and its measured length, or one millimetre and the scale.
272    pub fn reference(&self) -> (f64, f64) {
273        match &self.source {
274            CalibrationSource::Fiducial { spec, measured_px, .. } => {
275                (spec.sides()[0], measured_px[0])
276            }
277            CalibrationSource::Scale => (1.0, self.px_per_mm),
278        }
279    }
280
281    /// Measures `shape`, in the pixels of an image of `image_size`: its maximum length and
282    /// area, with their uncertainties. Valid only in the calibrated plane
283    /// ([`MEASUREMENT_VALIDITY`]).
284    ///
285    /// # Errors
286    ///
287    /// [`VisionError::InvalidInput`] for an image of another size than the calibration's, a
288    /// region outside the image, or a shape with no area (a point, keypoints, an empty mask).
289    pub fn measure(&self, shape: &Shape, image_size: (u32, u32)) -> Result<Measurement> {
290        if image_size != (self.image_width, self.image_height) {
291            return Err(VisionError::InvalidInput(format!(
292                "the calibration holds for {}x{} images and this one is {}x{}: a scale holds only \
293                 for the image size and camera position it was made at",
294                self.image_width, self.image_height, image_size.0, image_size.1
295            )));
296        }
297        within(shape, image_size)?;
298        let outline = Outline::of(shape)?;
299        let (k, sigma_k) = (self.px_per_mm, self.uncertainty_px_per_mm);
300        let (longest_px, line) = max_feret(&outline.hull);
301        let longest_mm = longest_px / k;
302        let longest_uncertainty_mm =
303            ((1.0 / k).powi(2) + (longest_px * sigma_k / (k * k)).powi(2)).sqrt();
304        let area_mm2 = outline.area / (k * k);
305        let area_uncertainty_mm2 = ((outline.boundary / 2.0 / (k * k)).powi(2)
306            + (2.0 * outline.area * sigma_k / k.powi(3)).powi(2))
307        .sqrt();
308        Ok(Measurement {
309            geometry: outline.geometry,
310            longest_px,
311            longest_mm,
312            longest_uncertainty_mm,
313            line,
314            area_px: outline.area,
315            area_mm2,
316            area_uncertainty_mm2,
317        })
318    }
319}
320
321fn within(shape: &Shape, (width, height): (u32, u32)) -> Result<()> {
322    if shape.is_within(width, height) {
323        return Ok(());
324    }
325    Err(VisionError::InvalidInput(format!(
326        "the region does not lie within the {width}x{height} image (a mask must be the image's size)"
327    )))
328}
329
330/// What a region's mask, polygon or box was measured as.
331#[non_exhaustive]
332#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
333#[serde(rename_all = "camelCase")]
334pub enum MeasuredGeometry {
335    /// A mask's set pixels, as unit squares.
336    Mask,
337    /// A polygon.
338    Polygon,
339    /// An axis-aligned box: an upper bound on the object's extent.
340    Box,
341}
342
343/// A region measured in the calibrated plane.
344///
345/// Field names follow the annotated viewer's measurement record: `longestMm`,
346/// `longestUncertaintyMm`, `areaMm2`, `areaUncertaintyMm2`, `line`.
347#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
348#[serde(rename_all = "camelCase")]
349pub struct Measurement {
350    /// What was measured.
351    pub geometry: MeasuredGeometry,
352    /// The maximum Feret diameter in pixels.
353    pub longest_px: f64,
354    /// The maximum length in millimetres.
355    pub longest_mm: f64,
356    /// One standard uncertainty of `longest_mm`.
357    pub longest_uncertainty_mm: f64,
358    /// The two points the maximum length joins, in source pixels.
359    pub line: [[f64; 2]; 2],
360    /// The area in square pixels.
361    pub area_px: f64,
362    /// The area in square millimetres.
363    pub area_mm2: f64,
364    /// One standard uncertainty of `area_mm2`.
365    pub area_uncertainty_mm2: f64,
366}