fprint_mindtct/lib.rs
1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! # fprint-mindtct
6//!
7//! A pure-Rust, dependency-free reimplementation of **MINDTCT** — NIST NBIS's minutiae detector.
8//! Given an 8-bit grayscale fingerprint image it produces a list of [`Minutia`] (`x`, `y`, `theta`,
9//! `quality`) reproducing the stock NBIS tool's `xyt` output. The `unstable-diagnostics` feature
10//! additionally exposes the intermediate block maps and binarized image used to reach them.
11//!
12//! ## Provenance
13//!
14//! MINDTCT is public-domain U.S. Government software (title 17 §105). This crate is a faithful
15//! port of stock upstream NBIS (`reference/nbis-stock/mindtct/`, see `docs/mindtct-algorithm.md`),
16//! verified black-box against the stock C tool; reproducing its `xyt` output bit-for-bit requires
17//! following its arithmetic and its ordering closely, which public domain permits. It is not
18//! derived from libfprint's patched `nbis/mindtct/` copy, whose changes carry LGPL terms. The
19//! crate carries `MIT OR Apache-2.0`. See `ARCHITECTURE.md` §Provenance & licensing.
20//!
21//! ## Types
22//!
23//! The crate takes its own [`GrayImage`] and returns its own [`Minutia`] — the `xyt` triple is an
24//! interoperability fact, so the detector stays a self-contained image-processing kernel with no
25//! dependency on the domain model. A consumer (e.g. `fprint-backend-native`) converts to its
26//! `fprint_core::Minutia` at the boundary.
27
28#![forbid(unsafe_code)]
29#![deny(missing_docs)]
30
31mod binarize;
32mod block;
33mod consts;
34mod detect;
35mod image;
36mod init;
37mod maps;
38mod num;
39mod params;
40mod quality;
41mod remove;
42mod ridges;
43mod util;
44mod xyt;
45
46/// One detected minutia in NIST `xyt` form.
47///
48/// Coordinates use the NIST internal convention: origin **bottom-left**, `x` rightward, `y` upward.
49/// `theta` is the ridge orientation in integer **degrees** on `0..=359`, 0 pointing east and
50/// increasing counter-clockwise (the `lfs2nist` representation). `quality` is a reliability estimate
51/// (higher is better). Mirrors the shape of `fprint_core::Minutia` (the consumer converts).
52#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
53pub struct Minutia {
54 /// Pixel column, origin bottom-left, increasing rightward.
55 pub x: i32,
56 /// Pixel row, origin bottom-left, increasing upward.
57 pub y: i32,
58 /// Ridge orientation in degrees, `0..=359`.
59 pub theta: i32,
60 /// Reliability estimate; higher is better.
61 pub quality: i32,
62}
63
64impl Minutia {
65 /// The `(x, y, theta)` triple, dropping `quality` — the interoperability fact a matcher
66 /// (BOZORTH3) or the domain model consumes. There is no `from_xyt`: a bare triple carries no
67 /// reliability, and `quality` is decided here.
68 #[must_use]
69 pub const fn as_xyt(&self) -> (i32, i32, i32) {
70 (self.x, self.y, self.theta)
71 }
72}
73
74/// The smallest image dimension MINDTCT can process, in pixels.
75///
76/// Below this in either axis there is nowhere to place the `windowsize × windowsize` block-map window
77/// clear of the padding (the constraint is `dimension ≥ windowsize + 1`), nor room for a single
78/// `blocksize × blocksize` block — so detection has no defined output. Derived from the shipping
79/// `LFSPARMS_V2` (`blocksize = 8`, `windowsize = 24`), it is the tightest bound of the two.
80/// [`GrayImage::new`] rejects any image below it, which is what lets [`detect_minutiae`] be total.
81pub const MIN_DETECTABLE_DIM: usize = {
82 let blocksize = crate::params::LFSPARMS_V2.blocksize;
83 let window = crate::params::LFSPARMS_V2.windowsize + 1;
84 (if blocksize > window {
85 blocksize
86 } else {
87 window
88 }) as usize
89};
90
91/// An 8-bit grayscale fingerprint image, row-major, one byte per pixel.
92///
93/// `data` holds at least `width * height` bytes (0 = black, 255 = white). `ppi` is the scan
94/// resolution in pixels-per-inch, carried because several MINDTCT thresholds are resolution-relative.
95///
96/// Build one with [`GrayImage::new`], which rejects an image MINDTCT cannot process — too small to
97/// carry a block-map window ([`MIN_DETECTABLE_DIM`]), too large for its `i32` pixel arithmetic, or a
98/// buffer shorter than `width * height`. The fields are private, so a value can only exist around a
99/// detectable image; a *longer* `data` is accepted and its trailing bytes are ignored.
100#[derive(Clone, Copy)]
101pub struct GrayImage<'a> {
102 /// The pixels, row-major, one byte each (0 = black, 255 = white).
103 data: &'a [u8],
104 /// Image width in pixels.
105 width: usize,
106 /// Image height in pixels.
107 height: usize,
108 /// Scan resolution in pixels-per-inch.
109 ppi: u16,
110}
111
112impl core::fmt::Debug for GrayImage<'_> {
113 /// Print geometry, not the pixel buffer.
114 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115 write!(
116 f,
117 "GrayImage {{ {}x{} @ {}ppi }}",
118 self.width, self.height, self.ppi
119 )
120 }
121}
122
123impl<'a> GrayImage<'a> {
124 /// Wrap a row-major 8-bit grayscale buffer, checking it can hold the stated image.
125 ///
126 /// `data` must be at least `width * height` bytes; a longer buffer is accepted and its trailing
127 /// bytes are ignored. `ppi` is the scan resolution in pixels-per-inch.
128 ///
129 /// # Errors
130 ///
131 /// - [`ImageError::TooLarge`] when either dimension exceeds `i32::MAX`, the range MINDTCT's
132 /// internal pixel arithmetic addresses.
133 /// - [`ImageError::TooSmall`] when either dimension is below [`MIN_DETECTABLE_DIM`]: MINDTCT
134 /// cannot place a block-map window on it, so detection has no defined output.
135 /// - [`ImageError::BufferTooShort`] when `data.len() < width * height`.
136 ///
137 /// A successfully constructed `GrayImage` is therefore guaranteed detectable: an empty
138 /// [`detect_minutiae`] result then means "no minutiae", never "image rejected".
139 pub fn new(
140 data: &'a [u8],
141 width: usize,
142 height: usize,
143 ppi: u16,
144 ) -> Result<GrayImage<'a>, ImageError> {
145 if width > i32::MAX as usize || height > i32::MAX as usize {
146 return Err(ImageError::TooLarge { width, height });
147 }
148 if width
149 .checked_mul(height)
150 .is_none_or(|area| area > i32::MAX as usize)
151 {
152 return Err(ImageError::TooLarge { width, height });
153 }
154 if width < MIN_DETECTABLE_DIM || height < MIN_DETECTABLE_DIM {
155 return Err(ImageError::TooSmall {
156 width,
157 height,
158 min: MIN_DETECTABLE_DIM,
159 });
160 }
161 if data.len() < width.saturating_mul(height) {
162 return Err(ImageError::BufferTooShort {
163 width,
164 height,
165 got: data.len(),
166 });
167 }
168 Ok(GrayImage {
169 data,
170 width,
171 height,
172 ppi,
173 })
174 }
175
176 /// Construct without the detectability checks `new` enforces, for crate-internal tests that
177 /// exercise sub-detection geometry (e.g. the padding seam) on images below [`MIN_DETECTABLE_DIM`].
178 ///
179 /// Kept `pub(crate)` and test-only on purpose: the invariant `new` upholds — a `GrayImage` a
180 /// caller holds is always detectable — must not be circumventable from outside the crate.
181 #[cfg(test)]
182 pub(crate) fn from_parts_unchecked(
183 data: &'a [u8],
184 width: usize,
185 height: usize,
186 ppi: u16,
187 ) -> GrayImage<'a> {
188 GrayImage {
189 data,
190 width,
191 height,
192 ppi,
193 }
194 }
195
196 /// Image width in pixels.
197 #[must_use]
198 pub fn width(&self) -> usize {
199 self.width
200 }
201
202 /// Image height in pixels.
203 #[must_use]
204 pub fn height(&self) -> usize {
205 self.height
206 }
207
208 /// Scan resolution in pixels-per-inch.
209 #[must_use]
210 pub fn ppi(&self) -> u16 {
211 self.ppi
212 }
213
214 /// The pixel buffer, row-major, one byte per pixel.
215 #[must_use]
216 pub fn data(&self) -> &[u8] {
217 self.data
218 }
219}
220
221/// The error [`GrayImage::new`] returns when the supplied image cannot be processed by MINDTCT.
222#[derive(Debug, Clone, PartialEq, Eq)]
223#[non_exhaustive]
224pub enum ImageError {
225 /// The pixel buffer is shorter than `width * height`.
226 BufferTooShort {
227 /// Stated image width in pixels.
228 width: usize,
229 /// Stated image height in pixels.
230 height: usize,
231 /// Length of the buffer supplied.
232 got: usize,
233 },
234 /// A dimension is below [`MIN_DETECTABLE_DIM`]: there is nowhere to place the block-map window,
235 /// so detection has no defined output.
236 TooSmall {
237 /// Stated image width in pixels.
238 width: usize,
239 /// Stated image height in pixels.
240 height: usize,
241 /// The smallest dimension MINDTCT can process ([`MIN_DETECTABLE_DIM`]).
242 min: usize,
243 },
244 /// A dimension, or the product `width * height`, exceeds `i32::MAX` — the range MINDTCT's
245 /// internal pixel arithmetic addresses.
246 TooLarge {
247 /// Stated image width in pixels.
248 width: usize,
249 /// Stated image height in pixels.
250 height: usize,
251 },
252}
253
254impl core::fmt::Display for ImageError {
255 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
256 match *self {
257 ImageError::BufferTooShort { width, height, got } => write!(
258 f,
259 "grayscale buffer holds {got} bytes, need {} for a {width}x{height} image",
260 width.saturating_mul(height)
261 ),
262 ImageError::TooSmall { width, height, min } => write!(
263 f,
264 "image {width}x{height} is too small to detect minutiae: each dimension must be at least {min} pixels"
265 ),
266 ImageError::TooLarge { width, height } => write!(
267 f,
268 "image {width}x{height} is too large: each dimension must be at most {}",
269 i32::MAX
270 ),
271 }
272 }
273}
274
275impl std::error::Error for ImageError {}
276
277// `DebugMaps` is the front-end's map container, used by the core pipeline on every run. Its public
278// diagnostic identity is gated: `unstable-diagnostics` exports it, otherwise it stays crate-internal.
279// The single definition lives in `diag` so the two visibilities share one struct.
280#[cfg(feature = "unstable-diagnostics")]
281#[doc(hidden)]
282pub use diag::DebugMaps;
283#[cfg(not(feature = "unstable-diagnostics"))]
284pub(crate) use diag::DebugMaps;
285
286mod diag {
287 /// The intermediate block maps and binarized image produced along the way to the minutiae.
288 ///
289 /// Exposed through [`debug_maps`](crate::debug_maps) for cross-implementation verification against
290 /// the stock C tool's map dumps. All four block maps are `map_w * map_h` in row-major block order;
291 /// `binarized` is a full-resolution `width * height` image (0 = ridge, 255 = valley — the
292 /// pre-`gray2bin` form).
293 #[derive(Clone, Debug, Default)]
294 pub struct DebugMaps {
295 /// Per-block ridge flow direction: `-1` (invalid) or a valid direction index.
296 pub direction_map: Vec<i32>,
297 /// Per-block low-contrast flag (`TRUE`/`FALSE` as `1`/`0`).
298 pub low_contrast_map: Vec<i32>,
299 /// Per-block low-ridge-flow flag (`TRUE`/`FALSE` as `1`/`0`).
300 pub low_flow_map: Vec<i32>,
301 /// Per-block high-curvature flag (`TRUE`/`FALSE` as `1`/`0`).
302 pub high_curve_map: Vec<i32>,
303 /// Width of the block maps, in blocks.
304 pub map_w: usize,
305 /// Height of the block maps, in blocks.
306 pub map_h: usize,
307 /// Binarized image, full resolution, `0` = ridge and `255` = valley — the output of the
308 /// directional-binarization stage (`binarize_V2`), i.e. **before** the detection/false-minutia
309 /// removal stages edit the binary image in place. (The stock tool's `.brw` dump is captured
310 /// after removal, so the two agree only where removal is a no-op.)
311 pub binarized: Vec<u8>,
312 }
313}
314
315/// The shared detection front-end carried between the pipeline stages: the block maps and their
316/// dimensions ([`DebugMaps`]), the in-place-edited binary image in the detector's `0 == valley` /
317/// `1 == ridge` convention, and the current minutiae list. Produced by [`run_detect`] and threaded
318/// through false-minutia removal, ridge counting, and quality assignment.
319struct DetectState {
320 maps: DebugMaps,
321 /// Binary image, `iw`×`ih`, stock `gray2bin(1, 1, 0)` convention (`0 == valley`, `1 == ridge`).
322 bdata: Vec<u8>,
323 minutiae: Vec<crate::detect::DetMinutia>,
324}
325
326/// Run the stock `lfs_detect_minutiae_V2` front-end through `detect_minutiae_V2` — the shared prefix
327/// of [`detect_minutiae`] and the diagnostic entry points.
328///
329/// Reuses [`build_maps`] for the pad → 6-bit scale → block maps → directional binarization stages,
330/// converts the binary image to the detector's `0 == valley` / `1 == ridge` convention
331/// (stock `gray2bin(1, 1, 0)`, `detect.c` L614), then runs `detect_minutiae_V2` over the unpadded
332/// image and block maps. Returns [`None`] on the internal size/error paths — an empty front-end map
333/// or a `detect_minutiae_V2` error. Those paths are unreachable for a value produced by
334/// [`GrayImage::new`], which rejects any image below [`MIN_DETECTABLE_DIM`]; the [`None`] arm is kept
335/// as a defensive net, not a reachable outcome.
336fn run_detect(img: GrayImage<'_>) -> Option<DetectState> {
337 use crate::detect::detect_minutiae_v2;
338 use crate::params::LFSPARMS_V2;
339
340 // Verified front-end: block maps + the pre-gray2bin binary image.
341 let maps = build_maps(img);
342 if maps.binarized.is_empty() {
343 return None;
344 }
345
346 // stock `gray2bin(1, 1, 0)`: ridge (0) → 1, valley (255) → 0.
347 let mut bdata: Vec<u8> = maps.binarized.iter().map(|&p| u8::from(p < 1)).collect();
348
349 let p = &LFSPARMS_V2;
350 // `width()`/`height() as i32` here and throughout this module are lossless: `GrayImage::new`
351 // rejects any dimension above `i32::MAX`, so the value always fits the detector's i32 arithmetic.
352 let minutiae = detect_minutiae_v2(
353 &mut bdata,
354 img.width() as i32,
355 img.height() as i32,
356 &maps.direction_map,
357 &maps.low_flow_map,
358 &maps.high_curve_map,
359 maps.map_w as i32,
360 maps.map_h as i32,
361 p,
362 )
363 .ok()?;
364
365 Some(DetectState {
366 maps,
367 bdata,
368 minutiae,
369 })
370}
371
372/// Project a detector minutiae list onto the diagnostic [`RawMinutia`] rows, list order preserved.
373#[cfg(feature = "unstable-diagnostics")]
374fn to_raw(minutiae: &[crate::detect::DetMinutia]) -> Vec<RawMinutia> {
375 minutiae
376 .iter()
377 .map(|m| RawMinutia {
378 x: m.x,
379 y: m.y,
380 direction: m.direction,
381 kind: m.kind,
382 appearing: i32::from(m.appearing),
383 })
384 .collect()
385}
386
387/// Detect the minutiae in a grayscale fingerprint image.
388///
389/// Runs the stock `get_minutiae` / `lfs_detect_minutiae_V2` pipeline (pad → 6-bit scale → block maps
390/// → binarize → detect → false-minutia removal → ridge counts → integrated quality → `xyt` output)
391/// and returns the minutiae in NIST internal `xyt` form (origin bottom-left, `theta` in whole
392/// degrees on `0..=359`, `quality` on `0..=100`). See `docs/mindtct-algorithm.md`.
393///
394/// The reliability that becomes each minutia's `quality` is derived from the **original** 8-bit image
395/// (the unpadded pixels) and the block maps at the scan resolution `ppmm = ppi / 25.4`, exactly as
396/// stock `combined_minutia_quality` consumes `idata`. Returns an empty list when the image has no
397/// detectable ridge structure — that is the *only* meaning of an empty result. An image too small to
398/// carry a block-map window is rejected earlier, by [`GrayImage::new`] ([`MIN_DETECTABLE_DIM`]), so it
399/// never reaches this function; a realistic fingerprint is far above that floor.
400///
401/// # Examples
402///
403/// A procedural image: dark horizontal ridges on a light field, with a gap cut into every other
404/// ridge. The gap ends a ridge, and a ridge ending is a minutia — plain stripes have none, and would
405/// make the loop below assert nothing.
406///
407/// The example asserts the shape of the answer, not the count: that detection finds *something*, and
408/// that each minutia sits inside the image with a documented angle and quality. The exact count is a
409/// property of the pixels and belongs in the golden suite.
410///
411/// ```
412/// use fprint_mindtct::{detect_minutiae, GrayImage};
413///
414/// let (width, height) = (128, 128);
415/// let data: Vec<u8> = (0..width * height)
416/// .map(|i| {
417/// let (x, y) = (i % width, i / width);
418/// let on_ridge = (y % 8) < 4;
419/// let gap = (48..80).contains(&x) && (y / 8) % 2 == 0;
420/// if on_ridge && !gap { 32 } else { 224 }
421/// })
422/// .collect();
423///
424/// let img = GrayImage::new(&data, width, height, 500).expect("buffer holds the image");
425/// let minutiae = detect_minutiae(img);
426///
427/// assert!(!minutiae.is_empty(), "the ridge gaps must yield minutiae");
428/// for m in &minutiae {
429/// assert!((0..width as i32).contains(&m.x));
430/// assert!((0..height as i32).contains(&m.y));
431/// assert!((0..360).contains(&m.theta));
432/// assert!((0..=100).contains(&m.quality));
433/// }
434/// ```
435#[must_use]
436pub fn detect_minutiae(img: GrayImage<'_>) -> Vec<Minutia> {
437 use crate::params::LFSPARMS_V2;
438 use crate::quality::{combined_minutia_quality, gen_quality_map};
439 use crate::remove::remove_false_minutia_v2;
440 use crate::ridges::count_minutiae_ridges;
441 use crate::xyt::lfs2nist_format;
442
443 // Front-end + detection (detect.c L455–633).
444 let Some(mut st) = run_detect(img) else {
445 return Vec::new();
446 };
447
448 let p = &LFSPARMS_V2;
449 let (iw, ih) = (img.width() as i32, img.height() as i32);
450 let (mw, mh) = (st.maps.map_w as i32, st.maps.map_h as i32);
451
452 // False-minutia removal (detect.c L639): edits the minutiae list and the binary image in place.
453 if remove_false_minutia_v2(
454 &mut st.minutiae,
455 &mut st.bdata,
456 iw,
457 ih,
458 &st.maps.direction_map,
459 &st.maps.low_flow_map,
460 &st.maps.high_curve_map,
461 mw,
462 mh,
463 p,
464 )
465 .is_err()
466 {
467 return Vec::new();
468 }
469
470 // Neighbor ridge counts (detect.c L662): sorts + dedups the list — fixing the final order and
471 // count — over the `0 == valley` / `1 == ridge` binary image left by removal.
472 if count_minutiae_ridges(&mut st.minutiae, &st.bdata, iw, ih, p).is_err() {
473 return Vec::new();
474 }
475
476 // Integrated quality map (getmin.c: gen_quality_map), then per-minutia reliability blended from
477 // the ORIGINAL 8-bit unpadded image at the scan resolution (combined_minutia_quality).
478 let quality_map = gen_quality_map(
479 &st.maps.direction_map,
480 &st.maps.low_contrast_map,
481 &st.maps.low_flow_map,
482 &st.maps.high_curve_map,
483 mw,
484 mh,
485 );
486 let ppmm = f64::from(img.ppi()) / 25.4;
487 if combined_minutia_quality(
488 &mut st.minutiae,
489 &quality_map,
490 mw,
491 mh,
492 p.blocksize,
493 img.data(),
494 iw,
495 ih,
496 ppmm,
497 )
498 .is_err()
499 {
500 return Vec::new();
501 }
502
503 // Final `xyt` conversion, list order preserved (results.c write_minutiae_XYTQ).
504 lfs2nist_format(&st.minutiae, ih)
505}
506
507/// One raw minutia exactly as `detect_minutiae_V2` emits it — the diagnostic row of a `.rmin` dump.
508///
509/// Captured **before** false-minutia removal, list order preserved. All fields are in the LFS-internal
510/// representation: `x`/`y` are pixel coordinates with origin top-left; `direction` is the integer
511/// direction on `0..2*num_directions` (`0..=31`); `kind` is the stock `type` (`0 == BIFURCATION`,
512/// `1 == RIDGE_ENDING`); `appearing` is `1` (appearing) or `0` (disappearing). Mirrors the oracle's
513/// `.rmin` line `"x y direction type appearing"`.
514#[cfg(feature = "unstable-diagnostics")]
515#[doc(hidden)]
516#[derive(Clone, Copy, PartialEq, Eq, Debug)]
517pub struct RawMinutia {
518 /// Pixel x, origin top-left.
519 pub x: i32,
520 /// Pixel y, origin top-left.
521 pub y: i32,
522 /// Integer direction on `0..=31` (`0..2*num_directions`).
523 pub direction: i32,
524 /// Stock `type`: `0 == BIFURCATION`, `1 == RIDGE_ENDING`.
525 pub kind: i32,
526 /// `1 == APPEARING`, `0 == DISAPPEARING`.
527 pub appearing: i32,
528}
529
530/// Diagnostic (hidden): the raw minutiae for an input exactly as `detect_minutiae_V2` produces them,
531/// **before** false-minutia removal and with list order preserved — the golden contract behind the
532/// oracle's `.rmin` dump.
533///
534/// Runs the same front-end as [`debug_maps`] (pad → 6-bit scale → block maps → directional
535/// binarization), then converts the binary image to the detector's `0 == valley` / `1 == ridge`
536/// convention (stock `gray2bin(1, 1, 0)`, `detect.c` L614) and runs `detect_minutiae_V2` over the
537/// unpadded image and block maps. Returns each detected point as a [`RawMinutia`]; returns an empty
538/// list on the (size) error paths the pipeline can surface.
539#[cfg(feature = "unstable-diagnostics")]
540#[doc(hidden)]
541#[must_use]
542pub fn debug_raw_minutiae(img: GrayImage<'_>) -> Vec<RawMinutia> {
543 // Shared front-end + `detect_minutiae_V2`; the raw list is captured before removal.
544 match run_detect(img) {
545 Some(st) => to_raw(&st.minutiae),
546 None => Vec::new(),
547 }
548}
549
550/// Diagnostic (hidden): the minutiae for an input **after** `remove_false_minutia_V2`, list order
551/// preserved — the golden contract behind the oracle's `.rmin2` dump.
552///
553/// Runs the same front-end and `detect_minutiae_V2` as [`debug_raw_minutiae`], then applies the ten
554/// false-minutia removal stages (`remove_false_minutia_V2`) over the same in-place-edited binary image
555/// and the **block** maps (not pixelized), before the ridge-count stage. Returns each surviving point
556/// as a [`RawMinutia`] in the same `(x, y, direction, type, appearing)` contract as `.rmin`; returns
557/// an empty list on the (size) error paths the pipeline can surface.
558#[cfg(feature = "unstable-diagnostics")]
559#[doc(hidden)]
560#[must_use]
561pub fn debug_removed_minutiae(img: GrayImage<'_>) -> Vec<RawMinutia> {
562 use crate::params::LFSPARMS_V2;
563 use crate::remove::remove_false_minutia_v2;
564
565 // Shared front-end + `detect_minutiae_V2`.
566 let Some(mut st) = run_detect(img) else {
567 return Vec::new();
568 };
569
570 let p = &LFSPARMS_V2;
571 let (iw, ih) = (img.width() as i32, img.height() as i32);
572 let (mw, mh) = (st.maps.map_w as i32, st.maps.map_h as i32);
573
574 // The ten false-minutia removal stages, over the same in-place-edited binary and block maps.
575 if remove_false_minutia_v2(
576 &mut st.minutiae,
577 &mut st.bdata,
578 iw,
579 ih,
580 &st.maps.direction_map,
581 &st.maps.low_flow_map,
582 &st.maps.high_curve_map,
583 mw,
584 mh,
585 p,
586 )
587 .is_err()
588 {
589 return Vec::new();
590 }
591
592 to_raw(&st.minutiae)
593}
594
595/// Diagnostic (hidden): how many minutiae each numbered stage of `remove_false_minutia_V2` dropped
596/// for an input, indexed by the reference's own stage number minus one (slot `0` is stage 1, slot
597/// `9` is stage 10). Returns all zeros on the (size) error paths the pipeline can surface.
598///
599/// Runs the same front-end and `detect_minutiae_V2` as [`debug_removed_minutiae`], then the ten
600/// removal stages, measuring the list length across each. Exposed so a test can ask which stages the
601/// corpus actually exercises — a stage that never drops a minutia is untested by the `.rmin2` golden
602/// however green it reads.
603///
604/// Slot `0` is the sort, which permutes the list and so is always `0`. Slot `5` (stage 6,
605/// `remove_or_adjust_side_minutiae_V2`) both removes and *adjusts*; an adjust leaves the length
606/// alone, so the slot counts its remove path only.
607#[cfg(feature = "unstable-diagnostics")]
608#[doc(hidden)]
609#[must_use]
610pub fn debug_removal_tally(img: GrayImage<'_>) -> [usize; 10] {
611 use crate::params::LFSPARMS_V2;
612 use crate::remove::remove_false_minutia_v2;
613
614 let Some(mut st) = run_detect(img) else {
615 return [0; 10];
616 };
617
618 let p = &LFSPARMS_V2;
619 let (iw, ih) = (img.width() as i32, img.height() as i32);
620 let (mw, mh) = (st.maps.map_w as i32, st.maps.map_h as i32);
621
622 remove_false_minutia_v2(
623 &mut st.minutiae,
624 &mut st.bdata,
625 iw,
626 ih,
627 &st.maps.direction_map,
628 &st.maps.low_flow_map,
629 &st.maps.high_curve_map,
630 mw,
631 mh,
632 p,
633 )
634 .unwrap_or([0; 10])
635}
636
637/// Diagnostic (hidden): the intermediate maps and binarized image for an input, used by verification
638/// tooling to localize any divergence from the stock C reference before the minutiae stage.
639///
640/// A thin wrapper over [`build_maps`], exposed only under `unstable-diagnostics`. Returns empty maps
641/// on the (size) error paths `gen_image_maps` can surface.
642#[cfg(feature = "unstable-diagnostics")]
643#[doc(hidden)]
644#[must_use]
645pub fn debug_maps(img: GrayImage<'_>) -> DebugMaps {
646 build_maps(img)
647}
648
649/// The `lfs_detect_minutiae_V2` front-end up to and including the binarization stage
650/// (`detect.c` L455–L582): build the V2 lookup tables, pad the image by the max padding, scale it to
651/// 6 bits, run the block-map pipeline (`gen_image_maps`), then directionally binarize the padded image
652/// against the direction map (`binarize_V2`). Fills the four block maps, their dimensions, and the
653/// full-resolution `binarized` image (`0` = ridge / `255` = valley, the pre-`gray2bin` form). Returns
654/// empty maps on the (size) error paths `gen_image_maps` can surface. Shared by [`run_detect`] and, as
655/// the public [`debug_maps`], by the diagnostic surface.
656fn build_maps(img: GrayImage<'_>) -> DebugMaps {
657 use crate::binarize::binarize_v2;
658 use crate::consts::DFT_COEFS;
659 use crate::image::{bits_8to6, pad_gray_image};
660 use crate::init::{get_max_padding_V2, init_dftwaves, init_dir2rad, init_rotgrids, Relative2};
661 use crate::maps::gen_image_maps;
662 use crate::params::LFSPARMS_V2;
663
664 let p = &LFSPARMS_V2;
665
666 // Max padding required to support the rotated DFT windows / dirbin grids.
667 let maxpad = get_max_padding_V2(
668 p.windowsize,
669 p.windowoffset,
670 p.dirbin_grid_w,
671 p.dirbin_grid_h,
672 );
673
674 // V2 lookup tables (direction->radians, DFT waves, rotated DFT grids).
675 let dir2rad = init_dir2rad(p.num_directions);
676 let dftwaves = init_dftwaves(&DFT_COEFS, p.num_dft_waves, p.windowsize);
677 let dftgrids = init_rotgrids(
678 img.width() as i32,
679 Some(maxpad),
680 p.start_dir_angle,
681 p.num_directions,
682 p.windowsize,
683 p.windowsize,
684 Relative2::Origin,
685 );
686
687 // Pad, then scale to 6 bits [0..63].
688 let (mut pdata, pw, ph) = pad_gray_image(&img, maxpad as usize);
689 bits_8to6(&mut pdata);
690
691 match gen_image_maps(
692 &pdata, pw as i32, ph as i32, &dir2rad, &dftwaves, &dftgrids, p,
693 ) {
694 Ok(m) => {
695 // Binarization stage (detect.c L557): the dir-bin rotated grids share the single
696 // `maxpad` so the one padded image serves both the DFT and dir-bin passes. Then
697 // `binarize_V2` produces the (unpadded) black-ridge/white-valley image.
698 let dirbingrids = init_rotgrids(
699 img.width() as i32,
700 Some(maxpad),
701 p.start_dir_angle,
702 p.num_directions,
703 p.dirbin_grid_w,
704 p.dirbin_grid_h,
705 Relative2::Center,
706 );
707 let bin = binarize_v2(
708 &pdata,
709 pw as i32,
710 ph as i32,
711 &m.direction_map,
712 m.map_w,
713 &dirbingrids,
714 p,
715 );
716 DebugMaps {
717 direction_map: m.direction_map,
718 low_contrast_map: m.low_contrast_map,
719 low_flow_map: m.low_flow_map,
720 high_curve_map: m.high_curve_map,
721 map_w: m.map_w as usize,
722 map_h: m.map_h as usize,
723 binarized: bin.data,
724 }
725 }
726 Err(_) => DebugMaps::default(),
727 }
728}