Skip to main content

adk_vision/geometry/
mask.rs

1//! [`Mask`]: a binary mask, run-length encoded in COCO's column-major order.
2
3use serde::{Deserialize, Serialize};
4
5use super::BBox;
6
7/// A binary mask, run-length encoded in COCO's column-major order: `counts` alternates runs
8/// of unset and set pixels, starting with unset, scanning each column top to bottom, columns
9/// left to right. The runs always sum to `width × height`.
10///
11/// # Example
12///
13/// ```
14/// use adk_vision::{BBox, Mask};
15///
16/// let mask = Mask::from_box(4, 3, &BBox::new(1.0, 1.0, 3.0, 2.0));
17/// assert_eq!(mask.counts, vec![4, 1, 2, 1, 4]);
18/// assert_eq!(mask.area(), 2);
19/// assert_eq!(Mask::encode(4, 3, &mask.decode()), mask);
20/// ```
21#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(try_from = "MaskWire")]
23pub struct Mask {
24    /// Width of the raster.
25    pub width: u32,
26    /// Height of the raster.
27    pub height: u32,
28    /// Alternating run lengths, unset first.
29    pub counts: Vec<u32>,
30}
31
32#[derive(Deserialize)]
33struct MaskWire {
34    width: u32,
35    height: u32,
36    counts: Vec<u32>,
37}
38
39impl TryFrom<MaskWire> for Mask {
40    type Error = String;
41
42    fn try_from(wire: MaskWire) -> Result<Self, Self::Error> {
43        let total: u64 = wire.counts.iter().map(|&c| u64::from(c)).sum();
44        let expected = u64::from(wire.width) * u64::from(wire.height);
45        if total != expected {
46            return Err(format!(
47                "mask runs sum to {total}, but a {}x{} mask has {expected} pixels",
48                wire.width, wire.height
49            ));
50        }
51        Ok(Self { width: wire.width, height: wire.height, counts: wire.counts })
52    }
53}
54
55impl Mask {
56    /// A mask with no pixel set.
57    pub fn empty(width: u32, height: u32) -> Self {
58        let total = width.saturating_mul(height);
59        Self { width, height, counts: if total == 0 { Vec::new() } else { vec![total] } }
60    }
61
62    /// Encodes a row-major bitmap of `width × height` pixels.
63    ///
64    /// # Panics
65    ///
66    /// Panics when `bits` is not `width × height` long.
67    pub fn encode(width: u32, height: u32, bits: &[bool]) -> Self {
68        let (w, h) = (width as usize, height as usize);
69        assert_eq!(bits.len(), w * h, "a {width}x{height} mask needs {} bits", w * h);
70        let mut counts = Vec::new();
71        let mut current = false;
72        let mut run = 0u32;
73        for x in 0..w {
74            for y in 0..h {
75                let bit = bits[y * w + x];
76                if bit != current {
77                    counts.push(run);
78                    run = 0;
79                    current = bit;
80                }
81                run += 1;
82            }
83        }
84        if w * h > 0 {
85            counts.push(run);
86        }
87        Self { width, height, counts }
88    }
89
90    /// Decodes to a row-major bitmap of `width × height` pixels.
91    pub fn decode(&self) -> Vec<bool> {
92        let (w, h) = (self.width as usize, self.height as usize);
93        let mut bits = vec![false; w * h];
94        let mut index = 0usize;
95        for (run, &count) in self.counts.iter().enumerate() {
96            let set = run % 2 == 1;
97            for i in index..(index + count as usize).min(w * h) {
98                if set {
99                    let (x, y) = (i / h, i % h);
100                    bits[y * w + x] = true;
101                }
102            }
103            index += count as usize;
104        }
105        bits
106    }
107
108    /// A mask with every pixel whose centre lies in `bbox` set.
109    pub fn from_box(width: u32, height: u32, bbox: &BBox) -> Self {
110        let mut bits = vec![false; width as usize * height as usize];
111        for y in 0..height {
112            for x in 0..width {
113                if bbox.contains([x as f32 + 0.5, y as f32 + 0.5]) {
114                    bits[y as usize * width as usize + x as usize] = true;
115                }
116            }
117        }
118        Self::encode(width, height, &bits)
119    }
120
121    /// The number of set pixels.
122    pub fn area(&self) -> u64 {
123        self.counts.iter().skip(1).step_by(2).map(|&c| u64::from(c)).sum()
124    }
125
126    /// The smallest box covering every set pixel, or `None` for an empty mask.
127    pub fn bbox(&self) -> Option<BBox> {
128        let h = u64::from(self.height);
129        if h == 0 {
130            return None;
131        }
132        let mut bounds: Option<(u64, u64, u64, u64)> = None;
133        let mut index = 0u64;
134        for (run, &count) in self.counts.iter().enumerate() {
135            let (start, len) = (index, u64::from(count));
136            index += len;
137            if run % 2 == 0 || len == 0 {
138                continue;
139            }
140            let end = start + len - 1;
141            let (c0, c1) = (start / h, end / h);
142            let (r0, r1) = if c0 == c1 { (start % h, end % h) } else { (0, h - 1) };
143            bounds = Some(match bounds {
144                None => (c0, r0, c1, r1),
145                Some((x0, y0, x1, y1)) => (x0.min(c0), y0.min(r0), x1.max(c1), y1.max(r1)),
146            });
147        }
148        bounds.map(|(x0, y0, x1, y1)| {
149            BBox::new(x0 as f32, y0 as f32, (x1 + 1) as f32, (y1 + 1) as f32)
150        })
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn invalid_runs_are_refused_on_deserialization() {
160        let err =
161            serde_json::from_str::<Mask>(r#"{"width":2,"height":2,"counts":[1,1]}"#).unwrap_err();
162        assert!(err.to_string().contains("sum to 2"));
163    }
164
165    #[test]
166    fn a_full_mask_starts_with_an_empty_run() {
167        let mask = Mask::encode(2, 2, &[true; 4]);
168        assert_eq!(mask.counts, vec![0, 4]);
169        assert_eq!(mask.bbox(), Some(BBox::new(0.0, 0.0, 2.0, 2.0)));
170    }
171
172    #[test]
173    fn spanning_runs_cover_full_rows() {
174        // Column 0 rows 1..3 and column 1 rows 0..1 are one run in column-major order.
175        let mut bits = vec![false; 6];
176        bits[2] = true; // (0,1)
177        bits[4] = true; // (0,2)
178        bits[1] = true; // (1,0)
179        let mask = Mask::encode(2, 3, &bits);
180        assert_eq!(mask.counts, vec![1, 3, 2]);
181        assert_eq!(mask.bbox(), Some(BBox::new(0.0, 0.0, 2.0, 3.0)));
182    }
183}