printobserver-panels 0.15.2

Camera calibration, drift and alignment checks, and the check image's panels, for printobserver.
Documentation
//! Whether the camera has moved since it was calibrated, and whether a frame
//! is the calibration's at all.
//!
//! Each landmark's stored patch is located by normalized cross-correlation
//! within its search radius; a best score below [`HIDDEN_BELOW`] counts as
//! hidden (by the head, the gantry or a part). The camera has moved when at
//! least two visible landmarks are displaced by more than the calibration's
//! tolerance, and drift is unverified when fewer than two are visible: one
//! moved landmark alone is as likely a false match as a moved camera.

use image::GrayImage;

use crate::calibration::CameraCalibration;
use crate::error::{ComposeError, FrameField};

/// The correlation below which a landmark counts as hidden.
pub const HIDDEN_BELOW: f32 = 0.6;

/// Where one landmark was found.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Located {
    /// How far from its calibrated place, in pixels, `[dx, dy]`.
    pub offset_px: [f64; 2],
    /// The best correlation found.
    pub score: f32,
}

/// Refuse a frame of another size, or from another stream, than the
/// calibration's.
///
/// # Errors
///
/// [`ComposeError::FrameMismatch`] naming the resolution or the stream.
pub fn check_frame(
    calibration: &CameraCalibration,
    size: [u32; 2],
    camera_snapshot_url: &str,
) -> Result<(), ComposeError> {
    if size != calibration.image_size_px {
        let [ew, eh] = calibration.image_size_px;
        return Err(ComposeError::FrameMismatch {
            field: FrameField::Resolution,
            expected: format!("{ew}x{eh}"),
            got: format!("{}x{}", size[0], size[1]),
        });
    }
    if camera_snapshot_url != calibration.camera_snapshot_url {
        return Err(ComposeError::FrameMismatch {
            field: FrameField::Stream,
            expected: calibration.camera_snapshot_url.clone(),
            got: camera_snapshot_url.to_owned(),
        });
    }
    Ok(())
}

/// Locate every landmark in a grey frame, in the calibration's order.
#[must_use]
pub fn locate_landmarks(calibration: &CameraCalibration, frame: &GrayImage) -> Vec<Located> {
    calibration
        .landmarks
        .iter()
        .zip(calibration.patches())
        .map(|(landmark, patch)| {
            locate(
                frame,
                patch,
                landmark.center_px,
                i64::from(landmark.search_radius_px),
            )
        })
        .collect()
}

/// Rule on drift from where the landmarks were found.
///
/// # Errors
///
/// [`ComposeError::CameraMoved`] naming the landmark that moved furthest, and
/// [`ComposeError::DriftUnverified`] when fewer than two are visible.
pub fn check_drift(calibration: &CameraCalibration, frame: &GrayImage) -> Result<(), ComposeError> {
    let found = locate_landmarks(calibration, frame);
    let visible: Vec<(&str, f64)> = calibration
        .landmarks
        .iter()
        .zip(&found)
        .filter(|(_, located)| located.score >= HIDDEN_BELOW)
        .map(|(landmark, located)| {
            (
                landmark.name.as_str(),
                located.offset_px[0].hypot(located.offset_px[1]),
            )
        })
        .collect();
    if visible.len() < 2 {
        return Err(ComposeError::DriftUnverified);
    }
    let moved: Vec<&(&str, f64)> = visible
        .iter()
        .filter(|(_, offset)| *offset > calibration.drift_tolerance_px)
        .collect();
    if moved.len() >= 2 {
        let (landmark, offset_px) =
            moved.iter().copied().fold(
                moved[0],
                |far, next| if next.1 > far.1 { next } else { far },
            );
        return Err(ComposeError::CameraMoved {
            landmark: (*landmark).to_owned(),
            offset_px: *offset_px,
        });
    }
    Ok(())
}

