use std::sync::OnceLock;
use image::{GrayImage, Rgb, RgbImage};
use imageproc::drawing::{draw_cross_mut, draw_hollow_rect_mut};
use imageproc::rect::Rect;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use crate::calibration::{CameraCalibration, Projector};
use crate::compose::decode;
use crate::drift::check_frame;
use crate::error::ComposeError;
use crate::view::{FoundLandmark, ReferenceLandmark, ViewCorrection, found_landmarks};
pub const SHEET_TOLERANCE_PX: f64 = 10.0;
pub const MAX_RESIDUAL_PX: f64 = 5.0;
pub const MIN_SUPPORT: f64 = 0.6;
pub const NO_SHEET_BELOW: f64 = 0.25;
pub const MIN_EDGES_SEEN: usize = 3;
pub const MIN_SAMPLES_PER_EDGE: usize = 6;
const EDGE_MIN_STRENGTH: f64 = 2.0;
const IN_VIEW_MARGIN_PX: f64 = 20.0;
const BLUR_SIGMA: f64 = 2.0;
const SEARCH_STEP_PX: f64 = 0.5;
const ALONG_EDGE_PX: f64 = 3.0;
const HUBER_PX: f64 = 1.5;
const HOLE_DARKER_BY: f64 = 25.0;
const HOLE_MIN_AREA: usize = 20;
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct SheetEdge {
pub name: String,
pub from_mm: [f64; 2],
pub to_mm: [f64; 2],
pub outward: [f64; 2],
pub profile_t_across_mm: Vec<[f64; 2]>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct SheetOutline {
pub sheet: String,
pub source: String,
pub plane: String,
pub edges: Vec<SheetEdge>,
pub hole_mm: Option<[f64; 2]>,
}
const COMMITTED: [&str; 2] = [
include_str!("../sheets/core-one-smooth-pei.json"),
include_str!("../sheets/core-one-textured-pei.json"),
];
impl SheetOutline {
#[must_use]
pub fn committed(sheet: &str) -> Option<&'static Self> {
static PARSED: OnceLock<Vec<SheetOutline>> = OnceLock::new();
PARSED
.get_or_init(|| {
COMMITTED
.iter()
.filter_map(|text| printobserver_types::serde_json::from_str(text).ok())
.collect()
})
.iter()
.find(|outline| outline.sheet == sheet)
}
#[must_use]
pub fn committed_sheets() -> Vec<&'static str> {
["smooth-pei", "textured-pei"]
.into_iter()
.filter(|sheet| Self::committed(sheet).is_some())
.collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum UnjudgeableCause {
TooLittleSheetInView,
NoSheetFound,
SheetOccluded,
LandmarksHidden,
FitInconsistent,
}
impl UnjudgeableCause {
#[must_use]
pub const fn said(self) -> &'static str {
match self {
Self::TooLittleSheetInView => "too little of the sheet is in the camera's view",
Self::NoSheetFound => "no sheet was found in the frame",
Self::SheetOccluded => "too much of the sheet's outline is hidden",
Self::LandmarksHidden => {
"fewer than two of the calibration's landmarks are found, so whether the camera moved cannot be told"
}
Self::FitInconsistent => "the sheet's edges fit no one shift of its outline",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SheetVerdict {
Aligned,
NotAligned,
Unjudgeable(UnjudgeableCause),
}
#[derive(Debug, Clone, PartialEq)]
pub struct SheetFit {
pub verdict: SheetVerdict,
pub shift_px: Option<[f64; 2]>,
pub residual_px: Option<f64>,
pub support: f64,
pub edges_seen: usize,
pub landmarks_moved: usize,
pub landmarks_visible: usize,
pub hole_found: bool,
pub correction: Option<ViewCorrection>,
pub drawn_jpeg: Vec<u8>,
}
impl SheetFit {
#[must_use]
pub fn offset_px(&self) -> Option<f64> {
self.shift_px.map(|[dx, dy]| dx.hypot(dy))
}
}
#[derive(Debug, Clone, Copy)]
pub struct SheetInputs<'a> {
pub frame_jpeg: &'a [u8],
pub camera_snapshot_url: &'a str,
pub calibration: &'a CameraCalibration,
pub sheet: &'a SheetOutline,
pub bed_z_mm: f64,
}
pub fn fit_sheet(inputs: &SheetInputs<'_>) -> Result<SheetFit, ComposeError> {
let frame = decode(inputs.frame_jpeg)?;
check_frame(
inputs.calibration,
[frame.width(), frame.height()],
inputs.camera_snapshot_url,
)?;
let grey = image::imageops::grayscale(&frame);
let landmarks = found_landmarks(inputs.calibration, &grey);
let gradients = Gradients::of(&grey);
let samples = Samples::projected(
&inputs.calibration.projector(),
inputs.sheet,
inputs.bed_z_mm,
[frame.width(), frame.height()],
);
let measured = measure(&gradients, &samples);
let visible = landmarks.iter().filter(|found| found.visible()).count();
let moved = landmarks
.iter()
.filter(|found| {
found.visible() && found.distance_px() > inputs.calibration.drift_tolerance_px
})
.count();
let verdict = ruled(&measured, visible, moved);
let correction = (verdict == SheetVerdict::Aligned)
.then_some(measured.shift)
.flatten()
.map(|shift| ViewCorrection::translation(shift, reference(&landmarks)));
let drawn_jpeg = drawn(frame, &samples, &measured, &landmarks, inputs.calibration)?;
Ok(SheetFit {
verdict,
shift_px: measured.shift,
residual_px: measured.residual,
support: measured.support,
edges_seen: measured.edges_seen,
landmarks_moved: moved,
landmarks_visible: visible,
hole_found: measured.hole.is_some(),
correction,
drawn_jpeg,
})
}
const OUTLINE_SEARCH_TOP_MM: u32 = 220;
const OUTLINE_SEARCH_STEP_MM: u32 = 2;
pub(crate) fn calibrated_outline(
frame: &RgbImage,
camera_snapshot_url: &str,
calibration: &CameraCalibration,
) -> Option<Vec<[f64; 2]>> {
let size = [frame.width(), frame.height()];
check_frame(calibration, size, camera_snapshot_url).ok()?;
let grey = image::imageops::grayscale(frame);
let moved = found_landmarks(calibration, &grey)
.iter()
.filter(|found| found.visible() && found.distance_px() > calibration.drift_tolerance_px)
.count();
if moved >= 2 {
return None;
}
let gradients = Gradients::of(&grey);
let projector = calibration.projector();
let mut best: Option<(f64, f64, &SheetOutline, f64, [f64; 2])> = None;
for sheet in SheetOutline::committed_sheets() {
let Some(outline) = SheetOutline::committed(sheet) else {
continue;
};
for step in 0..=OUTLINE_SEARCH_TOP_MM / OUTLINE_SEARCH_STEP_MM {
let bed_z_mm = f64::from(step * OUTLINE_SEARCH_STEP_MM);
let samples = Samples::projected(&projector, outline, bed_z_mm, size);
let measured = measure(&gradients, &samples);
let (Some(shift), Some(residual)) = (measured.shift, measured.residual) else {
continue;
};
if measured.unfitted.is_some() || residual > MAX_RESIDUAL_PX {
continue;
}
if best.is_none_or(|(support, least, ..)| {
measured
.support
.total_cmp(&support)
.then(least.total_cmp(&residual))
.is_gt()
}) {
best = Some((measured.support, residual, outline, bed_z_mm, shift));
}
}
}
let (_, _, outline, bed_z_mm, [dx, dy]) = best?;
Some(
outline_points_mm(outline)
.into_iter()
.filter_map(|[x, y]| projector.pixel([x, y, -bed_z_mm]))
.map(|[u, v]| [u + dx, v + dy])
.collect(),
)
}
fn outline_points_mm(sheet: &SheetOutline) -> Vec<[f64; 2]> {
let mut points = Vec::new();
for edge in &sheet.edges {
let (dx, dy) = (
edge.to_mm[0] - edge.from_mm[0],
edge.to_mm[1] - edge.from_mm[1],
);
let length = dx.hypot(dy);
if length <= 0.0 {
continue;
}
let direction = [dx / length, dy / length];
points.push(edge.from_mm);
points.extend(edge.profile_t_across_mm.iter().map(|[t, across]| {
[
edge.from_mm[0] + t * direction[0] + across * edge.outward[0],
edge.from_mm[1] + t * direction[1] + across * edge.outward[1],
]
}));
points.push(edge.to_mm);
}
points
}
fn ruled(measured: &Measured, visible: usize, moved: usize) -> SheetVerdict {
if moved >= 2 {
return SheetVerdict::NotAligned;
}
if let Some(cause) = measured.unfitted {
return SheetVerdict::Unjudgeable(cause);
}
if visible < 2 {
return SheetVerdict::Unjudgeable(UnjudgeableCause::LandmarksHidden);
}
if measured
.residual
.is_some_and(|residual| residual > MAX_RESIDUAL_PX)
{
return SheetVerdict::Unjudgeable(UnjudgeableCause::FitInconsistent);
}
if measured
.shift
.is_some_and(|[dx, dy]| dx.hypot(dy) > SHEET_TOLERANCE_PX)
{
return SheetVerdict::NotAligned;
}
SheetVerdict::Aligned
}
fn reference(landmarks: &[FoundLandmark]) -> Vec<ReferenceLandmark> {
landmarks
.iter()
.filter(|found| found.visible())
.map(|found| ReferenceLandmark {
name: found.name.clone(),
offset_px: found.located.offset_px,
score: f64::from(found.located.score),
})
.collect()
}
struct Gradients {
width: usize,
height: usize,
grey: Vec<f64>,
gx: Vec<f64>,
gy: Vec<f64>,
}
impl Gradients {
fn of(frame: &GrayImage) -> Self {
let (width, height) = (frame.width() as usize, frame.height() as usize);
let raw: Vec<f64> = frame
.as_raw()
.iter()
.map(|value| f64::from(*value))
.collect();
let grey = blurred(&raw, width, height, BLUR_SIGMA);
let mut gx = vec![0.0; width * height];
let mut gy = vec![0.0; width * height];
let at = |x: usize, y: usize| grey[y * width + x];
for y in 0..height {
let (up, down) = (y.saturating_sub(1), (y + 1).min(height - 1));
for x in 0..width {
let (left, right) = (x.saturating_sub(1), (x + 1).min(width - 1));
gx[y * width + x] = ((at(right, up) - at(left, up))
+ 2.0 * (at(right, y) - at(left, y))
+ (at(right, down) - at(left, down)))
/ 8.0;
gy[y * width + x] = ((at(left, down) - at(left, up))
+ 2.0 * (at(x, down) - at(x, up))
+ (at(right, down) - at(right, up)))
/ 8.0;
}
}
Self {
width,
height,
grey,
gx,
gy,
}
}
fn sample(&self, plane: &[f64], [x, y]: [f64; 2]) -> f64 {
let most = |size: usize| f64::from(u32::try_from(size - 1).unwrap_or(0));
let (x, y) = (
x.clamp(0.0, most(self.width)),
y.clamp(0.0, most(self.height)),
);
let (x0, y0) = (x.floor(), y.floor());
let (fx, fy) = (x - x0, y - y0);
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped into the frame above"
)]
let (x0, y0) = (x0 as usize, y0 as usize);
let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1));
let value = |x: usize, y: usize| plane[y * self.width + x];
(value(x0, y0) * (1.0 - fx) + value(x1, y0) * fx) * (1.0 - fy)
+ (value(x0, y1) * (1.0 - fx) + value(x1, y1) * fx) * fy
}
fn along(&self, point: [f64; 2], normal: [f64; 2]) -> f64 {
self.sample(&self.gx, point) * normal[0] + self.sample(&self.gy, point) * normal[1]
}
}
pub(crate) fn blurred(plane: &[f64], width: usize, height: usize, sigma: f64) -> Vec<f64> {
let radius = (sigma * 4.0).ceil();
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a few times a small sigma"
)]
let reach = radius as usize;
let weights: Vec<f64> = (0..=2 * reach)
.map(|k| {
let d = f64::from(u32::try_from(k).unwrap_or(0)) - radius;
(-(d * d) / (2.0 * sigma * sigma)).exp()
})
.collect();
let total: f64 = weights.iter().sum();
let weights: Vec<f64> = weights.iter().map(|weight| weight / total).collect();
let mut across = vec![0.0; plane.len()];
for y in 0..height {
let row = &plane[y * width..(y + 1) * width];
for x in 0..width {
across[y * width + x] = weights
.iter()
.enumerate()
.map(|(k, weight)| {
let at = (x + k).saturating_sub(reach).min(width - 1);
row[at] * weight
})
.sum();
}
}
let mut out = vec![0.0; plane.len()];
for y in 0..height {
for (k, weight) in weights.iter().enumerate() {
let from = (y + k).saturating_sub(reach).min(height - 1);
let source = &across[from * width..(from + 1) * width];
let target = &mut out[y * width..(y + 1) * width];
for (value, add) in target.iter_mut().zip(source) {
*value += add * weight;
}
}
}
out
}
struct Samples {
points: Vec<[f64; 2]>,
normals: Vec<[f64; 2]>,
edge: Vec<usize>,
edges: usize,
hole: Option<[f64; 2]>,
}
impl Samples {
fn projected(
projector: &Projector,
sheet: &SheetOutline,
bed_z_mm: f64,
size: [u32; 2],
) -> Self {
let [w, h] = size.map(f64::from);
let in_view = |[u, v]: [f64; 2]| {
u > IN_VIEW_MARGIN_PX
&& u < w - IN_VIEW_MARGIN_PX
&& v > IN_VIEW_MARGIN_PX
&& v < h - IN_VIEW_MARGIN_PX
};
let mut samples = Self {
points: Vec::new(),
normals: Vec::new(),
edge: Vec::new(),
edges: sheet.edges.len(),
hole: sheet
.hole_mm
.and_then(|[x, y]| projector.pixel([x, y, -bed_z_mm])),
};
for (index, edge) in sheet.edges.iter().enumerate() {
let (dx, dy) = (
edge.to_mm[0] - edge.from_mm[0],
edge.to_mm[1] - edge.from_mm[1],
);
let length = dx.hypot(dy);
if length <= 0.0 {
continue;
}
let direction = [dx / length, dy / length];
for [t, across] in &edge.profile_t_across_mm {
let bed = [
edge.from_mm[0] + t * direction[0] + across * edge.outward[0],
edge.from_mm[1] + t * direction[1] + across * edge.outward[1],
];
let (Some(point), Some(outer)) = (
projector.pixel([bed[0], bed[1], -bed_z_mm]),
projector.pixel([
bed[0] + edge.outward[0],
bed[1] + edge.outward[1],
-bed_z_mm,
]),
) else {
continue;
};
let normal = [outer[0] - point[0], outer[1] - point[1]];
let norm = normal[0].hypot(normal[1]);
if !in_view(point) || norm <= 1e-9 {
continue;
}
samples.points.push(point);
samples.normals.push([normal[0] / norm, normal[1] / norm]);
samples.edge.push(index);
}
}
samples
}
fn edges_with(&self, kept: &[bool]) -> usize {
(0..self.edges)
.filter(|edge| {
self.edge
.iter()
.zip(kept)
.filter(|(of, kept)| **of == *edge && **kept)
.count()
>= MIN_SAMPLES_PER_EDGE
})
.count()
}
}
struct Measured {
unfitted: Option<UnjudgeableCause>,
support: f64,
edges_seen: usize,
offsets: Vec<Option<f64>>,
hole: Option<[f64; 2]>,
shift: Option<[f64; 2]>,
residual: Option<f64>,
}
fn measure(gradients: &Gradients, samples: &Samples) -> Measured {
let mut measured = Measured {
unfitted: None,
support: 0.0,
edges_seen: 0,
offsets: Vec::new(),
hole: None,
shift: None,
residual: None,
};
let all = vec![true; samples.points.len()];
if samples.points.len() < MIN_EDGES_SEEN * MIN_SAMPLES_PER_EDGE
|| samples.edges_with(&all) < MIN_EDGES_SEEN
{
measured.unfitted = Some(UnjudgeableCause::TooLittleSheetInView);
measured.edges_seen = samples.edges_with(&all);
return measured;
}
measured.offsets = samples
.points
.iter()
.zip(&samples.normals)
.map(|(point, normal)| edge_offset(gradients, *point, *normal, SHEET_TOLERANCE_PX))
.collect();
let found: Vec<bool> = measured.offsets.iter().map(Option::is_some).collect();
let count = found.iter().filter(|found| **found).count();
measured.support = ratio(count, found.len());
measured.edges_seen = samples.edges_with(&found);
if measured.support < NO_SHEET_BELOW {
measured.unfitted = Some(UnjudgeableCause::NoSheetFound);
return measured;
}
if measured.support < MIN_SUPPORT || measured.edges_seen < MIN_EDGES_SEEN {
measured.unfitted = Some(UnjudgeableCause::SheetOccluded);
return measured;
}
let mut rows: Vec<([f64; 2], f64)> = samples
.normals
.iter()
.zip(&measured.offsets)
.filter_map(|(normal, offset)| offset.map(|offset| (*normal, offset)))
.collect();
let outline_rows = rows.len();
measured.hole = samples
.hole
.and_then(|hole| dark_blob(gradients, hole, SHEET_TOLERANCE_PX).map(|at| (hole, at)))
.map(|(hole, at)| {
rows.push(([1.0, 0.0], at[0] - hole[0]));
rows.push(([0.0, 1.0], at[1] - hole[1]));
at
});
let (shift, residuals) = huber_translation(&rows);
measured.shift = Some(shift);
measured.residual = Some(rms_inliers(&residuals[..outline_rows]));
measured
}
fn ratio(count: usize, total: usize) -> f64 {
let as_f64 = |n: usize| f64::from(u32::try_from(n).unwrap_or(u32::MAX));
if total == 0 {
0.0
} else {
as_f64(count) / as_f64(total)
}
}
fn edge_offset(
gradients: &Gradients,
point: [f64; 2],
normal: [f64; 2],
window: f64,
) -> Option<f64> {
let tangent = [-normal[1], normal[0]];
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a window of a few pixels"
)]
let steps = (2.0 * window / SEARCH_STEP_PX).round() as usize + 1;
let profile: Vec<f64> = (0..steps)
.map(|step| {
let d = -window + SEARCH_STEP_PX * f64::from(u32::try_from(step).unwrap_or(0));
let total: f64 = [-ALONG_EDGE_PX, 0.0, ALONG_EDGE_PX]
.iter()
.map(|t| {
gradients.along(
[
point[0] + d * normal[0] + t * tangent[0],
point[1] + d * normal[1] + t * tangent[1],
],
normal,
)
})
.sum();
-total / 3.0
})
.collect();
let (best, strength) = profile
.iter()
.copied()
.enumerate()
.reduce(|best, next| if next.1 > best.1 { next } else { best })?;
if best == 0 || best + 1 == steps || strength < EDGE_MIN_STRENGTH {
return None;
}
let (left, right) = (profile[best - 1], profile[best + 1]);
let curve = left - 2.0 * strength + right;
let refined = if curve.abs() > 1e-9 {
0.5 * SEARCH_STEP_PX * (left - right) / curve
} else {
0.0
};
Some(-window + SEARCH_STEP_PX * f64::from(u32::try_from(best).unwrap_or(0)) + refined)
}
fn dark_blob(gradients: &Gradients, guess: [f64; 2], window: f64) -> Option<[f64; 2]> {
#[expect(
clippy::cast_possible_truncation,
reason = "a projected point of a frame of a few thousand pixels"
)]
let (x, y) = (guess[0].round() as i64, guess[1].round() as i64);
#[expect(
clippy::cast_possible_truncation,
reason = "a tolerance of a few pixels"
)]
let reach = window as i64 + 12;
let (width, height) = (
i64::try_from(gradients.width).ok()?,
i64::try_from(gradients.height).ok()?,
);
if x - reach < 0 || y - reach < 0 || x + reach >= width || y + reach >= height {
return None;
}
let side = usize::try_from(2 * reach + 1).ok()?;
let value = |dx: usize, dy: usize| {
let at = usize::try_from((y - reach) * width + x - reach).unwrap_or(0)
+ dy * gradients.width
+ dx;
gradients.grey[at]
};
let mut values: Vec<f64> = (0..side * side)
.map(|k| value(k % side, k / side))
.collect();
let mut sorted = values.clone();
sorted.sort_by(f64::total_cmp);
let median = sorted[sorted.len() / 2];
for value in &mut values {
*value = if *value < median - HOLE_DARKER_BY {
1.0
} else {
0.0
};
}
let mut seen = vec![false; side * side];
let mut best: Option<(usize, [f64; 2])> = None;
let reach_f = f64::from(u32::try_from(reach).unwrap_or(0));
for start in 0..side * side {
if values[start] < 0.5 || seen[start] {
continue;
}
let mut stack = vec![start];
seen[start] = true;
let (mut area, mut sum) = (0_usize, [0.0, 0.0]);
while let Some(at) = stack.pop() {
area += 1;
let (cx, cy) = (at % side, at / side);
sum[0] += f64::from(u32::try_from(cx).unwrap_or(0));
sum[1] += f64::from(u32::try_from(cy).unwrap_or(0));
for (nx, ny) in [
(cx.wrapping_sub(1), cy),
(cx + 1, cy),
(cx, cy.wrapping_sub(1)),
(cx, cy + 1),
] {
if nx < side && ny < side && values[ny * side + nx] > 0.5 && !seen[ny * side + nx] {
seen[ny * side + nx] = true;
stack.push(ny * side + nx);
}
}
}
let count = f64::from(u32::try_from(area).unwrap_or(u32::MAX));
let centre = [sum[0] / count - reach_f, sum[1] / count - reach_f];
if centre[0].hypot(centre[1]) <= window
&& area >= HOLE_MIN_AREA
&& best.is_none_or(|(most, _)| area > most)
{
best = Some((area, centre));
}
}
let x_f = f64::from(i32::try_from(x).ok()?);
let y_f = f64::from(i32::try_from(y).ok()?);
best.map(|(_, centre)| [x_f + centre[0], y_f + centre[1]])
}
fn huber_translation(rows: &[([f64; 2], f64)]) -> ([f64; 2], Vec<f64>) {
let mut weights = vec![1.0; rows.len()];
let mut shift = [0.0, 0.0];
for _ in 0..10 {
let (mut xx, mut xy, mut yy) = (0.0, 0.0, 0.0);
let mut right = [0.0, 0.0];
for ((normal, target), weight) in rows.iter().zip(&weights) {
let squared = weight * weight;
xx += squared * normal[0] * normal[0];
xy += squared * normal[0] * normal[1];
yy += squared * normal[1] * normal[1];
right[0] += squared * normal[0] * target;
right[1] += squared * normal[1] * target;
}
let determinant = xx * yy - xy * xy;
if determinant.abs() < 1e-12 {
break;
}
shift = [
(yy * right[0] - xy * right[1]) / determinant,
(xx * right[1] - xy * right[0]) / determinant,
];
for ((normal, target), weight) in rows.iter().zip(weights.iter_mut()) {
let residual = (target - (normal[0] * shift[0] + normal[1] * shift[1])).abs();
*weight = if residual <= HUBER_PX {
1.0
} else {
(HUBER_PX / residual.max(1e-9)).sqrt()
};
}
}
let residuals = rows
.iter()
.map(|(normal, target)| target - (normal[0] * shift[0] + normal[1] * shift[1]))
.collect();
(shift, residuals)
}
fn rms_inliers(residuals: &[f64]) -> f64 {
if residuals.is_empty() {
return 0.0;
}
let mut sizes: Vec<f64> = residuals.iter().map(|r| r.abs()).collect();
sizes.sort_by(f64::total_cmp);
let median = sizes[sizes.len() / 2];
let bound = 3.0 * 1.4826 * median + 1.0;
let inliers: Vec<f64> = residuals
.iter()
.copied()
.filter(|r| r.abs() < bound)
.collect();
if inliers.is_empty() {
return 0.0;
}
let count = f64::from(u32::try_from(inliers.len()).unwrap_or(u32::MAX));
(inliers.iter().map(|r| r * r).sum::<f64>() / count).sqrt()
}
fn drawn(
mut frame: RgbImage,
samples: &Samples,
measured: &Measured,
landmarks: &[FoundLandmark],
calibration: &CameraCalibration,
) -> Result<Vec<u8>, ComposeError> {
const RED: Rgb<u8> = Rgb([255, 40, 40]);
const GREEN: Rgb<u8> = Rgb([40, 255, 40]);
const YELLOW: Rgb<u8> = Rgb([255, 230, 0]);
const CYAN: Rgb<u8> = Rgb([0, 230, 255]);
#[expect(
clippy::cast_possible_truncation,
reason = "a pixel of a frame of a few thousand pixels"
)]
let pixel = |[x, y]: [f64; 2]| (x.round() as i32, y.round() as i32);
for point in &samples.points {
let (x, y) = pixel(*point);
draw_cross_mut(&mut frame, RED, x, y);
}
if let Some(shift) = measured.shift {
for point in &samples.points {
let (x, y) = pixel([point[0] + shift[0], point[1] + shift[1]]);
draw_cross_mut(&mut frame, GREEN, x, y);
}
}
if let Some(hole) = measured.hole {
let (x, y) = pixel(hole);
draw_hollow_rect_mut(&mut frame, Rect::at(x - 6, y - 6).of_size(13, 13), YELLOW);
}
for (found, landmark) in landmarks.iter().zip(&calibration.landmarks) {
if !found.visible() {
continue;
}
let (x, y) = pixel([
landmark.center_px[0] + found.located.offset_px[0],
landmark.center_px[1] + found.located.offset_px[1],
]);
let colour = if found.distance_px() > calibration.drift_tolerance_px {
RED
} else {
CYAN
};
draw_hollow_rect_mut(&mut frame, Rect::at(x - 24, y - 24).of_size(49, 49), colour);
}
let mut jpeg = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
.encode_image(&frame)
.map_err(|error| ComposeError::Encode {
detail: error.to_string(),
})?;
Ok(jpeg)
}
#[cfg(test)]
mod tests {
use super::{SheetOutline, huber_translation, rms_inliers};
#[test]
fn both_committed_sheets_are_read_and_no_other_is_named() {
assert_eq!(
SheetOutline::committed_sheets(),
["smooth-pei", "textured-pei"]
);
for sheet in ["smooth-pei", "textured-pei"] {
let outline = SheetOutline::committed(sheet).expect("committed");
assert_eq!(outline.edges.len(), 4);
assert!(outline.hole_mm.is_some());
assert!(
outline
.edges
.iter()
.all(|edge| edge.profile_t_across_mm.len() >= 6)
);
}
assert!(SheetOutline::committed("satin-pei").is_none());
}
#[test]
fn the_huber_fit_finds_a_known_shift_through_an_outlier() {
let shift = [3.0, -2.0];
let mut rows: Vec<([f64; 2], f64)> = [[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.0, -1.0]]
.iter()
.cycle()
.take(40)
.map(|normal: &[f64; 2]| (*normal, normal[0] * shift[0] + normal[1] * shift[1]))
.collect();
rows.push(([1.0, 0.0], 40.0));
let (found, residuals) = huber_translation(&rows);
assert!(
(found[0] - 3.0).abs() < 0.2 && (found[1] + 2.0).abs() < 0.2,
"{found:?}"
);
assert!(rms_inliers(&residuals) < 0.5);
}
}