Skip to main content

printobserver_panels/
view.rs

1//! Whether the camera's view still matches what a check draws through.
2//!
3//! A calibration fixes where the camera looked when it was fitted, and a
4//! camera that shifts a little afterwards is ordinary on a real printer. A
5//! print's own first layer, once it is clearly found, says where the
6//! projection lands now ([`crate::alignment`]); that offset becomes the print's
7//! [`ViewCorrection`], a translation every later drawing of the print goes
8//! through. The landmarks found agreeing on the frame it was taken on are kept
9//! as its reference, and each later frame is judged against them
10//! ([`judge_view`]): landmarks that moved from the calibration but sit where
11//! the reference had them are the same shifted camera, and the frame is drawn
12//! through the correction; two or more that moved again mean the camera moved
13//! again.
14//!
15//! Landmark-fitted models were measured and rejected: on the first shifted
16//! print, every landmark found agreeing sat on one side of the frame, about
17//! 60 to 80 px off, while the part had moved about 15 px, so any model fitted
18//! to them landed the outline beside the part. The other three models stay in
19//! [`ViewModel`] so the record's shape need not change when one is earned.
20
21use image::GrayImage;
22use printobserver_types::schemars::JsonSchema;
23use printobserver_types::serde::{Deserialize, Serialize};
24
25use crate::calibration::CameraCalibration;
26use crate::compose::decode;
27use crate::drift::{
28    HIDDEN_BELOW, Located, VIEW_SEARCH_RADIUS_PX, check_frame, locate_landmarks_within,
29};
30use crate::error::ComposeError;
31
32/// How close two landmarks' offsets must be to count as agreeing, in pixels:
33/// the two that agreed on the first shifted print sat 20 px apart.
34pub const AGREEMENT_PX: f64 = 25.0;
35
36/// The model a [`ViewCorrection`] maps pixels by. Only [`Self::Translation`]
37/// is ever written.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
39#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
40#[schemars(crate = "printobserver_types::schemars")]
41pub enum ViewModel {
42    /// A shift alone.
43    Translation,
44    /// A shift, a rotation and one scale.
45    Similarity,
46    /// A general linear map and a shift.
47    Affine,
48    /// A plane-to-plane projective map.
49    Homography,
50}
51
52/// One landmark of a correction's reference: where it was found on the frame
53/// the correction was taken on.
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
55#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
56#[schemars(crate = "printobserver_types::schemars")]
57pub struct ReferenceLandmark {
58    /// The calibration's name for it.
59    pub name: String,
60    /// How far from its calibrated place it was found, `[dx, dy]` pixels.
61    pub offset_px: [f64; 2],
62    /// The correlation it was found at.
63    pub score: f64,
64}
65
66/// How a print's drawings map the calibrated view onto the current frame.
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
68#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
69#[schemars(crate = "printobserver_types::schemars")]
70pub struct ViewCorrection {
71    /// The model `matrix` is of.
72    pub model: ViewModel,
73    /// Maps a pixel of the calibrated view to the current frame, in
74    /// homogeneous coordinates, row by row.
75    pub matrix: [[f64; 3]; 3],
76    /// The landmarks found agreeing on the frame the correction was taken on,
77    /// which later frames are compared against.
78    pub landmarks: Vec<ReferenceLandmark>,
79    /// The RMS distance between those landmarks' offsets and the correction's
80    /// shift, in pixels: how far the landmarks disagree with the part.
81    pub residual_px: f64,
82}
83
84impl ViewCorrection {
85    /// The translation by `shift_px`, its reference `landmarks`.
86    #[must_use]
87    pub fn translation(shift_px: [f64; 2], landmarks: Vec<ReferenceLandmark>) -> Self {
88        let squares: Vec<f64> = landmarks
89            .iter()
90            .map(|landmark| {
91                let (dx, dy) = (
92                    landmark.offset_px[0] - shift_px[0],
93                    landmark.offset_px[1] - shift_px[1],
94                );
95                dx * dx + dy * dy
96            })
97            .collect();
98        let residual_px = if squares.is_empty() {
99            0.0
100        } else {
101            (squares.iter().sum::<f64>() / f64::from(u32::try_from(squares.len()).unwrap_or(1)))
102                .sqrt()
103        };
104        Self {
105            model: ViewModel::Translation,
106            matrix: [
107                [1.0, 0.0, shift_px[0]],
108                [0.0, 1.0, shift_px[1]],
109                [0.0, 0.0, 1.0],
110            ],
111            landmarks,
112            residual_px,
113        }
114    }
115
116    /// The shift the correction applies at the frame's origin, `[dx, dy]`.
117    #[must_use]
118    pub const fn shift_px(&self) -> [f64; 2] {
119        [self.matrix[0][2], self.matrix[1][2]]
120    }
121
122    /// Where one pixel of the calibrated view lands on the current frame.
123    #[must_use]
124    pub fn apply(&self, [x, y]: [f64; 2]) -> [f64; 2] {
125        let m = &self.matrix;
126        let w = m[2][0] * x + m[2][1] * y + m[2][2];
127        let w = if w.abs() < 1e-12 { 1.0 } else { w };
128        [
129            (m[0][0] * x + m[0][1] * y + m[0][2]) / w,
130            (m[1][0] * x + m[1][1] * y + m[1][2]) / w,
131        ]
132    }
133}
134
135/// What one judgement of the view found.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
137#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
138#[schemars(crate = "printobserver_types::schemars")]
139pub enum ViewOutcome {
140    /// No more than one found landmark sits beyond the calibration's
141    /// tolerance of its calibrated place: one alone is as likely a false match
142    /// as a moved camera.
143    Unshifted,
144    /// Landmarks moved from the calibration but agree with the reference of
145    /// the correction in force, so the frame is drawn through it.
146    Refit,
147    /// Fewer than two landmarks are found, or fewer than two of the
148    /// reference's are found again.
149    LandmarksNotFound,
150    /// Landmarks moved and no correction is in force, or two or more moved
151    /// beyond the tolerance from the correction's reference: the camera moved
152    /// again.
153    ViewRefitRejected,
154    /// The frame is not the calibration's size or stream.
155    FrameMismatch,
156}
157
158impl ViewOutcome {
159    /// Whether a frame so judged may be drawn on.
160    #[must_use]
161    pub const fn drawable(self) -> bool {
162        matches!(self, Self::Unshifted | Self::Refit)
163    }
164}
165
166/// One landmark as one frame showed it.
167#[derive(Debug, Clone, PartialEq)]
168pub struct FoundLandmark {
169    /// The calibration's name for it.
170    pub name: String,
171    /// Where and how well it was found.
172    pub located: Located,
173}
174
175impl FoundLandmark {
176    /// How far from its calibrated place it was found.
177    #[must_use]
178    pub fn distance_px(&self) -> f64 {
179        self.located.offset_px[0].hypot(self.located.offset_px[1])
180    }
181
182    /// Whether it was found at all, rather than hidden.
183    #[must_use]
184    pub fn visible(&self) -> bool {
185        self.located.score >= HIDDEN_BELOW
186    }
187}
188
189/// One judgement of the view.
190#[derive(Debug, Clone, PartialEq)]
191pub struct ViewJudgement {
192    /// What it found.
193    pub outcome: ViewOutcome,
194    /// Why the frame may not be drawn on, for the refusals.
195    pub reason: Option<String>,
196    /// Every landmark of the calibration as this frame showed it, in its
197    /// order.
198    pub landmarks: Vec<FoundLandmark>,
199}
200
201impl ViewJudgement {
202    /// The largest set of visible landmarks whose offsets all lie within
203    /// [`AGREEMENT_PX`] of one another: the reference a correction taken on
204    /// this frame keeps. Ties go to the set found the more surely.
205    #[must_use]
206    pub fn agreeing(&self) -> Vec<ReferenceLandmark> {
207        let visible: Vec<&FoundLandmark> = self.landmarks.iter().filter(|l| l.visible()).collect();
208        let mut best: Vec<&FoundLandmark> = Vec::new();
209        let mut best_score = f64::NEG_INFINITY;
210        let count = visible.len().min(16);
211        for mask in 1_u32..(1 << count) {
212            let members: Vec<&FoundLandmark> = (0..count)
213                .filter(|bit| mask & (1 << bit) != 0)
214                .map(|bit| visible[bit])
215                .collect();
216            let agree = members.iter().enumerate().all(|(i, a)| {
217                members.iter().skip(i + 1).all(|b| {
218                    (a.located.offset_px[0] - b.located.offset_px[0])
219                        .hypot(a.located.offset_px[1] - b.located.offset_px[1])
220                        <= AGREEMENT_PX
221                })
222            });
223            if !agree {
224                continue;
225            }
226            let score: f64 = members.iter().map(|l| f64::from(l.located.score)).sum();
227            if members.len() > best.len() || (members.len() == best.len() && score > best_score) {
228                best = members;
229                best_score = score;
230            }
231        }
232        best.into_iter()
233            .map(|landmark| ReferenceLandmark {
234                name: landmark.name.clone(),
235                offset_px: landmark.located.offset_px,
236                score: f64::from(landmark.located.score),
237            })
238            .collect()
239    }
240
241    /// Whether two or more visible landmarks sit beyond the calibration's
242    /// tolerance of their calibrated places.
243    #[must_use]
244    pub fn moved(&self, calibration: &CameraCalibration) -> bool {
245        self.landmarks
246            .iter()
247            .filter(|l| l.visible() && l.distance_px() > calibration.drift_tolerance_px)
248            .count()
249            >= 2
250    }
251}
252
253/// Judge one grey frame's view, against the reference of the correction in
254/// force when there is one, every landmark searched within
255/// [`VIEW_SEARCH_RADIUS_PX`].
256#[must_use]
257pub fn judge_view(
258    calibration: &CameraCalibration,
259    frame: &GrayImage,
260    correction: Option<&ViewCorrection>,
261) -> ViewJudgement {
262    judge_found(calibration, found_landmarks(calibration, frame), correction)
263}
264
265/// Every landmark of a calibration as one grey frame shows it, in its order,
266/// each searched within [`VIEW_SEARCH_RADIUS_PX`].
267#[must_use]
268pub fn found_landmarks(calibration: &CameraCalibration, frame: &GrayImage) -> Vec<FoundLandmark> {
269    calibration
270        .landmarks
271        .iter()
272        .zip(locate_landmarks_within(
273            calibration,
274            frame,
275            VIEW_SEARCH_RADIUS_PX,
276        ))
277        .map(|(landmark, located)| FoundLandmark {
278            name: landmark.name.clone(),
279            located,
280        })
281        .collect()
282}
283
284/// Judge a view from landmarks already found on its frame, against the
285/// reference of the correction in force when there is one.
286#[must_use]
287pub fn judge_found(
288    calibration: &CameraCalibration,
289    landmarks: Vec<FoundLandmark>,
290    correction: Option<&ViewCorrection>,
291) -> ViewJudgement {
292    let tolerance = calibration.drift_tolerance_px;
293    let judged = |outcome: ViewOutcome, reason: Option<String>, landmarks: Vec<FoundLandmark>| {
294        ViewJudgement {
295            outcome,
296            reason,
297            landmarks,
298        }
299    };
300    let visible = landmarks.iter().filter(|l| l.visible()).count();
301    let Some(correction) = correction else {
302        if visible < 2 {
303            return judged(
304                ViewOutcome::LandmarksNotFound,
305                Some(LANDMARKS_NOT_FOUND.to_owned()),
306                landmarks,
307            );
308        }
309        let furthest = landmarks
310            .iter()
311            .filter(|l| l.visible() && l.distance_px() > tolerance)
312            .max_by(|a, b| a.distance_px().total_cmp(&b.distance_px()));
313        let moved = landmarks
314            .iter()
315            .filter(|l| l.visible() && l.distance_px() > tolerance)
316            .count();
317        if moved >= 2
318            && let Some(furthest) = furthest
319        {
320            let reason = format!(
321                "the camera has shifted since it was calibrated, {} being {:.1} px from where it was, and no correction taken from this print's first layer is in force yet",
322                furthest.name,
323                furthest.distance_px()
324            );
325            return judged(ViewOutcome::ViewRefitRejected, Some(reason), landmarks);
326        }
327        return judged(ViewOutcome::Unshifted, None, landmarks);
328    };
329    let again: Vec<(&ReferenceLandmark, &FoundLandmark)> = correction
330        .landmarks
331        .iter()
332        .filter_map(|reference| {
333            landmarks
334                .iter()
335                .find(|found| found.name == reference.name && found.visible())
336                .map(|found| (reference, found))
337        })
338        .collect();
339    if again.len() < 2 {
340        return judged(
341            ViewOutcome::LandmarksNotFound,
342            Some(LANDMARKS_NOT_FOUND_AGAIN.to_owned()),
343            landmarks,
344        );
345    }
346    let from_reference = |(reference, found): &(&ReferenceLandmark, &FoundLandmark)| {
347        (found.located.offset_px[0] - reference.offset_px[0])
348            .hypot(found.located.offset_px[1] - reference.offset_px[1])
349    };
350    let moved_again: Vec<(&str, f64)> = again
351        .iter()
352        .map(|pair| (pair.0.name.as_str(), from_reference(pair)))
353        .filter(|(_, distance)| *distance > tolerance)
354        .collect();
355    if moved_again.len() >= 2 {
356        let (name, distance) = moved_again
357            .iter()
358            .copied()
359            .fold(
360                moved_again[0],
361                |far, next| if next.1 > far.1 { next } else { far },
362            );
363        let reason = format!(
364            "the camera has moved again since this print's first-layer correction was taken: {name} is {distance:.1} px from where that correction's frame had it"
365        );
366        return judged(ViewOutcome::ViewRefitRejected, Some(reason), landmarks);
367    }
368    let shifted = landmarks
369        .iter()
370        .filter(|l| l.visible() && l.distance_px() > tolerance)
371        .count()
372        >= 2;
373    let outcome = if shifted {
374        ViewOutcome::Refit
375    } else {
376        ViewOutcome::Unshifted
377    };
378    judged(outcome, None, landmarks)
379}
380
381/// Why a frame with fewer than two landmarks found is not drawn on.
382pub const LANDMARKS_NOT_FOUND: &str = "fewer than two of the calibration's landmarks are found in the frame, so whether the camera has shifted is unknown";
383
384/// Why a frame finding fewer than two of a correction's reference landmarks
385/// again is not drawn on.
386pub const LANDMARKS_NOT_FOUND_AGAIN: &str = "fewer than two of the landmarks this print's first-layer correction was taken against are found in the frame, so whether the camera has moved again is unknown";
387
388/// Every landmark of a calibration as one JPEG frame shows it, once the frame
389/// is held to the calibration's size and stream.
390///
391/// # Errors
392///
393/// [`ComposeError::Undecodable`] for a frame that is no JPEG, and
394/// [`ComposeError::FrameMismatch`] for one of another size or stream than the
395/// calibration's.
396pub fn landmarks_in_frame(
397    calibration: &CameraCalibration,
398    jpeg: &[u8],
399    camera_snapshot_url: &str,
400) -> Result<Vec<FoundLandmark>, ComposeError> {
401    let frame = decode(jpeg)?;
402    check_frame(
403        calibration,
404        [frame.width(), frame.height()],
405        camera_snapshot_url,
406    )?;
407    Ok(found_landmarks(
408        calibration,
409        &image::imageops::grayscale(&frame),
410    ))
411}