library:ml: SCRFD letterbox, anchor decode and NMS
- Commit
c6b0e7e2a290a47090dd7d03306fdfb977f07191- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 02:45 UTC (3 months ago)
- Parents
8fe75f7
Diff
library/ml/src/main/rust/src/lib.rs
diff --git a/library/ml/src/main/rust/src/lib.rs b/library/ml/src/main/rust/src/lib.rsindex cc0ca019ec..2461676bd8 100644--- a/library/ml/src/main/rust/src/lib.rs+++ b/library/ml/src/main/rust/src/lib.rs@@ -36,6 +36,7 @@ //! arena arithmetic and the preprocessing, with no device and no asset. pub mod nets;+pub mod post; pub mod preprocess; pub mod weights;
library/ml/src/main/rust/src/post/mod.rs
diff --git a/library/ml/src/main/rust/src/post/mod.rs b/library/ml/src/main/rust/src/post/mod.rsnew file mode 100644index 0000000000..e02f2b7721--- /dev/null+++ b/library/ml/src/main/rust/src/post/mod.rs@@ -0,0 +1,13 @@+//! Turning a net's output maps into the things a caller actually wanted.+//!+//! Everything here is pure CPU work on small arrays, and deliberately so. A plan ends at+//! the last convolution; what follows is thresholding, sorting, pairwise comparison and+//! contour walking — data-dependent control flow over tens of candidates rather than+//! millions of elements, which is the one part of these pipelines a GPU makes slower.+//!+//! It is also the part that was invisible before. All of this lived inside the ncnn+//! fork's `.so`, so a wrong threshold or an off-by-one in an anchor centre could not be+//! read, let alone tested. Each module here is ported from a named C++ function and+//! host-tested against values computed by hand.++pub mod nms;
library/ml/src/main/rust/src/post/nms.rs
diff --git a/library/ml/src/main/rust/src/post/nms.rs b/library/ml/src/main/rust/src/post/nms.rsnew file mode 100644index 0000000000..a02d4e7180--- /dev/null+++ b/library/ml/src/main/rust/src/post/nms.rs@@ -0,0 +1,523 @@+//! SCRFD's post-processing: anchor decode, non-maximum suppression, and undoing the+//! letterbox.+//!+//! # Why this is host code and not a shader+//!+//! The plan stops at [`crate::nets::scrfd`]'s nine convolution outputs. What follows is+//! a threshold, a sort and a quadratic pairwise comparison over however many proposals+//! survived — data-dependent control flow over a handful of candidates, which is the+//! shape of work a GPU is worst at and a CPU finishes in microseconds.+//!+//! # Ported from `scrfd.cpp`, including its quirks+//!+//! Every constant and every rounding decision below is `scrfd.cpp:144-224` and+//! `:389-443`. Three are worth calling out because they look like mistakes:+//!+//! * **Anchor centres are `j * stride`, with no half-cell offset.** The reference builds+//! a table of anchor boxes and then uses only its row *count*: `distance2bbox` needs+//! the centre, and the centre is `anchor[0] + j * stride + anchor_w / 2`, in which the+//! `anchor_w / 2` cancels the `-anchor_w / 2` that `anchor[0]` is. So the box geometry+//! is independent of the anchor sizes, and this port does not compute them at all.+//! ([`ANCHORS`] is still 2, because the score map has two channels.)+//! * **Box extents carry an inclusive `+1`.** The reference sets+//! `width = x1 - x0 + 1`, so a box is a pixel wider and taller than+//! `distance2bbox` produced. That inflation is then *kept* through NMS and through the+//! undo, so it changes which detections survive. It is preserved here.+//! * **The letterbox offset is subtracted as an integer.** `wpad / 2` is integer+//! division in C++, and using the true half of an odd pad would shift every+//! coordinate by half a pixel.+//!+//! # One deliberate difference+//!+//! The reference sorts with a quicksort, which is unstable, so proposals with equal+//! scores come out in an arbitrary order and NMS then keeps an arbitrary one of them.+//! [`suppress`] sorts stably, so equal scores keep the order they were decoded in. That+//! makes this port *more* deterministic than the thing it replaces, and it is the reason+//! a bit-identical comparison against ncnn can differ on a tie.++use crate::nets::Shape;+use crate::preprocess::Letterbox;++/// Anchors per cell, at every stride. See the note above on why this is all that is+/// needed of the anchor table.+pub const ANCHORS: usize = 2;+/// Keypoints SCRFD predicts: both eyes, the nose, both mouth corners.+pub const KEYPOINTS: usize = 5;++/// Score at or above which a proposal is kept. `scrfd.cpp`'s caller default.+pub const SCORE_THRESHOLD: f32 = 0.5;+/// IoU **strictly above** which an overlapping proposal is dropped.+pub const IOU_THRESHOLD: f32 = 0.45;++/// One detected face.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Face {+ /// The score map's value, already through a sigmoid in the graph.+ pub score: f32,+ /// `[x0, y0, x1, y1]`, a half-open box: `x1` is one past the last column.+ ///+ /// The `+1` that makes it half-open is the reference's, applied at decode and never+ /// removed — see the module docs.+ pub bounds: [f32; 4],+ /// `(x, y)` per keypoint, in the same space as [`Face::bounds`].+ pub keypoints: [(f32, f32); KEYPOINTS],+}++impl Face {+ fn area(&self) -> f32 {+ let [x0, y0, x1, y1] = self.bounds;+ (x1 - x0).max(0.0) * (y1 - y0).max(0.0)+ }++ fn intersection(&self, other: &Face) -> f32 {+ let [ax0, ay0, ax1, ay1] = self.bounds;+ let [bx0, by0, bx1, by1] = other.bounds;+ let width = ax1.min(bx1) - ax0.max(bx0);+ let height = ay1.min(by1) - ay0.max(by0);+ if width <= 0.0 || height <= 0.0 {+ return 0.0;+ }+ width * height+ }+}++/// One stride's three maps, as the plan hands them back.+pub struct Maps<'a> {+ /// `[anchors, h, w]`, post-sigmoid.+ pub score: &'a [f32],+ /// `[anchors * 4, h, w]`: left, top, right, bottom distances in stride units.+ pub bbox: &'a [f32],+ /// `[anchors * 10, h, w]`: five `(x, y)` offsets in stride units.+ pub keypoints: &'a [f32],+ /// The score map's shape, which the other two share spatially.+ pub shape: Shape,+}++/// Decode one stride's maps into proposals, appending to `out`.+///+/// Iterates anchor, then row, then column — the reference's order, which is what fixes+/// the order of equal-scoring proposals under the stable sort in [`suppress`].+pub fn decode(+ maps: &Maps,+ stride: u32,+ threshold: f32,+ out: &mut Vec<Face>,+) -> Result<(), String> {+ let (h, w) = (maps.shape.h, maps.shape.w);+ let cells = (h * w) as usize;+ if maps.shape.c as usize != ANCHORS {+ return Err(format!("a score map with {} channels, not {ANCHORS}", maps.shape.c));+ }+ for (name, map, channels) in [+ ("score", maps.score, ANCHORS),+ ("box", maps.bbox, ANCHORS * 4),+ ("keypoint", maps.keypoints, ANCHORS * KEYPOINTS * 2),+ ] {+ if map.len() != cells * channels {+ return Err(format!(+ "a {name} map of {} values, not {channels} x {h} x {w}",+ map.len()+ ));+ }+ }++ let at = |map: &[f32], channel: usize, index: usize| -> Result<f32, String> {+ map.get(channel * cells + index)+ .copied()+ .ok_or_else(|| format!("channel {channel} element {index} is out of range"))+ };++ for anchor in 0..ANCHORS {+ for row in 0..h {+ for column in 0..w {+ let index = (row * w + column) as usize;+ let score = at(maps.score, anchor, index)?;+ if score < threshold {+ continue;+ }+ // The centre, with no half-cell offset. See the module docs.+ let cx = (column * stride) as f32;+ let cy = (row * stride) as f32;+ let distance = |k: usize| -> Result<f32, String> {+ Ok(at(maps.bbox, anchor * 4 + k, index)? * stride as f32)+ };+ let (left, top) = (distance(0)?, distance(1)?);+ let (right, bottom) = (distance(2)?, distance(3)?);+ let (x0, y0) = (cx - left, cy - top);+ let (x1, y1) = (cx + right, cy + bottom);++ let mut keypoints = [(0.0, 0.0); KEYPOINTS];+ for (k, point) in keypoints.iter_mut().enumerate() {+ let base = anchor * KEYPOINTS * 2 + k * 2;+ *point = (+ cx + at(maps.keypoints, base, index)? * stride as f32,+ cy + at(maps.keypoints, base + 1, index)? * stride as f32,+ );+ }++ out.push(Face {+ score,+ // `+ 1` on each extent: the reference's inclusive width and height.+ bounds: [x0, y0, x1 + 1.0, y1 + 1.0],+ keypoints,+ });+ }+ }+ }+ Ok(())+}++/// Sort by score and drop any proposal overlapping a better one by more than `threshold`.+///+/// Greedy and quadratic in the number of proposals, which after a 0.5 score threshold is+/// a handful even on a group photo.+pub fn suppress(faces: &mut Vec<Face>, threshold: f32) {+ // Stable, unlike the reference's quicksort — see the module docs. `total_cmp` rather+ // than `partial_cmp`: a NaN score would otherwise make the ordering inconsistent and+ // the sort's behaviour unspecified.+ faces.sort_by(|a, b| b.score.total_cmp(&a.score));++ let mut kept: Vec<Face> = Vec::new();+ for face in faces.iter() {+ let overlaps = kept.iter().any(|other| {+ let intersection = face.intersection(other);+ let union = face.area() + other.area() - intersection;+ // Strictly greater, and a zero union cannot suppress: two degenerate boxes+ // would otherwise divide by zero and compare as NaN, which is `false` here+ // but only by accident.+ union > 0.0 && intersection / union > threshold+ });+ if !overlaps {+ kept.push(*face);+ }+ }+ *faces = kept;+}++/// Map coordinates out of the letterboxed space and back onto the source image.+///+/// Undoes the padding and the scale, clamps to `[0, extent - 1]`, and then normalises to+/// `0..1` of the source — which is the form `scrfd_jni.cpp:77-84` returned and therefore+/// what the Kotlin already expects.+pub fn to_source(faces: &mut [Face], fit: &Letterbox, width: u32, height: u32) {+ let (left, top) = (fit.offset.0 as f32, fit.offset.1 as f32);+ let (limit_x, limit_y) = ((width.max(1) - 1) as f32, (height.max(1) - 1) as f32);+ let scale = if fit.scale == 0.0 { 1.0 } else { fit.scale };+ let undo = |value: f32, pad: f32, limit: f32| ((value - pad) / scale).clamp(0.0, limit);++ for face in faces {+ let [x0, y0, x1, y1] = face.bounds;+ face.bounds = [+ undo(x0, left, limit_x) / width as f32,+ undo(y0, top, limit_y) / height as f32,+ undo(x1, left, limit_x) / width as f32,+ undo(y1, top, limit_y) / height as f32,+ ];+ for point in &mut face.keypoints {+ *point = (+ undo(point.0, left, limit_x) / width as f32,+ undo(point.1, top, limit_y) / height as f32,+ );+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A `[channels, h, w]` map that is zero except for the values named.+ fn map(channels: usize, h: u32, w: u32, set: &[(usize, usize, f32)]) -> Vec<f32> {+ let mut values = vec![0.0; channels * (h * w) as usize];+ for &(channel, index, value) in set {+ if let Some(slot) = values.get_mut(channel * (h * w) as usize + index) {+ *slot = value;+ }+ }+ values+ }++ fn face(score: f32, bounds: [f32; 4]) -> Face {+ Face { score, bounds, keypoints: [(0.0, 0.0); KEYPOINTS] }+ }++ #[test]+ fn a_proposal_decodes_to_a_box_around_its_cell_centre() {+ // Anchor 0 at cell (1, 2) of a stride-8 map, all four distances 1.0 — so one+ // stride out in every direction from the centre at (16, 8).+ let shape = Shape::new(2, 4, 4);+ let (row, column) = (1usize, 2usize);+ let index = row * 4 + column;+ let score = map(2, 4, 4, &[(0, index, 0.9)]);+ let bbox = map(8, 4, 4, &[(0, index, 1.0), (1, index, 1.0), (2, index, 1.0), (3, index, 1.0)]);+ let keypoints = map(20, 4, 4, &[]);+ let mut out = Vec::new();+ decode(+ &Maps { score: &score, bbox: &bbox, keypoints: &keypoints, shape },+ 8,+ 0.5,+ &mut out,+ )+ .expect("decodes");++ assert_eq!(out.len(), 1);+ let got = out.first().copied().expect("one face");+ assert_eq!(got.score, 0.9);+ // Centre (16, 8), 8 out each way, then the inclusive `+1` on the far edges.+ assert_eq!(got.bounds, [8.0, 0.0, 25.0, 17.0]);+ }++ #[test]+ fn the_second_anchor_reads_its_own_slice_of_every_map() {+ // Anchor 1's box channels are 4..8 and its keypoints 10..20. Reading anchor 0's+ // by mistake gives a box at the same place with the wrong size, which is the+ // kind of error that halves recall and never crashes.+ let shape = Shape::new(2, 2, 2);+ let score = map(2, 2, 2, &[(1, 0, 0.8)]);+ let bbox = map(8, 2, 2, &[(4, 0, 2.0), (5, 0, 2.0), (6, 0, 3.0), (7, 0, 3.0)]);+ let keypoints = map(20, 2, 2, &[(10, 0, 1.0), (11, 0, -1.0)]);+ let mut out = Vec::new();+ decode(+ &Maps { score: &score, bbox: &bbox, keypoints: &keypoints, shape },+ 16,+ 0.5,+ &mut out,+ )+ .expect("decodes");++ let got = out.first().copied().expect("one face");+ // Cell (0, 0), so the centre is the origin: 2 strides left/up, 3 right/down.+ assert_eq!(got.bounds, [-32.0, -32.0, 49.0, 49.0]);+ assert_eq!(got.keypoints.first().copied(), Some((16.0, -16.0)));+ }++ #[test]+ fn keypoints_decode_as_offsets_from_the_centre_in_stride_units() {+ // Five distinct offsets, so a transposed x/y or a keypoint read at the wrong+ // channel pair is visible. Cell (0, 1) at stride 8, centre (8, 0).+ let shape = Shape::new(2, 1, 2);+ let score = map(2, 1, 2, &[(0, 1, 1.0)]);+ let bbox = map(8, 1, 2, &[]);+ let offsets: Vec<(usize, usize, f32)> = (0..10)+ .map(|k| (k, 1usize, (k as f32 + 1.0) / 8.0))+ .collect();+ let keypoints = map(20, 1, 2, &offsets);+ let mut out = Vec::new();+ decode(+ &Maps { score: &score, bbox: &bbox, keypoints: &keypoints, shape },+ 8,+ 0.5,+ &mut out,+ )+ .expect("decodes");++ let got = out.first().copied().expect("one face");+ // x gets 8 + (2k + 1), y gets 0 + (2k + 2).+ assert_eq!(+ got.keypoints,+ [(9.0, 2.0), (11.0, 4.0), (13.0, 6.0), (15.0, 8.0), (17.0, 10.0)]+ );+ }++ #[test]+ fn a_score_exactly_at_the_threshold_is_kept() {+ // The reference tests `prob >= prob_threshold`. Using `>` would silently drop+ // the boundary case, which on a quantised score map is not rare.+ let shape = Shape::new(2, 1, 1);+ let score = map(2, 1, 1, &[(0, 0, 0.5)]);+ let bbox = map(8, 1, 1, &[]);+ let keypoints = map(20, 1, 1, &[]);+ let mut out = Vec::new();+ decode(+ &Maps { score: &score, bbox: &bbox, keypoints: &keypoints, shape },+ 8,+ 0.5,+ &mut out,+ )+ .expect("decodes");+ assert_eq!(out.len(), 1);+ }++ #[test]+ fn suppression_keeps_the_best_of_an_overlapping_pair() {+ let mut faces = vec![+ face(0.6, [0.0, 0.0, 10.0, 10.0]),+ face(0.9, [1.0, 1.0, 11.0, 11.0]),+ ];+ suppress(&mut faces, 0.45);+ assert_eq!(faces.len(), 1);+ assert_eq!(faces.first().map(|f| f.score), Some(0.9));+ }++ #[test]+ fn suppression_keeps_two_faces_that_barely_overlap() {+ // 100-unit boxes sharing a 10x100 strip: IoU is 1000 / 19000, well under 0.45.+ let mut faces = vec![+ face(0.9, [0.0, 0.0, 100.0, 100.0]),+ face(0.8, [90.0, 0.0, 190.0, 100.0]),+ ];+ suppress(&mut faces, 0.45);+ assert_eq!(faces.len(), 2);+ }++ #[test]+ fn suppression_is_strictly_greater_than_the_threshold() {+ // Two boxes whose IoU is exactly 1/3. At a threshold of 1/3 the reference's+ // `>` keeps both; a `>=` would drop one.+ let mut faces =+ vec![face(0.9, [0.0, 0.0, 2.0, 1.0]), face(0.8, [1.0, 0.0, 3.0, 1.0])];+ let exactly = 1.0 / 3.0;+ suppress(&mut faces, exactly);+ assert_eq!(faces.len(), 2, "an IoU equal to the threshold must not suppress");+ suppress(&mut faces, exactly - 0.01);+ assert_eq!(faces.len(), 1);+ }++ #[test]+ fn suppression_compares_against_everything_already_kept() {+ // Three boxes in a row where the middle one overlaps both ends but the ends do+ // not overlap each other. A greedy pass that only compared with the immediately+ // preceding proposal would keep the middle one.+ let mut faces = vec![+ face(0.9, [0.0, 0.0, 10.0, 10.0]),+ face(0.7, [2.0, 0.0, 12.0, 10.0]),+ face(0.8, [40.0, 0.0, 50.0, 10.0]),+ ];+ suppress(&mut faces, 0.45);+ let scores: Vec<f32> = faces.iter().map(|f| f.score).collect();+ assert_eq!(scores, vec![0.9, 0.8]);+ }++ #[test]+ fn equal_scores_keep_their_decode_order() {+ // The one deliberate divergence from `scrfd.cpp`, whose quicksort leaves this+ // arbitrary. Pinned so a future change to the sort is a visible decision.+ let mut faces = vec![+ face(0.7, [0.0, 0.0, 1.0, 1.0]),+ face(0.7, [100.0, 0.0, 101.0, 1.0]),+ face(0.7, [200.0, 0.0, 201.0, 1.0]),+ ];+ suppress(&mut faces, 0.45);+ let lefts: Vec<f32> = faces.iter().map(|f| f.bounds[0]).collect();+ assert_eq!(lefts, vec![0.0, 100.0, 200.0]);+ }++ #[test]+ fn undoing_the_letterbox_recovers_the_original_fraction() {+ // A 1280x720 photo: scale 0.5, resized 640x360, padded to 640x384, so 12 rows of+ // padding above. A box filling the image maps back to the whole frame.+ let fit = Letterbox::new(1280, 720, 640, 32).expect("fits");+ assert_eq!(fit.resized, (640, 360));+ assert_eq!(fit.padded, (640, 384));+ assert_eq!(fit.offset, (0, 12));++ let mut faces = vec![face(0.9, [0.0, 12.0, 640.0, 372.0])];+ to_source(&mut faces, &fit, 1280, 720);+ let got = faces.first().copied().expect("one face");+ // Clamped to the last pixel, hence 1279/1280 rather than exactly 1.+ assert!((got.bounds[0] - 0.0).abs() < 1e-6, "{:?}", got.bounds);+ assert!((got.bounds[1] - 0.0).abs() < 1e-6, "{:?}", got.bounds);+ assert!((got.bounds[2] - 1279.0 / 1280.0).abs() < 1e-6, "{:?}", got.bounds);+ assert!((got.bounds[3] - 719.0 / 720.0).abs() < 1e-6, "{:?}", got.bounds);+ }++ #[test]+ fn a_coordinate_outside_the_image_clamps_rather_than_going_negative() {+ // Decode routinely produces boxes past the edge — the distances are unbounded —+ // and a negative normalised coordinate would index outside the bitmap when the+ // Kotlin crops.+ let fit = Letterbox::new(640, 640, 640, 32).expect("fits");+ let mut faces = vec![face(0.9, [-500.0, -500.0, 5000.0, 5000.0])];+ to_source(&mut faces, &fit, 640, 640);+ let got = faces.first().copied().expect("one face");+ for value in got.bounds {+ assert!((0.0..=1.0).contains(&value), "{:?}", got.bounds);+ }+ }++ #[test]+ fn a_portrait_photo_pads_on_the_left_and_right() {+ // 720x1280: the long side is the height, so the width scales to 360 and pads to+ // 384 — 12 columns on the left. The transposed case of the test above, which is+ // where a swapped width/height shows up.+ let fit = Letterbox::new(720, 1280, 640, 32).expect("fits");+ assert_eq!(fit.resized, (360, 640));+ assert_eq!(fit.padded, (384, 640));+ assert_eq!(fit.offset, (12, 0));+ }++ #[test]+ fn a_square_photo_needs_no_padding_at_all() {+ let fit = Letterbox::new(1000, 1000, 640, 32).expect("fits");+ assert_eq!(fit.resized, (640, 640));+ assert_eq!(fit.padded, (640, 640));+ assert_eq!(fit.offset, (0, 0));+ }++ #[test]+ fn the_short_side_truncates_rather_than_rounds() {+ // 1000x667 at scale 0.64 gives 426.88. The reference truncates to 426, which+ // pads to 448; rounding to 427 would also pad to 448 but shift the image one+ // row, and there are aspect ratios where it changes the padded size outright.+ let fit = Letterbox::new(1000, 667, 640, 32).expect("fits");+ assert_eq!(fit.resized.1, 426);+ assert_eq!(fit.padded.1, 448);+ // 22 rows of padding, 11 above: an even split here, but the odd case below is+ // the one that pins the integer division.+ assert_eq!(fit.offset.1, 11);+ }++ #[test]+ fn an_odd_pad_puts_the_extra_row_at_the_bottom() {+ // Any short side that pads by an odd number: `pad / 2` above and the rest below.+ let fit = Letterbox::new(640, 27, 640, 32).expect("fits");+ assert_eq!(fit.resized, (640, 27));+ assert_eq!(fit.padded, (640, 32));+ // 5 rows of padding: 2 above, 3 below.+ assert_eq!(fit.offset.1, 2);+ }++ #[test]+ fn every_letterbox_extent_is_a_multiple_of_the_requested_size() {+ // The net refuses anything else, so this is the property that keeps the two in+ // agreement across every aspect ratio a camera produces.+ for (width, height) in [+ (4032, 3024),+ (3024, 4032),+ (1920, 1080),+ (1080, 1920),+ (640, 480),+ (1, 4000),+ (4000, 1),+ (1, 1),+ ] {+ let fit = Letterbox::new(width, height, 640, 32).expect("fits");+ assert!(fit.padded.0.is_multiple_of(32), "{width}x{height}: {:?}", fit.padded);+ assert!(fit.padded.1.is_multiple_of(32), "{width}x{height}: {:?}", fit.padded);+ assert!(fit.padded.0 >= fit.resized.0 && fit.padded.1 >= fit.resized.1);+ }+ }++ #[test]+ fn a_zero_sized_image_is_refused() {+ assert!(Letterbox::new(0, 100, 640, 32).is_err());+ assert!(Letterbox::new(100, 0, 640, 32).is_err());+ }++ #[test]+ fn a_map_of_the_wrong_length_is_refused_rather_than_read_short() {+ let shape = Shape::new(2, 2, 2);+ let score = map(2, 2, 2, &[]);+ let bbox = map(4, 2, 2, &[]);+ let keypoints = map(20, 2, 2, &[]);+ let mut out = Vec::new();+ let error = decode(+ &Maps { score: &score, bbox: &bbox, keypoints: &keypoints, shape },+ 8,+ 0.5,+ &mut out,+ )+ .expect_err("a short box map");+ assert!(error.contains("box map"), "{error}");+ }+}
library/ml/src/main/rust/src/preprocess.rs
diff --git a/library/ml/src/main/rust/src/preprocess.rs b/library/ml/src/main/rust/src/preprocess.rsindex 012b4713fb..c30f93cbe3 100644--- a/library/ml/src/main/rust/src/preprocess.rs+++ b/library/ml/src/main/rust/src/preprocess.rs@@ -44,6 +44,173 @@ pub const RESCALE_ONLY: Normalise = Normalise { mean: [0.0; 3], std: [1.0; 3] }; pub const IMAGENET: Normalise = Normalise { mean: [0.485, 0.456, 0.406], std: [0.229, 0.224, 0.225] }; +/// `(value - 127.5) / 128` on the `0..255` scale, which is what SCRFD wants.+///+/// Expressed against the `0..1` rescale every [`Normalise`] applies: `127.5 / 255` is+/// exactly `0.5`, and dividing by `128 / 255` is dividing by 128 after the rescale.+///+/// **Not** [`FACE_EMBED`], whose divisor is 127.5. The two differ by 0.4% and share a+/// mean, so a swapped constant shifts every embedding slightly and every box slightly,+/// with no symptom either would fail on. `scrfd.cpp:310` and the MobileFaceNet+/// preprocessing are the two places that disagree.+pub const SCRFD: Normalise =+ Normalise { mean: [0.5, 0.5, 0.5], std: [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0] };++/// `(value - 127.5) / 127.5` on the `0..255` scale, which is what MobileFaceNet wants.+/// See [`SCRFD`] for why these are two constants and not one.+pub const FACE_EMBED: Normalise = Normalise { mean: [0.5, 0.5, 0.5], std: [0.5, 0.5, 0.5] };++/// How an image was fitted into the detector's input, and what it takes to undo it.+///+/// SCRFD runs at 640 on the long side with the short side padded up to a multiple of 32,+/// the image centred in the padding. Every box and keypoint the net predicts is in this+/// padded space, so [`Letterbox`] is carried alongside them until+/// `post::nms::to_source` maps them back.+///+/// The arithmetic is `scrfd.cpp:286-308` reproduced exactly, integer truncation+/// included. Two details are load-bearing:+///+/// * The resized extent is `(original * scale) as u32` — a **truncation**, not a round.+/// At 640 on the long side that differs by a pixel often enough to matter, and the+/// padding is derived from it.+/// * The padding is split `pad / 2` above and `pad - pad / 2` below, with **integer**+/// division, so an odd pad puts the extra row at the bottom. Undoing it subtracts the+/// same integer `pad / 2`, which is why that value is stored rather than recomputed+/// from a float.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Letterbox {+ /// What the source was multiplied by to reach [`Letterbox::resized`].+ pub scale: f32,+ /// `(width, height)` after scaling, before padding.+ pub resized: (u32, u32),+ /// `(width, height)` after padding. Both are multiples of the requested multiple.+ pub padded: (u32, u32),+ /// `(left, top)` padding, which is what a coordinate has subtracted from it.+ pub offset: (u32, u32),+}++impl Letterbox {+ /// Fit a `width` x `height` image to `long_side`, padding up to `multiple`.+ pub fn new(+ width: u32,+ height: u32,+ long_side: u32,+ multiple: u32,+ ) -> Result<Letterbox, String> {+ if width == 0 || height == 0 {+ return Err(format!("a {width}x{height} image"));+ }+ if long_side == 0 || multiple == 0 {+ return Err(format!("a {long_side} long side at a multiple of {multiple}"));+ }+ // The long side goes to `long_side`; the short side follows by the same scale,+ // truncated. `.max(1)` only bites at aspect ratios beyond about 640:1.+ let (scale, resized) = if width > height {+ let scale = long_side as f32 / width as f32;+ (scale, (long_side, ((height as f32 * scale) as u32).max(1)))+ } else {+ let scale = long_side as f32 / height as f32;+ (scale, (((width as f32 * scale) as u32).max(1), long_side))+ };+ let pad = |extent: u32| extent.div_ceil(multiple) * multiple - extent;+ let (pad_w, pad_h) = (pad(resized.0), pad(resized.1));+ Ok(Letterbox {+ scale,+ resized,+ padded: (resized.0 + pad_w, resized.1 + pad_h),+ offset: (pad_w / 2, pad_h / 2),+ })+ }++ /// The net's input shape for this fit.+ pub fn shape(&self) -> Shape {+ Shape::new(3, self.padded.1, self.padded.0)+ }+}++/// Resize `pixels` into `fit`'s padded extent and write it as planar fp16.+///+/// The image is scaled to `fit.resized`, centred at `fit.offset`, and everything outside+/// it is filled with **raw zero put through `norm`** — not with zero. `scrfd.cpp` pads+/// before it normalises, so the border a detection can see is `(0 - 127.5) / 128`, which+/// is about `-0.996` rather than neutral grey. Filling with 0.0 instead changes what the+/// net sees along two edges of every non-square photo.+pub fn to_letterboxed_f16(+ pixels: &[i32],+ width: u32,+ height: u32,+ fit: &Letterbox,+ norm: &Normalise,+ dst: &mut [u16],+) -> Result<(), String> {+ if width == 0 || height == 0 {+ return Err("a zero-sized bitmap".into());+ }+ let expected = (width as usize)+ .checked_mul(height as usize)+ .ok_or("bitmap dimensions overflow")?;+ if pixels.len() != expected {+ return Err(format!("{} pixels for a {width}x{height} bitmap", pixels.len()));+ }+ let shape = fit.shape();+ if dst.len() != shape.len() as usize {+ return Err(format!("{} output elements for {shape:?}", dst.len()));+ }++ let plane = (shape.h * shape.w) as usize;+ let (out_w, out_h) = fit.resized;+ let (left, top) = fit.offset;+ let x_scale = width as f32 / out_w as f32;+ let y_scale = height as f32 / out_h as f32;++ // The border value, computed once: raw 0 through the normalisation.+ let border: [u16; 3] = [0, 1, 2].map(|c| {+ let mean = norm.mean.get(c).copied().unwrap_or(0.0);+ let std = norm.std.get(c).copied().unwrap_or(1.0);+ f32_to_f16((0.0 - mean) / std)+ });++ for out_y in 0..shape.h {+ let inside_row = out_y >= top && out_y < top + out_h;+ let (y0, y1, wy) = if inside_row {+ sample(out_y - top, y_scale, height)+ } else {+ (0, 0, 0.0)+ };+ for out_x in 0..shape.w {+ let at = (out_y * shape.w + out_x) as usize;+ if !inside_row || out_x < left || out_x >= left + out_w {+ for channel in 0..3usize {+ let slot = dst+ .get_mut(channel * plane + at)+ .ok_or("letterboxing wrote past the end of its output")?;+ *slot = border.get(channel).copied().unwrap_or(0);+ }+ continue;+ }+ let (x0, x1, wx) = sample(out_x - left, x_scale, width);++ let p00 = pixel(pixels, width, x0, y0);+ let p10 = pixel(pixels, width, x1, y0);+ let p01 = pixel(pixels, width, x0, y1);+ let p11 = pixel(pixels, width, x1, y1);++ for channel in 0..3usize {+ let top_row = lerp(p00[channel], p10[channel], wx);+ let bottom_row = lerp(p01[channel], p11[channel], wx);+ let value = lerp_f32(top_row, bottom_row, wy) / 255.0;+ let mean = norm.mean.get(channel).copied().unwrap_or(0.0);+ let std = norm.std.get(channel).copied().unwrap_or(1.0);+ let slot = dst+ .get_mut(channel * plane + at)+ .ok_or("letterboxing wrote past the end of its output")?;+ *slot = f32_to_f16((value - mean) / std);+ }+ }+ }+ Ok(())+}+ /// Resize `pixels` to `shape` and write it as planar fp16. /// /// `pixels` is `ARGB_8888` as `Bitmap.getPixels` produces it — `0xAARRGGBB` per entry,@@ -330,6 +497,96 @@ mod tests { assert!(f16_to_f32(f32_to_f16(-1e-30)).is_sign_negative()); } + #[test]+ fn the_scrfd_and_embedder_normalisations_share_a_mean_but_not_a_divisor() {+ // Both are `(v - 127.5) / d`, with d = 128 and d = 127.5. The 0.4% difference is+ // invisible in any output, so the two constants are pinned against a direct+ // computation on the 0..255 scale rather than against each other.+ let through = |norm: &Normalise, raw: f32| (raw / 255.0 - norm.mean[0]) / norm.std[0];+ for raw in [0.0f32, 127.5, 255.0] {+ assert!((through(&SCRFD, raw) - (raw - 127.5) / 128.0).abs() < 1e-6, "{raw}");+ assert!(+ (through(&FACE_EMBED, raw) - (raw - 127.5) / 127.5).abs() < 1e-6,+ "{raw}"+ );+ }+ // And they really are different, so a swap is a change.+ assert_ne!(SCRFD.std[0], FACE_EMBED.std[0]);+ }++ #[test]+ fn letterbox_padding_is_normalised_zero_and_not_zero() {+ // `scrfd.cpp` pads with raw 0 *before* it normalises, so the border the net sees+ // is (0 - 127.5) / 128. Filling with 0.0 instead — the obvious reading of "pad+ // with zero" — puts a mid-grey frame around every non-square photo.+ //+ // 64x20 at a long side of 64: no scaling, and the height pads 20 up to 32, so+ // 6 rows above and 6 below.+ let pixels = vec![argb(255, 255, 255); 64 * 20];+ let fit = Letterbox::new(64, 20, 64, 32).expect("fits");+ assert_eq!(fit.resized, (64, 20));+ assert_eq!(fit.padded, (64, 32));+ assert_eq!(fit.offset, (0, 6));++ let shape = fit.shape();+ let mut out = vec![0u16; shape.len() as usize];+ to_letterboxed_f16(&pixels, 64, 20, &fit, &SCRFD, &mut out).expect("letterboxes");++ let want_border = (0.0 - 127.5) / 128.0;+ let want_image = (255.0 - 127.5) / 128.0;+ let row = |y: u32| f16_to_f32(out[(y * shape.w) as usize]);+ // Row 0 and row 5 are padding, row 6 is the first image row.+ assert!((row(0) - want_border).abs() < 2e-3, "row 0 is {}", row(0));+ assert!((row(5) - want_border).abs() < 2e-3, "row 5 is {}", row(5));+ assert!((row(6) - want_image).abs() < 2e-3, "row 6 is {}", row(6));+ // Row 25 is the last image row, 26 and 31 are the bottom padding.+ assert!((row(25) - want_image).abs() < 2e-3, "row 25 is {}", row(25));+ assert!((row(26) - want_border).abs() < 2e-3, "row 26 is {}", row(26));+ assert!((row(31) - want_border).abs() < 2e-3, "row 31 is {}", row(31));+ }++ #[test]+ fn a_letterboxed_image_lands_centred_at_the_offset() {+ // A single white column in an otherwise black source, so its position after+ // padding is unambiguous. 20x64 portrait at a long side of 64: no scaling, and+ // the width pads 20 up to 32, so 6 columns on the left.+ let mut pixels = vec![argb(0, 0, 0); 20 * 64];+ for row in 0..64 {+ pixels[row * 20 + 10] = argb(255, 255, 255);+ }+ let fit = Letterbox::new(20, 64, 64, 32).expect("fits");+ assert_eq!(fit.resized, (20, 64));+ assert_eq!(fit.padded, (32, 64));+ assert_eq!(fit.offset, (6, 0));++ let shape = fit.shape();+ let mut out = vec![0u16; shape.len() as usize];+ to_letterboxed_f16(&pixels, 20, 64, &fit, &RESCALE_ONLY, &mut out)+ .expect("letterboxes");++ // The bright column was at source x = 10, so it is at output x = 10 + 6 = 16.+ let row = (shape.h / 2 * shape.w) as usize;+ let brightest = (0..shape.w)+ .max_by(|&a, &b| {+ f16_to_f32(out[row + a as usize]).total_cmp(&f16_to_f32(out[row + b as usize]))+ })+ .expect("a row");+ assert_eq!(brightest, 16);+ // And the padding either side really is the border, not a smeared edge pixel.+ assert_eq!(f16_to_f32(out[row]), 0.0);+ assert_eq!(f16_to_f32(out[row + 31]), 0.0);+ }++ #[test]+ fn a_mismatched_letterbox_output_length_is_refused() {+ let pixels = vec![argb(0, 0, 0); 4];+ let fit = Letterbox::new(2, 2, 64, 32).expect("fits");+ let mut out = vec![0u16; 8];+ let error = to_letterboxed_f16(&pixels, 2, 2, &fit, &SCRFD, &mut out)+ .expect_err("wrong length");+ assert!(error.contains("output elements"), "{error}");+ }+ #[test] fn a_mismatched_output_length_is_refused() { let pixels = vec![argb(0, 0, 0)];