Skip to main content

qualia_vision/biosense/magnification/
pyramid_reconstruct.rs

1//! Reconstruct an image from a Laplacian pyramid (caller-buffered).
2
3use super::gaussian_pyramid_build::{PyramidLevelMeta, MAX_PYRAMID_LEVELS};
4use crate::cv::error::CvError;
5
6fn expand_add(
7    coarse: &[f32],
8    cw: usize,
9    ch: usize,
10    parent_w: usize,
11    parent_h: usize,
12    lap: &[f32],
13    dest: &mut [f32],
14) {
15    for y in 0..parent_h {
16        let cy = (y / 2).min(ch - 1);
17        for x in 0..parent_w {
18            let cx = (x / 2).min(cw - 1);
19            let idx = y * parent_w + x;
20            dest[idx] = lap[idx] + coarse[cy * cw + cx];
21        }
22    }
23}
24
25/// Reconstruct level-0 image from Laplacian pyramid into `out` (`meta[0].len` elements).
26///
27/// `work` must hold at least the largest intermediate level (≥ level-0 size is sufficient).
28pub fn pyramid_reconstruct(
29    lap_packed: &[f32],
30    meta: &[PyramidLevelMeta; MAX_PYRAMID_LEVELS],
31    n_levels: usize,
32    out: &mut [f32],
33    work: &mut [f32],
34) -> Result<(), CvError> {
35    if n_levels == 0 || n_levels > MAX_PYRAMID_LEVELS {
36        return Err(CvError::InvalidParameter);
37    }
38    let l0 = meta[0].len;
39    if out.len() < l0 || work.len() < l0 {
40        return Err(CvError::BufferTooSmall);
41    }
42
43    if n_levels == 1 {
44        let o = meta[0].offset;
45        out[..l0].copy_from_slice(&lap_packed[o..o + l0]);
46        return Ok(());
47    }
48
49    // Start from top residual into a side buffer sized to top, then walk down.
50    // Use `work` for "current coarse", `out` for next parent when parent is level 0.
51    let top = n_levels - 1;
52    let mut cur_w = meta[top].width as usize;
53    let mut cur_h = meta[top].height as usize;
54    let mut cur_len = meta[top].len;
55
56    // Keep current reconstruction in a stack-friendly two-buffer ping-pong via work/out.
57    // Allocate conceptually: copy top into work[0..cur_len]
58    if work.len() < cur_len {
59        return Err(CvError::BufferTooSmall);
60    }
61    let to = meta[top].offset;
62    work[..cur_len].copy_from_slice(&lap_packed[to..to + cur_len]);
63
64    for i in (0..n_levels - 1).rev() {
65        let parent = &meta[i];
66        let pw = parent.width as usize;
67        let ph = parent.height as usize;
68        let plen = parent.len;
69        let lap = &lap_packed[parent.offset..parent.offset + plen];
70
71        if i == 0 {
72            if out.len() < plen {
73                return Err(CvError::BufferTooSmall);
74            }
75            expand_add(&work[..cur_len], cur_w, cur_h, pw, ph, lap, out);
76        } else {
77            // Need temporary for expanded parent — write into out then copy back to work
78            if out.len() < plen || work.len() < plen {
79                return Err(CvError::BufferTooSmall);
80            }
81            expand_add(&work[..cur_len], cur_w, cur_h, pw, ph, lap, out);
82            work[..plen].copy_from_slice(&out[..plen]);
83            cur_w = pw;
84            cur_h = ph;
85            cur_len = plen;
86        }
87    }
88    Ok(())
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    use crate::biosense::magnification::gaussian_pyramid_build::{
95        gaussian_pyramid_build, gaussian_pyramid_scratch_elems,
96    };
97    use crate::biosense::magnification::laplacian_pyramid_build::laplacian_pyramid_build;
98
99    #[test]
100    fn reconstruct_approx_input() {
101        let w = 16u32;
102        let h = 16u32;
103        let n_px = (w * h) as usize;
104        let mut src = vec![0.0f32; n_px];
105        for y in 0..h as usize {
106            for x in 0..w as usize {
107                src[y * w as usize + x] = (x as f32 * 0.5 + y as f32 * 0.25).sin() * 40.0 + 100.0;
108            }
109        }
110        let levels = 4usize;
111        let need = gaussian_pyramid_scratch_elems(w, h, levels);
112        let mut g = vec![0.0f32; need];
113        let mut meta = [PyramidLevelMeta::default(); MAX_PYRAMID_LEVELS];
114        let n = gaussian_pyramid_build(&src, w, h, levels, &mut g, &mut meta).unwrap();
115        let mut lap = vec![0.0f32; need];
116        let mut expand = vec![0.0f32; n_px];
117        laplacian_pyramid_build(&g, &meta, n, &mut lap, &mut expand).unwrap();
118        let mut recon = vec![0.0f32; n_px];
119        let mut work = vec![0.0f32; n_px];
120        pyramid_reconstruct(&lap, &meta, n, &mut recon, &mut work).unwrap();
121
122        let mut max_err = 0.0f32;
123        for i in 0..n_px {
124            max_err = max_err.max((recon[i] - src[i]).abs());
125        }
126        // Nearest-neighbor expand is lossy but should stay close for smooth fields.
127        assert!(max_err < 25.0, "max_err={max_err}");
128        let mean_err: f32 = recon
129            .iter()
130            .zip(src.iter())
131            .map(|(a, b)| (a - b).abs())
132            .sum::<f32>()
133            / n_px as f32;
134        assert!(mean_err < 5.0, "mean_err={mean_err}");
135    }
136}