use image::GrayImage;
use crate::calibration::CameraCalibration;
use crate::error::{ComposeError, FrameField};
pub const HIDDEN_BELOW: f32 = 0.6;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Located {
pub offset_px: [f64; 2],
pub score: f32,
}
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(())
}
#[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()
}
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(())
}
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,
}
}
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]
}