Skip to main content

qualia_vision/biosense/magnification/
gaussian_pyramid_build.rs

1//! Gaussian image pyramid (caller-buffered levels, fixed max depth).
2//!
3//! Tier-2 cold construction may pre-size buffers; hot downsample uses fixed 5-tap
4//! separable-style box average (no heap in the pixel loop).
5
6use crate::cv::error::CvError;
7
8/// Maximum pyramid depth (level 0 = full resolution).
9pub const MAX_PYRAMID_LEVELS: usize = 6;
10
11/// Per-level geometry written by [`gaussian_pyramid_build`].
12#[derive(Debug, Clone, Copy, Default)]
13pub struct PyramidLevelMeta {
14    pub width: u32,
15    pub height: u32,
16    /// Byte/element offset into the packed level buffer.
17    pub offset: usize,
18    pub len: usize,
19}
20
21/// Bytes (f32 elements) required for `n_levels` of a `width×height` Gaussian pyramid.
22pub fn gaussian_pyramid_scratch_elems(width: u32, height: u32, n_levels: usize) -> usize {
23    let n = n_levels.clamp(1, MAX_PYRAMID_LEVELS);
24    let mut w = width as usize;
25    let mut h = height as usize;
26    let mut total = 0usize;
27    for _ in 0..n {
28        total = total.saturating_add(w.saturating_mul(h));
29        w = (w / 2).max(1);
30        h = (h / 2).max(1);
31    }
32    total
33}
34
35/// Build a Gaussian pyramid into a packed caller buffer.
36///
37/// Level 0 copies `src` (`width*height` f32). Each subsequent level is a 2×
38/// spatial downsample of the previous (4-neighbor mean with edge clamp).
39///
40/// Returns number of levels written (≤ `n_levels`, stops early if dim stalls at 1×1).
41pub fn gaussian_pyramid_build(
42    src: &[f32],
43    width: u32,
44    height: u32,
45    n_levels: usize,
46    out_packed: &mut [f32],
47    meta: &mut [PyramidLevelMeta; MAX_PYRAMID_LEVELS],
48) -> Result<usize, CvError> {
49    if width == 0 || height == 0 || n_levels == 0 {
50        return Err(CvError::InvalidParameter);
51    }
52    let n_req = n_levels.min(MAX_PYRAMID_LEVELS);
53    let need = width as usize * height as usize;
54    if src.len() < need {
55        return Err(CvError::BufferTooSmall);
56    }
57    let scratch_need = gaussian_pyramid_scratch_elems(width, height, n_req);
58    if out_packed.len() < scratch_need {
59        return Err(CvError::BufferTooSmall);
60    }
61
62    // Level 0
63    out_packed[..need].copy_from_slice(&src[..need]);
64    meta[0] = PyramidLevelMeta {
65        width,
66        height,
67        offset: 0,
68        len: need,
69    };
70
71    let mut levels = 1usize;
72    let mut prev_w = width as usize;
73    let mut prev_h = height as usize;
74    let mut prev_off = 0usize;
75
76    while levels < n_req {
77        let next_w = (prev_w / 2).max(1);
78        let next_h = (prev_h / 2).max(1);
79        if next_w == prev_w && next_h == prev_h {
80            break; // cannot refine further
81        }
82        let next_len = next_w * next_h;
83        let next_off = prev_off + prev_w * prev_h;
84        if next_off + next_len > out_packed.len() {
85            return Err(CvError::BufferTooSmall);
86        }
87
88        for y in 0..next_h {
89            for x in 0..next_w {
90                let x0 = (x * 2).min(prev_w - 1);
91                let y0 = (y * 2).min(prev_h - 1);
92                let x1 = (x0 + 1).min(prev_w - 1);
93                let y1 = (y0 + 1).min(prev_h - 1);
94                let base = prev_off;
95                let a = out_packed[base + y0 * prev_w + x0];
96                let b = out_packed[base + y0 * prev_w + x1];
97                let c = out_packed[base + y1 * prev_w + x0];
98                let d = out_packed[base + y1 * prev_w + x1];
99                out_packed[next_off + y * next_w + x] = 0.25 * (a + b + c + d);
100            }
101        }
102
103        meta[levels] = PyramidLevelMeta {
104            width: next_w as u32,
105            height: next_h as u32,
106            offset: next_off,
107            len: next_len,
108        };
109        prev_w = next_w;
110        prev_h = next_h;
111        prev_off = next_off;
112        levels += 1;
113    }
114
115    // Zero unused meta slots
116    for m in meta.iter_mut().skip(levels) {
117        *m = PyramidLevelMeta::default();
118    }
119    Ok(levels)
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn level0_matches_source() {
128        let w = 4u32;
129        let h = 4u32;
130        let mut src = [0.0f32; 16];
131        for i in 0..16 {
132            src[i] = i as f32;
133        }
134        let need = gaussian_pyramid_scratch_elems(w, h, 3);
135        let mut out = vec![0.0f32; need];
136        let mut meta = [PyramidLevelMeta::default(); MAX_PYRAMID_LEVELS];
137        let n = gaussian_pyramid_build(&src, w, h, 3, &mut out, &mut meta).unwrap();
138        assert!(n >= 2);
139        assert_eq!(meta[0].width, 4);
140        assert_eq!(meta[0].height, 4);
141        for i in 0..16 {
142            assert!((out[i] - src[i]).abs() < 1e-6);
143        }
144        assert_eq!(meta[1].width, 2);
145        assert_eq!(meta[1].height, 2);
146    }
147
148    #[test]
149    fn rejects_empty() {
150        let mut out = [0.0f32; 4];
151        let mut meta = [PyramidLevelMeta::default(); MAX_PYRAMID_LEVELS];
152        assert!(gaussian_pyramid_build(&[], 0, 0, 2, &mut out, &mut meta).is_err());
153    }
154}