Skip to main content

visloc_objects/
bbox.rs

1//! Axis-aligned image boxes and detections.
2
3/// An axis-aligned box in pixel coordinates, `[x_min, x_max] × [y_min, y_max]`.
4#[derive(Debug, Clone, Copy, PartialEq)]
5pub struct BBox {
6    pub x_min: f64,
7    pub y_min: f64,
8    pub x_max: f64,
9    pub y_max: f64,
10}
11
12impl BBox {
13    pub const fn new(x_min: f64, y_min: f64, x_max: f64, y_max: f64) -> Self {
14        Self {
15            x_min,
16            y_min,
17            x_max,
18            y_max,
19        }
20    }
21
22    /// A box from its top-left corner and size.
23    pub fn from_xywh(x: f64, y: f64, width: f64, height: f64) -> Self {
24        Self::new(x, y, x + width, y + height)
25    }
26
27    /// A box from its centre and size.
28    pub fn from_center_size(cx: f64, cy: f64, width: f64, height: f64) -> Self {
29        Self::new(
30            cx - 0.5 * width,
31            cy - 0.5 * height,
32            cx + 0.5 * width,
33            cy + 0.5 * height,
34        )
35    }
36
37    pub fn width(&self) -> f64 {
38        (self.x_max - self.x_min).max(0.0)
39    }
40
41    pub fn height(&self) -> f64 {
42        (self.y_max - self.y_min).max(0.0)
43    }
44
45    pub fn area(&self) -> f64 {
46        self.width() * self.height()
47    }
48
49    pub fn center(&self) -> (f64, f64) {
50        (
51            0.5 * (self.x_min + self.x_max),
52            0.5 * (self.y_min + self.y_max),
53        )
54    }
55
56    /// Finite corners and a positive width and height.
57    pub fn is_valid(&self) -> bool {
58        [self.x_min, self.y_min, self.x_max, self.y_max]
59            .iter()
60            .all(|v| v.is_finite())
61            && self.x_max > self.x_min
62            && self.y_max > self.y_min
63    }
64
65    /// This box, found in an image turned `degrees` clockwise (0, 90, 180 or
66    /// 270; other values leave it as it is), in the pixels of the original
67    /// `width` × `height` image. For cameras mounted sideways, whose frames
68    /// are turned upright before detection.
69    pub fn unrotated(&self, degrees: u32, width: f64, height: f64) -> BBox {
70        let b = self;
71        match degrees {
72            // Turned clockwise by 90: original (x, y) is at (height - y, x).
73            90 => BBox::new(b.y_min, height - b.x_max, b.y_max, height - b.x_min),
74            180 => BBox::new(
75                width - b.x_max,
76                height - b.y_max,
77                width - b.x_min,
78                height - b.y_min,
79            ),
80            // Turned clockwise by 270: original (x, y) is at (y, width - x).
81            270 => BBox::new(width - b.y_max, b.x_min, width - b.y_min, b.x_max),
82            _ => *b,
83        }
84    }
85
86    /// Intersection over union, 0 when the boxes do not overlap or are empty.
87    pub fn iou(&self, other: &BBox) -> f64 {
88        let width = (self.x_max.min(other.x_max) - self.x_min.max(other.x_min)).max(0.0);
89        let height = (self.y_max.min(other.y_max) - self.y_min.max(other.y_min)).max(0.0);
90        let intersection = width * height;
91        let union = self.area() + other.area() - intersection;
92        if union > 0.0 {
93            intersection / union
94        } else {
95            0.0
96        }
97    }
98}
99
100/// One detector output: a box, its confidence and its class.
101#[derive(Debug, Clone, Copy, PartialEq)]
102pub struct Detection {
103    pub bbox: BBox,
104    /// Detector confidence, in [0, 1].
105    pub score: f64,
106    /// The detector's class index (for example a COCO label).
107    pub class_id: u32,
108}
109
110impl Detection {
111    pub const fn new(bbox: BBox, score: f64, class_id: u32) -> Self {
112        Self {
113            bbox,
114            score,
115            class_id,
116        }
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn iou_of_identical_disjoint_and_half_overlapping_boxes() {
126        let a = BBox::from_xywh(0.0, 0.0, 10.0, 10.0);
127        assert_eq!(a.iou(&a), 1.0);
128        assert_eq!(a.iou(&BBox::from_xywh(20.0, 0.0, 10.0, 10.0)), 0.0);
129        // Overlap 5×10 = 50, union 150.
130        let b = BBox::from_xywh(5.0, 0.0, 10.0, 10.0);
131        assert!((a.iou(&b) - 50.0 / 150.0).abs() < 1e-12);
132        assert_eq!(a.iou(&b), b.iou(&a));
133    }
134
135    #[test]
136    fn unrotated_undoes_image_rotation() {
137        // One lit pixel at (5, 2) in a 7 × 4 image; find it in each rotated
138        // image and map its pixel square back.
139        let mut original = image::GrayImage::new(7, 4);
140        original.put_pixel(5, 2, image::Luma([255]));
141        for degrees in [0, 90, 180, 270] {
142            let rotated = match degrees {
143                90 => image::imageops::rotate90(&original),
144                180 => image::imageops::rotate180(&original),
145                270 => image::imageops::rotate270(&original),
146                _ => original.clone(),
147            };
148            let (u, v, _) = rotated
149                .enumerate_pixels()
150                .find(|(_, _, p)| p[0] == 255)
151                .unwrap();
152            let found = BBox::from_xywh(f64::from(u), f64::from(v), 1.0, 1.0);
153            assert_eq!(
154                found.unrotated(degrees, 7.0, 4.0),
155                BBox::from_xywh(5.0, 2.0, 1.0, 1.0),
156                "{degrees} degrees"
157            );
158        }
159    }
160
161    #[test]
162    fn degenerate_boxes_are_invalid_and_have_zero_iou() {
163        let empty = BBox::new(5.0, 5.0, 5.0, 9.0);
164        assert!(!empty.is_valid());
165        assert!(!BBox::new(0.0, 0.0, f64::NAN, 1.0).is_valid());
166        assert_eq!(empty.iou(&empty), 0.0);
167        assert!(BBox::from_center_size(1.0, 2.0, 3.0, 4.0).is_valid());
168    }
169}