Skip to main content

qualia_vision/biosense/face/
yunet_decode_detections.rs

1//! Decode YuNet-style face detection tensors into fixed detection boxes.
2//!
3//! Runtime-agnostic: caller supplies model output floats (from ORT/tract/other).
4//! Weight file is MIT (OpenCV Zoo YuNet) — PermissiveReady, not commercial-gated.
5
6use crate::cv::error::CvError;
7
8/// One face box in normalized image coordinates (0..1) or pixels if scale applied.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct FaceBox {
11    pub x: f32,
12    pub y: f32,
13    pub w: f32,
14    pub h: f32,
15    pub score: f32,
16}
17
18/// YuNet multi-stride heads emit prior-decoded boxes; this decoder accepts a flat
19/// list of rows `[x, y, w, h, score, ...pad]` with `stride` floats per row.
20pub fn yunet_decode_detections(
21    rows: &[f32],
22    stride: usize,
23    score_idx: usize,
24    min_score: f32,
25    out: &mut [FaceBox],
26) -> Result<usize, CvError> {
27    if stride < 5 || score_idx >= stride {
28        return Err(CvError::InvalidParameter);
29    }
30    if rows.is_empty() {
31        return Ok(0);
32    }
33    if rows.len() % stride != 0 {
34        return Err(CvError::DimensionMismatch);
35    }
36    let n_rows = rows.len() / stride;
37    let mut written = 0usize;
38    for i in 0..n_rows {
39        if written >= out.len() {
40            break;
41        }
42        let base = i * stride;
43        let score = rows[base + score_idx];
44        if score < min_score {
45            continue;
46        }
47        out[written] = FaceBox {
48            x: rows[base],
49            y: rows[base + 1],
50            w: rows[base + 2],
51            h: rows[base + 3],
52            score,
53        };
54        written += 1;
55    }
56    Ok(written)
57}
58
59/// Greedy IoU NMS into `out` (caller buffer); returns kept count.
60pub fn face_nms(boxes: &[FaceBox], iou_thr: f32, out: &mut [FaceBox]) -> usize {
61    let mut order: [usize; 256] = [0; 256];
62    let n = boxes.len().min(256);
63    for i in 0..n {
64        order[i] = i;
65    }
66    // Simple selection sort by score desc (n small).
67    for i in 0..n {
68        let mut best = i;
69        for j in (i + 1)..n {
70            if boxes[order[j]].score > boxes[order[best]].score {
71                best = j;
72            }
73        }
74        order.swap(i, best);
75    }
76    let mut kept = 0usize;
77    let mut suppressed = [false; 256];
78    for a in 0..n {
79        let ia = order[a];
80        if suppressed[ia] {
81            continue;
82        }
83        if kept >= out.len() {
84            break;
85        }
86        out[kept] = boxes[ia];
87        kept += 1;
88        for b in (a + 1)..n {
89            let ib = order[b];
90            if suppressed[ib] {
91                continue;
92            }
93            if iou(boxes[ia], boxes[ib]) > iou_thr {
94                suppressed[ib] = true;
95            }
96        }
97    }
98    kept
99}
100
101fn iou(a: FaceBox, b: FaceBox) -> f32 {
102    let ax2 = a.x + a.w;
103    let ay2 = a.y + a.h;
104    let bx2 = b.x + b.w;
105    let by2 = b.y + b.h;
106    let ix1 = a.x.max(b.x);
107    let iy1 = a.y.max(b.y);
108    let ix2 = ax2.min(bx2);
109    let iy2 = ay2.min(by2);
110    let iw = (ix2 - ix1).max(0.0);
111    let ih = (iy2 - iy1).max(0.0);
112    let inter = iw * ih;
113    let uni = a.w * a.h + b.w * b.h - inter;
114    if uni <= 1e-9 {
115        0.0
116    } else {
117        inter / uni
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn decode_filters_score() {
127        let rows = [0.1, 0.1, 0.2, 0.2, 0.9, 0.0, 0.5, 0.5, 0.1, 0.1, 0.05, 0.0];
128        let mut out = [FaceBox {
129            x: 0.0,
130            y: 0.0,
131            w: 0.0,
132            h: 0.0,
133            score: 0.0,
134        }; 4];
135        let n = yunet_decode_detections(&rows, 6, 4, 0.2, &mut out).unwrap();
136        assert_eq!(n, 1);
137        assert!((out[0].score - 0.9).abs() < 1e-5);
138    }
139
140    #[test]
141    fn nms_suppresses_overlap() {
142        let boxes = [
143            FaceBox {
144                x: 0.0,
145                y: 0.0,
146                w: 1.0,
147                h: 1.0,
148                score: 0.9,
149            },
150            FaceBox {
151                x: 0.1,
152                y: 0.1,
153                w: 1.0,
154                h: 1.0,
155                score: 0.8,
156            },
157        ];
158        let mut out = [FaceBox {
159            x: 0.0,
160            y: 0.0,
161            w: 0.0,
162            h: 0.0,
163            score: 0.0,
164        }; 2];
165        let k = face_nms(&boxes, 0.3, &mut out);
166        assert_eq!(k, 1);
167    }
168}