Skip to main content

visloc_objects/
detector.rs

1//! The object-detector boundary.
2
3use std::fmt;
4
5use crate::bbox::Detection;
6use crate::image::RgbImage;
7
8/// Finds objects in one image. The tracker only needs the resulting
9/// [`Detection`]s, so any detector, learned or replayed, plugs in here.
10pub trait ObjectDetector {
11    type Error: std::error::Error + Send + Sync + 'static;
12
13    /// The detections in `image`, in pixel coordinates of `image`.
14    fn detect(&mut self, image: &RgbImage) -> Result<Vec<Detection>, Self::Error>;
15}
16
17/// Returns stored detections frame by frame and ignores the image: ground
18/// truth, a detector's output saved earlier, or synthetic boxes in tests.
19#[derive(Debug, Clone, Default)]
20pub struct ReplayDetector {
21    frames: Vec<Vec<Detection>>,
22    next: usize,
23}
24
25impl ReplayDetector {
26    pub fn new(frames: Vec<Vec<Detection>>) -> Self {
27        Self { frames, next: 0 }
28    }
29
30    /// Frames not replayed yet.
31    pub fn remaining(&self) -> usize {
32        self.frames.len() - self.next
33    }
34}
35
36/// [`ReplayDetector`] was asked for more frames than it holds.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct ReplayExhausted {
39    pub frames: usize,
40}
41
42impl fmt::Display for ReplayExhausted {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "all {} replayed frames were used", self.frames)
45    }
46}
47
48impl std::error::Error for ReplayExhausted {}
49
50impl ObjectDetector for ReplayDetector {
51    type Error = ReplayExhausted;
52
53    fn detect(&mut self, _image: &RgbImage) -> Result<Vec<Detection>, Self::Error> {
54        let frame = self.frames.get(self.next).ok_or(ReplayExhausted {
55            frames: self.frames.len(),
56        })?;
57        self.next += 1;
58        Ok(frame.clone())
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65    use crate::bbox::BBox;
66
67    #[test]
68    fn replays_frames_in_order_then_reports_exhaustion() {
69        let a = Detection::new(BBox::from_xywh(0.0, 0.0, 10.0, 20.0), 0.9, 0);
70        let mut detector = ReplayDetector::new(vec![vec![a], vec![]]);
71        let image = RgbImage::from_gray(1, 1, &[0]).unwrap();
72        assert_eq!(detector.detect(&image).unwrap(), vec![a]);
73        assert_eq!(detector.remaining(), 1);
74        assert!(detector.detect(&image).unwrap().is_empty());
75        assert_eq!(detector.detect(&image), Err(ReplayExhausted { frames: 2 }));
76    }
77}