/// Find one patch near where it was, by normalized cross-correlation, with
/// the peak refined to a fraction of a pixel by a parabola through its
/// neighbours.
fn locate(frame: &GrayImage, patch: &GrayImage, center: [f64; 2], radius: i64) -> Located {
    let hidden = Located {
        offset_px: [0.0, 0.0],
        score: -1.0,
    };
    let (pw, ph) = (i64::from(patch.width()), i64::from(patch.height()));
    let (fw, fh) = (i64::from(frame.width()), i64::from(frame.height()));
    #[expect(
        clippy::cast_possible_truncation,
        reason = "a landmark's centre is a pixel of a frame of at most a few thousand pixels"
    )]
    let (left, top) = (
        center[0].round() as i64 - pw / 2,
        center[1].round() as i64 - ph / 2,
    );
    let template: Vec<f32> = patch
        .as_raw()
        .iter()
        .map(|value| f32::from(*value))
        .collect();
    #[expect(
        clippy::cast_precision_loss,
        reason = "a patch holds a few thousand pixels"
    )]
    let count = template.len() as f32;
    let mean = template.iter().sum::<f32>() / count;
    let centred: Vec<f32> = template.iter().map(|value| value - mean).collect();
    let template_norm = centred
        .iter()
        .map(|value| value * value)
        .sum::<f32>()
        .sqrt();
    if template_norm < 1e-3 {
        return hidden;
    }
    let pixels = frame.as_raw();
    let side = usize::try_from(2 * radius + 1).unwrap_or(0);
    let mut scores = vec![f32::NEG_INFINITY; side * side];
    let width = usize::try_from(fw).unwrap_or(0);
    let pw_us = usize::try_from(pw).unwrap_or(0);
    for dy in -radius..=radius {
        for dx in -radius..=radius {
            let (x0, y0) = (left + dx, top + dy);
            if x0 < 0 || y0 < 0 || x0 + pw > fw || y0 + ph > fh {
                continue;
            }
            let (x0, y0) = (
                usize::try_from(x0).unwrap_or(0),
                usize::try_from(y0).unwrap_or(0),
            );
            let (mut sum, mut squares, mut cross) = (0.0_f32, 0.0_f32, 0.0_f32);
            for (row, weights) in centred.chunks_exact(pw_us).enumerate() {
                let start = (y0 + row) * width + x0;
                for (pixel, weight) in pixels[start..start + pw_us].iter().zip(weights) {
                    let value = f32::from(*pixel);
                    sum += value;
                    squares += value * value;
                    cross += value * weight;
                }
            }
            let spread = (squares - sum * sum / count).max(0.0).sqrt();
            if spread > 1e-3 {
                let at =
                    usize::try_from((dy + radius) * (2 * radius + 1) + dx + radius).unwrap_or(0);
                scores[at] = cross / (spread * template_norm);
            }
        }
    }
    let Some((best, score)) = scores
        .iter()
        .copied()
        .enumerate()
        .filter(|(_, score)| score.is_finite())
        .reduce(|best, next| if next.1 > best.1 { next } else { best })
    else {
        return hidden;
    };
    Located {
        offset_px: refined_peak(&scores, side, best, score, radius),
        score,
    }
}

/// A correlation peak's place as an offset from the search's centre, refined
/// to a fraction of a pixel by a parabola through its neighbours on each axis.
fn refined_peak(scores: &[f32], side: usize, best: usize, score: f32, radius: i64) -> [f64; 2] {
    let (row, column) = (best / side, best % side);
    let refine = |before: Option<f32>, after: Option<f32>| match (before, after) {
        (Some(a), Some(c)) if a.is_finite() && c.is_finite() => {
            let curve = a - 2.0 * score + c;
            if curve.abs() > 1e-9 {
                f64::from(0.5 * (a - c) / curve)
            } else {
                0.0
            }
        }
        _ => 0.0,
    };
    let at = |r: usize, c: usize| scores.get(r * side + c).copied();
    let sub_x = refine(
        column.checked_sub(1).and_then(|c| at(row, c)),
        (column + 1 < side).then(|| at(row, column + 1)).flatten(),
    );
    let sub_y = refine(
        row.checked_sub(1).and_then(|r| at(r, column)),
        (row + 1 < side).then(|| at(row + 1, column)).flatten(),
    );
    let radius = f64::from(u32::try_from(radius).unwrap_or(0));
    let whole = |index: usize| f64::from(u32::try_from(index).unwrap_or(0)) - radius;
    [whole(column) + sub_x, whole(row) + sub_y]
}