Skip to main content

chess_corners/config/
uncertainty.rs

1use serde::{Deserialize, Serialize};
2
3use crate::ChessError;
4
5/// Which position uncertainty each corner reports in
6/// [`position_covariance`](crate::CornerDescriptor::position_covariance).
7///
8/// Detector-independent: it applies to every localizer (the ChESS
9/// refiners and the Radon peak fit) the same way. Corner positions are the
10/// same under every variant.
11///
12/// In JSON: `"off"`, `{"propagated": {"noise": "estimate"}}` or
13/// `{"propagated": {"noise": {"known": 1.2}}}`.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
15#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
16#[serde(rename_all = "snake_case", deny_unknown_fields)]
17#[non_exhaustive]
18pub enum Uncertainty {
19    /// No position covariance (the default). Localizers skip the noise
20    /// propagation and the systematic model, and the detector makes no
21    /// noise estimate.
22    #[default]
23    Off,
24    /// Image noise propagated through the localizer to first order, plus
25    /// the localizer's systematic-error model (from the corner's offset to
26    /// the localizer's fit window and the width of its edges). `noise` is
27    /// the image noise level that expresses the propagated part in px².
28    ///
29    /// Every localizer reports a covariance. None is reported on upscaled
30    /// input ([`DetectorConfig::upscale`](crate::DetectorConfig::upscale)):
31    /// interpolation correlates the noise of neighbouring pixels.
32    ///
33    /// The systematic part includes a per-localizer floor measured on real
34    /// calibration images (about 0.05 px per axis for the saddle-point fit
35    /// and the Radon peak fit, 0.07 center of mass). On real, well-exposed
36    /// images this floor is usually the largest part of the covariance, so
37    /// the reported σ varies little from corner to corner there. Weighting
38    /// a calibration by it has not been shown to beat uniform weighting on
39    /// real data. Errors shared by all corners of an image (defocus,
40    /// lens-model error) are outside it. The floor was fitted on one camera
41    /// pair and is likely low for other optics. Within that pair the two
42    /// cameras' own floors differed by up to 2×.
43    Propagated {
44        /// The image noise level.
45        noise: NoiseLevel,
46    },
47}
48
49/// The image noise level that turns a propagated position covariance into
50/// px² (see [`Uncertainty::Propagated`]).
51///
52/// In JSON: `"estimate"` or `{"known": 1.2}`.
53#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
54#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
55#[serde(rename_all = "snake_case")]
56#[non_exhaustive]
57pub enum NoiseLevel {
58    /// Estimate σ from each image with
59    /// [`estimate_noise_sigma_u8`](crate::estimate_noise_sigma_u8) (the
60    /// default), once per frame and only when a corner carries a
61    /// covariance. The estimate is not reliable on demosaiced or JPEG
62    /// images; use [`Known`](Self::Known) for those.
63    #[default]
64    Estimate,
65    /// A known standard deviation of the image's pixel noise, in gray
66    /// levels (finite and `>= 0`), for example the standard deviation of
67    /// the difference of two frames of a static scene, divided by `√2`.
68    /// It is the total noise as it appears in the 8-bit image, rounding
69    /// included (rounding adds `1/12` gray level² to the sensor noise,
70    /// which matters only below about 1 gray level). The covariance never
71    /// uses a variance below that `1/12`.
72    Known(
73        #[cfg_attr(feature = "schemars", schemars(range(min = 0.0)))]
74        #[cfg_attr(feature = "schemars", schemars(extend("x-unit" = "gray level")))]
75        f32,
76    ),
77}
78
79impl Uncertainty {
80    /// Whether the localizers report a covariance.
81    #[inline]
82    pub(crate) fn propagates(self) -> bool {
83        matches!(self, Self::Propagated { .. })
84    }
85
86    /// Reject a known noise level that is negative or not finite.
87    pub(crate) fn validate(self) -> Result<(), ChessError> {
88        match self {
89            Self::Propagated {
90                noise: NoiseLevel::Known(sigma),
91            } if !(sigma.is_finite() && sigma >= 0.0) => Err(ChessError::InvalidNoiseSigma(sigma)),
92            _ => Ok(()),
93        }
94    }
95}