fprint_mindtct/image.rs
1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Image plumbing: the 6-bit rescale (`bits_8to6`, a `>> 2`, and its inverse `bits_6to8`, a `<< 2`)
6//! and the constant-intensity border padding (`pad_uchar_image`) that the detection front-end runs
7//! before block analysis. Mirrors stock NBIS `imgutil.c` (`bits_6to8` L88, `bits_8to6` L118,
8//! `pad_uchar_image` L189). See `docs/mindtct-algorithm.md`.
9//!
10//! Two faithful details a naive port would get wrong:
11//! * **`bits_6to8` wraps like C's `unsigned char <<= 2`.** Only values on `[0..64)` (the output of
12//! `bits_8to6`) round-trip meaningfully; a stray value `>= 64` has its high bits truncated exactly
13//! as the stock byte shift does, which the `<< 2` on `u8` reproduces bit-for-bit.
14//! * **Padding fills with a *constant* intensity**, not edge replication — `PAD_VALUE` (medium gray)
15//! is written across the whole allocation first, then the input is `memcpy`'d scanline-by-scanline
16//! into the centered region. The stock code notes edge-copying as an unimplemented alternative.
17
18use crate::consts::PAD_VALUE;
19use crate::GrayImage;
20
21/// `bits_8to6` — scale every pixel from 8-bit `[0..256)` down to 6-bit `[0..64)` by `>> 2`.
22///
23/// Stock `imgutil.c` iterates `isize = iw * ih` bytes shifting each right by 2 (an integer divide by
24/// 4). MINDTCT feeds this into the DFT / binarization front-end, which is built around 6-bit input
25/// (`IMG_6BIT_PIX_LIMIT == 64`). Operates in place over the whole slice; the caller passes the full
26/// `width * height` (already padded) buffer, so no dimensions are needed — the C `iw`/`ih` served
27/// only to compute that product.
28pub(crate) fn bits_8to6(idata: &mut [u8]) {
29 for pix in idata.iter_mut() {
30 // Divide every pixel value by 4 so that [0..256) -> [0..64).
31 *pix >>= 2;
32 }
33}
34
35/// `bits_6to8` — the inverse of [`bits_8to6`]: scale every pixel from 6-bit `[0..64)` back up to
36/// 8-bit `[0..256)` by `<< 2` (a multiply by 4).
37///
38/// Stock `imgutil.c` shifts each byte left by 2. The low two bits discarded by [`bits_8to6`] are
39/// gone, so the round trip is lossy (`255 -> 63 -> 252`), matching the reference. The `<< 2` on `u8`
40/// truncates any high bits exactly like C's `unsigned char <<= 2`, so out-of-range inputs wrap
41/// identically. MINDTCT uses this in `results.c` to restore the binarized image to 8-bit for output.
42//
43// `#[cfg(test)]`: the inverse of the wired [`bits_8to6`]. The port emits minutiae, not the 8-bit
44// binarized image (`results.c`'s output stage), so nothing in the pipeline calls it; it is
45// transcribed for fidelity and compiled only for the tests below that pin its arithmetic.
46#[cfg(test)]
47pub(crate) fn bits_6to8(idata: &mut [u8]) {
48 for pix in idata.iter_mut() {
49 // Multiply every pixel value by 4 so that [0..64) -> [0..256).
50 *pix <<= 2;
51 }
52}
53
54/// `pad_uchar_image` — copy an 8-bit grayscale image into a larger buffer, centered, with `pad`
55/// pixels of constant `pad_value` intensity added on every side.
56///
57/// Returns the padded image plus its dimensions `(pdata, pw, ph)` where `pw = iw + 2*pad` and
58/// `ph = ih + 2*pad`. Faithful to `imgutil.c` L189: allocate `pw * ph`, `memset` it all to
59/// `pad_value`, then `memcpy` the input in one scanline at a time starting at offset
60/// `pad * pw + pad`. The stock C returns an error code only on `malloc` failure; the Rust `Vec`
61/// allocation replaces that path, so this is infallible for the sizes MINDTCT uses.
62///
63/// # Panics
64/// If `idata.len() < iw * ih` (the input must hold at least a full `iw * ih` image).
65pub(crate) fn pad_uchar_image(
66 idata: &[u8],
67 iw: usize,
68 ih: usize,
69 pad: usize,
70 pad_value: u8,
71) -> (Vec<u8>, usize, usize) {
72 // Account for pad on both sides of the image.
73 let pad2 = pad << 1;
74 let pw = iw + pad2;
75 let ph = ih + pad2;
76
77 // Initialize the whole allocation to the constant PAD value.
78 let mut pdata = vec![pad_value; pw * ph];
79
80 // Copy the input image into the padded image one scanline at a time, centered: the first
81 // destination row/col is `pad`, matching the stock `pdata + (pad * pw) + pad` start offset.
82 for row in 0..ih {
83 let src = &idata[row * iw..row * iw + iw];
84 let dst_start = (pad + row) * pw + pad;
85 pdata[dst_start..dst_start + iw].copy_from_slice(src);
86 }
87
88 (pdata, pw, ph)
89}
90
91/// Build the padded working buffer for a [`GrayImage`], mirroring the `lfs_detect_minutiae_V2`
92/// front-end (`detect.c` L488): pad by `maxpad` with [`PAD_VALUE`] when `maxpad > 0`, otherwise take
93/// a plain copy of the image at its original size.
94///
95/// Returns `(pdata, pw, ph)`. This is the seam the pipeline calls right before [`bits_8to6`]; the
96/// `else` branch reproduces the stock "padding is unnecessary, so just copy" fast path exactly (same
97/// dimensions, same bytes) so the two paths stay bit-identical to the reference.
98pub(crate) fn pad_gray_image(img: &GrayImage<'_>, maxpad: usize) -> (Vec<u8>, usize, usize) {
99 if maxpad > 0 {
100 pad_uchar_image(
101 img.data(),
102 img.width(),
103 img.height(),
104 maxpad,
105 PAD_VALUE as u8,
106 )
107 } else {
108 // If padding is unnecessary, copy the input image unchanged.
109 (img.data().to_vec(), img.width(), img.height())
110 }
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116
117 // --- bits_8to6: >> 2 over [0..256) -> [0..64) ---------------------------------------------
118 #[test]
119 fn bits_8to6_shifts_right_two() {
120 let mut v = [0u8, 3, 4, 5, 128, 254, 255];
121 bits_8to6(&mut v);
122 // 3>>2==0, 4>>2==1, 5>>2==1, 128>>2==32, 254>>2==63, 255>>2==63.
123 assert_eq!(v, [0, 0, 1, 1, 32, 63, 63]);
124 }
125
126 #[test]
127 fn bits_8to6_never_exceeds_6bit_limit() {
128 // Every possible 8-bit input maps strictly below IMG_6BIT_PIX_LIMIT (64).
129 for p in 0u8..=255 {
130 let mut one = [p];
131 bits_8to6(&mut one);
132 assert!(one[0] < 64, "{p} >> 2 = {} should be < 64", one[0]);
133 }
134 }
135
136 // --- bits_6to8: << 2 over [0..64) -> [0..256) ---------------------------------------------
137 #[test]
138 fn bits_6to8_shifts_left_two() {
139 let mut v = [0u8, 1, 32, 63];
140 bits_6to8(&mut v);
141 // 1<<2==4, 32<<2==128, 63<<2==252.
142 assert_eq!(v, [0, 4, 128, 252]);
143 }
144
145 #[test]
146 fn bits_6to8_wraps_like_unsigned_char() {
147 // Out-of-range (>= 64) input truncates its high bits exactly like C's `unsigned char <<= 2`.
148 let mut v = [64u8, 127, 128, 255];
149 bits_6to8(&mut v);
150 // 64<<2 == 256 & 0xFF == 0; 127<<2 == 508 & 0xFF == 252;
151 // 128<<2 == 512 & 0xFF == 0; 255<<2 == 1020 & 0xFF == 252.
152 assert_eq!(v, [0, 252, 0, 252]);
153 }
154
155 // --- round trip through the 6-bit reduction is lossy in the low two bits ------------------
156 #[test]
157 fn round_trip_drops_low_two_bits() {
158 let mut v = [255u8, 5, 7, 200];
159 bits_8to6(&mut v);
160 bits_6to8(&mut v);
161 // Each value is floored to its multiple of 4: 255->252, 5->4, 7->4, 200->200.
162 assert_eq!(v, [252, 4, 4, 200]);
163 }
164
165 // --- pad_uchar_image: centered copy inside a constant-fill border -------------------------
166 #[test]
167 fn pad_uchar_image_centers_and_fills() {
168 // 2x2 image, pad 1 -> 4x4 with the image in the center and PAD_VALUE (128) elsewhere.
169 let img = [1u8, 2, 3, 4];
170 let (pdata, pw, ph) = pad_uchar_image(&img, 2, 2, 1, 128);
171 assert_eq!((pw, ph), (4, 4));
172 #[rustfmt::skip]
173 let expected = [
174 128, 128, 128, 128,
175 128, 1, 2, 128,
176 128, 3, 4, 128,
177 128, 128, 128, 128,
178 ];
179 assert_eq!(pdata, expected);
180 }
181
182 #[test]
183 fn pad_uchar_image_zero_pad_is_identity() {
184 let img = [10u8, 20, 30, 40, 50, 60];
185 let (pdata, pw, ph) = pad_uchar_image(&img, 3, 2, 0, 128);
186 assert_eq!((pw, ph), (3, 2));
187 assert_eq!(pdata, img);
188 }
189
190 #[test]
191 fn pad_uchar_image_nonsquare_and_pad2() {
192 // 3x1 image, pad 2 -> 7x5. Only row 2 (the centered scanline) holds the image.
193 let img = [7u8, 8, 9];
194 let (pdata, pw, ph) = pad_uchar_image(&img, 3, 1, 2, 128);
195 assert_eq!((pw, ph), (7, 5));
196 // The three input pixels land at offset pad*pw + pad = 2*7 + 2 = 16.
197 assert_eq!(&pdata[16..19], &[7, 8, 9]);
198 // Everything else is PAD_VALUE.
199 assert!(pdata[..16].iter().all(|&b| b == 128));
200 assert!(pdata[19..].iter().all(|&b| b == 128));
201 }
202
203 // --- pad_gray_image: front-end seam -------------------------------------------------------
204 #[test]
205 fn pad_gray_image_pads_with_pad_value() {
206 let data = [1u8, 2, 3, 4];
207 // 2x2 is below the detection floor; construct unchecked to test the padding seam in isolation.
208 let img = GrayImage::from_parts_unchecked(&data, 2, 2, 500);
209 let (pdata, pw, ph) = pad_gray_image(&img, 1);
210 assert_eq!((pw, ph), (4, 4));
211 // Center holds the image; border is PAD_VALUE (128).
212 assert_eq!(&pdata[5..7], &[1, 2]);
213 assert_eq!(&pdata[9..11], &[3, 4]);
214 assert_eq!(pdata[0], PAD_VALUE as u8);
215 }
216
217 #[test]
218 fn pad_gray_image_zero_maxpad_copies_unchanged() {
219 let data = [11u8, 22, 33, 44, 55, 66];
220 // 3x2 is below the detection floor; construct unchecked to test the copy path in isolation.
221 let img = GrayImage::from_parts_unchecked(&data, 3, 2, 500);
222 let (pdata, pw, ph) = pad_gray_image(&img, 0);
223 assert_eq!((pw, ph), (3, 2));
224 assert_eq!(pdata, data);
225 }
226}