Skip to main content

printobserver_panels/
calibration.rs

1//! One printer's camera calibration: the file `tools/camera-calibration`
2//! writes, validated as it is read, and the projection it defines.
3//!
4//! The lens is `OpenCV`'s fisheye (equidistant) model; the bed frame is the
5//! G-code's own (X right, Y back, Z up, millimetres), and the pose maps it to
6//! the camera in `OpenCV`'s convention. On a bed-z printer the bed drops as the
7//! print rises, so with the print at height `z` a point `(x, y, h)` of the part
8//! sits at `(x, y, h - z)`: the layer being printed always lies at the
9//! nozzle's plane.
10
11use base64::Engine as _;
12use image::GrayImage;
13use nalgebra::{Rotation3, Vector3};
14use printobserver_types::schemars::JsonSchema;
15use printobserver_types::serde::{Deserialize, Serialize};
16
17/// The calibration file's one schema version.
18pub const SCHEMA_VERSION: u32 = 1;
19
20/// The furthest a landmark is searched for, in pixels: the drift check scores
21/// every offset within it, so a radius past this is no landmark search.
22pub const MAX_SEARCH_RADIUS_PX: u32 = 256;
23
24/// How the printer moves its bed: the one motion a calibration describes.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
26#[serde(crate = "printobserver_types::serde")]
27#[schemars(crate = "printobserver_types::schemars")]
28pub enum Motion {
29    /// The bed moves only in Z, dropping as the print rises.
30    #[serde(rename = "bed-z")]
31    BedZ,
32}
33
34/// The lens: focal lengths and principal point in pixels, and the fisheye
35/// distortion terms `k1`–`k4`.
36#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
37#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
38#[schemars(crate = "printobserver_types::schemars")]
39pub struct Intrinsics {
40    /// Focal length along X, in pixels.
41    pub fx: f64,
42    /// Focal length along Y, in pixels.
43    pub fy: f64,
44    /// Principal point, X.
45    pub cx: f64,
46    /// Principal point, Y.
47    pub cy: f64,
48    /// The equidistant model's `k1`–`k4`; the tool fits `k1` and writes the
49    /// rest as 0.
50    pub k: [f64; 4],
51}
52
53/// Where the bed is, seen from the camera: the transform from the bed frame
54/// to the camera's, `X_cam = R · X_bed + t`.
55#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
56#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
57#[schemars(crate = "printobserver_types::schemars")]
58pub struct BedPose {
59    /// `R` as a Rodrigues vector, in radians.
60    pub rotation_rodrigues: [f64; 3],
61    /// `t`, in millimetres.
62    pub translation_mm: [f64; 3],
63}
64
65/// A fixed chassis feature the drift check locates in every frame.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
67#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
68#[schemars(crate = "printobserver_types::schemars")]
69pub struct Landmark {
70    /// What it is.
71    pub name: String,
72    /// Where its patch's centre was in the calibrated frames, in pixels.
73    pub center_px: [f64; 2],
74    /// The grey patch around it, as a base64 PNG.
75    pub patch_png_base64: String,
76    /// How far from `center_px` it is searched for, in pixels.
77    pub search_radius_px: u32,
78}
79
80/// How well the fit went.
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
82#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
83#[schemars(crate = "printobserver_types::schemars")]
84pub struct Fit {
85    /// The RMS distance of the marks from their projected outlines, in
86    /// pixels.
87    pub rms_reprojection_px: f64,
88    /// How many frames the marks were on.
89    pub frames: u32,
90    /// The date the frames were taken, `YYYY-MM-DD`.
91    // llmlint: ignore[invalid_states_unrepresentable] See suppressions.toml.
92    pub calibrated_at: String,
93}
94
95/// One printer's camera calibration, as `tools/camera-calibration` writes it.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
97#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
98#[schemars(crate = "printobserver_types::schemars")]
99pub struct CameraCalibration {
100    /// Always [`SCHEMA_VERSION`], which the generated schema pins, so the
101    /// calibration tool's tests refuse a file of any other version.
102    #[schemars(range(min = 1, max = 1))]
103    pub schema_version: u32,
104    /// How the printer moves its bed.
105    pub motion: Motion,
106    /// The calibrated frames' size, `[width, height]`; a frame of any other
107    /// size is refused, never scaled.
108    pub image_size_px: [u32; 2],
109    /// The lens.
110    pub intrinsics: Intrinsics,
111    /// The bed's pose.
112    pub bed_pose: BedPose,
113    /// The drift check's landmarks.
114    pub landmarks: Vec<Landmark>,
115    /// How far, in pixels, two visible landmarks must both have moved for the
116    /// camera to count as moved.
117    pub drift_tolerance_px: f64,
118    /// The `[camera] snapshot_url` the calibrated frames came from; a frame
119    /// from any other is refused.
120    // llmlint: ignore[invalid_states_unrepresentable] See suppressions.toml.
121    pub camera_snapshot_url: String,
122    /// The first-layer alignment check's pass threshold, in pixels.
123    pub alignment_max_offset_px: f64,
124    /// How well the fit went.
125    pub fit: Fit,
126    /// Each landmark's patch, decoded once as the file is read.
127    #[serde(skip)]
128    #[schemars(skip)]
129    patches: Vec<GrayImage>,
130}
131
132/// Why a calibration file was refused.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub enum CalibrationError {
135    /// It is not JSON of the calibration's shape.
136    Shape {
137        /// What the parser said.
138        detail: String,
139    },
140    /// A value is out of what a calibration can hold.
141    Invalid {
142        /// The key, as the file spells it.
143        field: &'static str,
144        /// Why.
145        reason: String,
146    },
147}
148
149impl core::fmt::Display for CalibrationError {
150    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151        match self {
152            Self::Shape { detail } => write!(formatter, "not a camera calibration: {detail}"),
153            Self::Invalid { field, reason } => write!(formatter, "`{field}` {reason}"),
154        }
155    }
156}
157
158impl std::error::Error for CalibrationError {}
159
160/// Refuse one field.
161fn invalid(field: &'static str, reason: impl Into<String>) -> CalibrationError {
162    CalibrationError::Invalid {
163        field,
164        reason: reason.into(),
165    }
166}
167
168/// Whether text is a calendar date written `YYYY-MM-DD`.
169fn is_date(text: &str) -> bool {
170    chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d").is_ok() && text.len() == 10
171}
172
173/// Refuse a number that is not finite, or not above zero when it must be.
174fn finite(field: &'static str, values: &[f64], positive: bool) -> Result<(), CalibrationError> {
175    for value in values {
176        if !value.is_finite() {
177            return Err(invalid(field, "is not a finite number"));
178        }
179        if positive && *value <= 0.0 {
180            return Err(invalid(field, "must be above zero"));
181        }
182    }
183    Ok(())
184}
185
186impl CameraCalibration {
187    /// Read and validate a calibration file.
188    ///
189    /// # Errors
190    ///
191    /// [`CalibrationError::Shape`] for anything that is not the file's shape,
192    /// and [`CalibrationError::Invalid`] naming the key that holds a value no
193    /// calibration can: another schema version, an empty or non-finite size,
194    /// focal length or tolerance, a snapshot URL that is no address, or a
195    /// landmark whose patch is not a PNG or whose search radius is zero.
196    pub fn from_json(bytes: &[u8]) -> Result<Self, CalibrationError> {
197        let mut calibration: Self =
198            printobserver_types::serde_json::from_slice(bytes).map_err(|error| {
199                CalibrationError::Shape {
200                    detail: error.to_string(),
201                }
202            })?;
203        if calibration.schema_version != SCHEMA_VERSION {
204            return Err(invalid(
205                "schema_version",
206                format!(
207                    "is {}, and this program reads version {SCHEMA_VERSION}",
208                    calibration.schema_version
209                ),
210            ));
211        }
212        if calibration.image_size_px.contains(&0) {
213            return Err(invalid("image_size_px", "names an empty frame"));
214        }
215        let lens = calibration.intrinsics;
216        finite("intrinsics.fx", &[lens.fx, lens.fy], true)?;
217        finite("intrinsics.cx", &[lens.cx, lens.cy], false)?;
218        finite("intrinsics.k", &lens.k, false)?;
219        finite(
220            "bed_pose.rotation_rodrigues",
221            &calibration.bed_pose.rotation_rodrigues,
222            false,
223        )?;
224        finite(
225            "bed_pose.translation_mm",
226            &calibration.bed_pose.translation_mm,
227            false,
228        )?;
229        finite(
230            "drift_tolerance_px",
231            &[calibration.drift_tolerance_px],
232            true,
233        )?;
234        finite(
235            "alignment_max_offset_px",
236            &[calibration.alignment_max_offset_px],
237            true,
238        )?;
239        printobserver_vision_api::WebAddress::new(&calibration.camera_snapshot_url)
240            .map_err(|why| invalid("camera_snapshot_url", why))?;
241        if !is_date(&calibration.fit.calibrated_at) {
242            return Err(invalid("fit.calibrated_at", "is not a YYYY-MM-DD date"));
243        }
244        // The drift check rules only on two visible landmarks; a file naming
245        // fewer, or one landmark twice, could never rule or would count one
246        // feature as two.
247        let names: std::collections::BTreeSet<&str> = calibration
248            .landmarks
249            .iter()
250            .map(|landmark| landmark.name.as_str())
251            .collect();
252        if names.len() < 2 || names.len() != calibration.landmarks.len() {
253            return Err(invalid(
254                "landmarks",
255                "must name at least two chassis landmarks, each once",
256            ));
257        }
258        let mut patches = Vec::with_capacity(calibration.landmarks.len());
259        for landmark in &calibration.landmarks {
260            finite("landmarks.center_px", &landmark.center_px, false)?;
261            let [w, h] = calibration.image_size_px.map(f64::from);
262            if !((0.0..w).contains(&landmark.center_px[0])
263                && (0.0..h).contains(&landmark.center_px[1]))
264            {
265                return Err(invalid("landmarks.center_px", "lies outside the frame"));
266            }
267            if !(1..=MAX_SEARCH_RADIUS_PX).contains(&landmark.search_radius_px) {
268                return Err(invalid(
269                    "landmarks.search_radius_px",
270                    format!("must be from 1 to {MAX_SEARCH_RADIUS_PX}"),
271                ));
272            }
273            let png = base64::engine::general_purpose::STANDARD
274                .decode(&landmark.patch_png_base64)
275                .map_err(|error| invalid("landmarks.patch_png_base64", error.to_string()))?;
276            let patch = image::load_from_memory_with_format(&png, image::ImageFormat::Png)
277                .map_err(|error| invalid("landmarks.patch_png_base64", error.to_string()))?
278                .to_luma8();
279            if patch.width() < 2 || patch.height() < 2 {
280                return Err(invalid("landmarks.patch_png_base64", "is no patch"));
281            }
282            patches.push(patch);
283        }
284        calibration.patches = patches;
285        Ok(calibration)
286    }
287
288    /// Each landmark's decoded patch, in `landmarks`' order.
289    pub(crate) fn patches(&self) -> &[GrayImage] {
290        &self.patches
291    }
292
293    /// Where bed points appear in a frame, in the calibration's pixels: each
294    /// `[x, y, h]` of the part, with the print at `print_z_mm`. `None` for a
295    /// point behind the camera or outside a frame of `frame_size_px`.
296    #[must_use]
297    pub fn project(
298        &self,
299        points_mm: &[[f64; 3]],
300        print_z_mm: f64,
301        frame_size_px: [u32; 2],
302    ) -> Vec<Option<[f64; 2]>> {
303        let [w, h] = frame_size_px.map(f64::from);
304        let projector = self.projector();
305        points_mm
306            .iter()
307            .map(|point| {
308                projector
309                    .pixel([point[0], point[1], point[2] - print_z_mm])
310                    .filter(|[u, v]| (0.0..w).contains(u) && (0.0..h).contains(v))
311            })
312            .collect()
313    }
314
315    /// The projection, ready to map many points.
316    pub(crate) fn projector(&self) -> Projector {
317        let [rx, ry, rz] = self.bed_pose.rotation_rodrigues;
318        let [tx, ty, tz] = self.bed_pose.translation_mm;
319        Projector {
320            rotation: Rotation3::new(Vector3::new(rx, ry, rz)),
321            translation: Vector3::new(tx, ty, tz),
322            lens: self.intrinsics,
323        }
324    }
325
326    /// Where the camera's centre is, in bed millimetres with the nozzle's
327    /// plane at height 0: `-Rᵀ t`.
328    #[must_use]
329    pub fn camera_centre_mm(&self) -> [f64; 3] {
330        let projector = self.projector();
331        let centre = -(projector.rotation.inverse() * projector.translation);
332        [centre.x, centre.y, centre.z]
333    }
334
335    /// A copy whose bed pose is another: what a test moves a projection with.
336    #[must_use]
337    pub fn with_bed_pose(&self, bed_pose: BedPose) -> Self {
338        Self {
339            bed_pose,
340            ..self.clone()
341        }
342    }
343}
344
345/// The fisheye projection of one calibration.
346#[derive(Debug, Clone, Copy)]
347pub(crate) struct Projector {
348    /// `R`.
349    rotation: Rotation3<f64>,
350    /// `t`.
351    translation: Vector3<f64>,
352    /// The lens.
353    lens: Intrinsics,
354}
355
356impl Projector {
357    /// Where a world point (bed frame, already lowered by the print height)
358    /// lands, unbounded by any frame; `None` behind the camera.
359    pub(crate) fn pixel(&self, world: [f64; 3]) -> Option<[f64; 2]> {
360        let camera = self.rotation * Vector3::new(world[0], world[1], world[2]) + self.translation;
361        if camera.z <= 1e-6 {
362            return None;
363        }
364        let (a, b) = (camera.x / camera.z, camera.y / camera.z);
365        let r = a.hypot(b);
366        let theta = r.atan();
367        let t2 = theta * theta;
368        let [k1, k2, k3, k4] = self.lens.k;
369        let theta_d = theta * (1.0 + t2 * (k1 + t2 * (k2 + t2 * (k3 + t2 * k4))));
370        let scale = if r > 1e-12 { theta_d / r } else { 1.0 };
371        Some([
372            self.lens.fx * a * scale + self.lens.cx,
373            self.lens.fy * b * scale + self.lens.cy,
374        ])
375    }
376}