mod geometry;
use serde::{Deserialize, Serialize};
use crate::digest::Digest;
use crate::error::{Result, VisionError};
use crate::geometry::Shape;
use geometry::{Outline, max_feret, min_area_rect};
pub const MEASUREMENT_VALIDITY: &str = "Valid only for objects lying in the plane of the \
calibration fiducial, seen by the same camera at the same image size: one image holds no \
depth, so anything nearer to or farther from the camera than the fiducial measures wrongly.";
const MIN_FIDUCIAL_PX: f64 = 10.0;
const MAX_ANISOTROPY: f64 = 0.2;
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FiducialSpec {
pub width_mm: f64,
pub height_mm: f64,
#[serde(default)]
pub tolerance_mm: f64,
}
impl FiducialSpec {
pub fn square(size_mm: f64) -> Self {
Self { width_mm: size_mm, height_mm: size_mm, tolerance_mm: 0.0 }
}
pub fn rectangle(width_mm: f64, height_mm: f64) -> Self {
Self { width_mm, height_mm, tolerance_mm: 0.0 }
}
#[must_use]
pub fn with_tolerance(mut self, tolerance_mm: f64) -> Self {
self.tolerance_mm = tolerance_mm;
self
}
pub fn validate(&self) -> Result<()> {
let positive = |v: f64| v.is_finite() && v > 0.0;
if !positive(self.width_mm) || !positive(self.height_mm) {
return Err(VisionError::InvalidInput(format!(
"a fiducial's size must be positive millimetres, not {} x {}",
self.width_mm, self.height_mm
)));
}
if !self.tolerance_mm.is_finite()
|| self.tolerance_mm < 0.0
|| self.tolerance_mm >= self.width_mm.min(self.height_mm)
{
return Err(VisionError::InvalidInput(format!(
"a fiducial's tolerance must be zero or more and smaller than its sides, not {}",
self.tolerance_mm
)));
}
Ok(())
}
fn sides(&self) -> [f64; 2] {
[self.width_mm.max(self.height_mm), self.width_mm.min(self.height_mm)]
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
pub enum CalibrationSource {
Fiducial {
spec: FiducialSpec,
measured_px: [f64; 2],
#[serde(default, skip_serializing_if = "Option::is_none")]
image: Option<Digest>,
},
Scale,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Calibration {
pub px_per_mm: f64,
pub uncertainty_px_per_mm: f64,
pub image_width: u32,
pub image_height: u32,
pub source: CalibrationSource,
}
impl Calibration {
pub fn from_fiducial(
shape: &Shape,
spec: FiducialSpec,
image_size: (u32, u32),
) -> Result<Self> {
spec.validate()?;
within(shape, image_size)?;
let outline = Outline::of(shape)?;
let [long_px, short_px] = min_area_rect(&outline.hull);
if short_px < MIN_FIDUCIAL_PX {
return Err(VisionError::InvalidInput(format!(
"the fiducial spans {short_px:.1} px on its short side; it needs at least \
{MIN_FIDUCIAL_PX} px to calibrate: move the camera closer or use a larger fiducial"
)));
}
let [long_mm, short_mm] = spec.sides();
let (k_long, k_short) = (long_px / long_mm, short_px / short_mm);
let k = (k_long + k_short) / 2.0;
let anisotropy = (k_long - k_short).abs() / k;
if anisotropy > MAX_ANISOTROPY {
return Err(VisionError::InvalidInput(format!(
"the fiducial measures {long_px:.1} x {short_px:.1} px, which does not match its \
{long_mm} x {short_mm} mm shape within {}%: the region is not the fiducial, or \
the plane is tilted too far to measure in",
MAX_ANISOTROPY * 100.0
)));
}
let quantisation = 0.5 * ((1.0 / long_mm).powi(2) + (1.0 / short_mm).powi(2)).sqrt();
let tolerance = k * spec.tolerance_mm / ((long_mm + short_mm) / 2.0);
let perspective = (k_long - k_short).abs() / 2.0;
let uncertainty = (quantisation.powi(2) + tolerance.powi(2) + perspective.powi(2)).sqrt();
Ok(Self {
px_per_mm: k,
uncertainty_px_per_mm: uncertainty,
image_width: image_size.0,
image_height: image_size.1,
source: CalibrationSource::Fiducial {
spec,
measured_px: [long_px, short_px],
image: None,
},
})
}
pub fn from_scale(
px_per_mm: f64,
uncertainty_px_per_mm: f64,
image_size: (u32, u32),
) -> Result<Self> {
if !px_per_mm.is_finite() || px_per_mm <= 0.0 {
return Err(VisionError::InvalidInput(format!(
"a scale must be positive pixels per millimetre, not {px_per_mm}"
)));
}
if !uncertainty_px_per_mm.is_finite() || uncertainty_px_per_mm < 0.0 {
return Err(VisionError::InvalidInput(format!(
"a scale's uncertainty must be zero or more, not {uncertainty_px_per_mm}"
)));
}
Ok(Self {
px_per_mm,
uncertainty_px_per_mm,
image_width: image_size.0,
image_height: image_size.1,
source: CalibrationSource::Scale,
})
}
#[must_use]
pub fn with_image(mut self, digest: Digest) -> Self {
if let CalibrationSource::Fiducial { image, .. } = &mut self.source {
*image = Some(digest);
}
self
}
pub fn relative_uncertainty(&self) -> f64 {
self.uncertainty_px_per_mm / self.px_per_mm
}
pub fn reference(&self) -> (f64, f64) {
match &self.source {
CalibrationSource::Fiducial { spec, measured_px, .. } => {
(spec.sides()[0], measured_px[0])
}
CalibrationSource::Scale => (1.0, self.px_per_mm),
}
}
pub fn measure(&self, shape: &Shape, image_size: (u32, u32)) -> Result<Measurement> {
if image_size != (self.image_width, self.image_height) {
return Err(VisionError::InvalidInput(format!(
"the calibration holds for {}x{} images and this one is {}x{}: a scale holds only \
for the image size and camera position it was made at",
self.image_width, self.image_height, image_size.0, image_size.1
)));
}
within(shape, image_size)?;
let outline = Outline::of(shape)?;
let (k, sigma_k) = (self.px_per_mm, self.uncertainty_px_per_mm);
let (longest_px, line) = max_feret(&outline.hull);
let longest_mm = longest_px / k;
let longest_uncertainty_mm =
((1.0 / k).powi(2) + (longest_px * sigma_k / (k * k)).powi(2)).sqrt();
let area_mm2 = outline.area / (k * k);
let area_uncertainty_mm2 = ((outline.boundary / 2.0 / (k * k)).powi(2)
+ (2.0 * outline.area * sigma_k / k.powi(3)).powi(2))
.sqrt();
Ok(Measurement {
geometry: outline.geometry,
longest_px,
longest_mm,
longest_uncertainty_mm,
line,
area_px: outline.area,
area_mm2,
area_uncertainty_mm2,
})
}
}
fn within(shape: &Shape, (width, height): (u32, u32)) -> Result<()> {
if shape.is_within(width, height) {
return Ok(());
}
Err(VisionError::InvalidInput(format!(
"the region does not lie within the {width}x{height} image (a mask must be the image's size)"
)))
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MeasuredGeometry {
Mask,
Polygon,
Box,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Measurement {
pub geometry: MeasuredGeometry,
pub longest_px: f64,
pub longest_mm: f64,
pub longest_uncertainty_mm: f64,
pub line: [[f64; 2]; 2],
pub area_px: f64,
pub area_mm2: f64,
pub area_uncertainty_mm2: f64,
}