Skip to main content

chess_corners/
noise.rs

1//! Per-image pixel-noise estimate.
2
3use crate::ChessError;
4
5/// Estimate the standard deviation of an 8-bit grayscale image's pixel
6/// noise, in gray levels.
7///
8/// This is the estimate [`Detector`](crate::Detector) uses to express
9/// position covariances in px² under
10/// [`NoiseLevel::Estimate`](crate::NoiseLevel::Estimate); calling it on the
11/// same image returns the same value. Strong
12/// edges, corners, smooth shading and areas near black or white are
13/// excluded, so it suits images dominated by a calibration board. It is not
14/// reliable on demosaiced or JPEG images; supply
15/// [`NoiseLevel::Known`](crate::NoiseLevel::Known) for those. Cost is independent of the image size (well under a
16/// millisecond).
17///
18/// `img` is `width * height` bytes, row-major. Returns `Ok(None)` when the
19/// image is smaller than 4×4 or has too few structure-free areas for an
20/// estimate. The full accuracy statement is on
21/// [`chess_corners_core::estimate_noise_sigma_u8`].
22///
23/// ```
24/// // A flat gray image with no noise: the estimate is the 8-bit
25/// // rounding floor, near zero.
26/// let img = vec![128u8; 64 * 64];
27/// let sigma = chess_corners::estimate_noise_sigma_u8(&img, 64, 64)?;
28/// assert!(sigma.is_none_or(|s| s < 0.5));
29/// # Ok::<(), chess_corners::ChessError>(())
30/// ```
31///
32/// # Errors
33///
34/// Returns [`ChessError::DimensionMismatch`] if `img.len() != width * height`.
35pub fn estimate_noise_sigma_u8(
36    img: &[u8],
37    width: u32,
38    height: u32,
39) -> Result<Option<f32>, ChessError> {
40    let (w, h) = (width as usize, height as usize);
41    let expected = w * h;
42    if img.len() != expected {
43        return Err(ChessError::DimensionMismatch {
44            expected,
45            actual: img.len(),
46        });
47    }
48    Ok(chess_corners_core::estimate_noise_sigma_u8(img, w, h))
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use chess_corners_testutil::aa_chessboard;
55
56    #[test]
57    fn rejects_dimension_mismatch() {
58        let err = estimate_noise_sigma_u8(&[0u8; 10], 4, 4).unwrap_err();
59        assert!(matches!(
60            err,
61            ChessError::DimensionMismatch {
62                expected: 16,
63                actual: 10
64            }
65        ));
66    }
67
68    #[test]
69    fn matches_the_core_estimate() {
70        let size = 128usize;
71        let mut img = aa_chessboard(size, 12, (0.3, 0.6), 40, 200);
72        // Deterministic ±3 gray-level noise.
73        let mut state = 11u32;
74        for v in &mut img {
75            state = state.wrapping_mul(1_103_515_245).wrapping_add(12_345);
76            *v = v
77                .saturating_add(((state >> 16) % 7) as u8)
78                .saturating_sub(3);
79        }
80        let facade = estimate_noise_sigma_u8(&img, size as u32, size as u32).unwrap();
81        let core = chess_corners_core::estimate_noise_sigma_u8(&img, size, size);
82        assert_eq!(facade, core);
83        assert!(facade.is_some_and(|s| s > 1.0));
84    }
85}