Skip to main content

smriti/ml/
face_detector.rs

1//! SCRFD Face Detection
2//!
3//! Detects faces in images and returns bounding boxes with landmarks.
4//! Uses the SCRFD-10GF model via ONNX Runtime.
5//!
6//! SCRFD outputs 9 tensors (3 strides x 3 types):
7//! ```text
8//!   Stride 8:  scores[12800,1], bboxes[12800,4], landmarks[12800,10]
9//!   Stride 16: scores[3200,1],  bboxes[3200,4],  landmarks[3200,10]
10//!   Stride 32: scores[800,1],   bboxes[800,4],   landmarks[800,10]
11//! ```
12//!
13//! Bboxes are anchor-distance format (left, top, right, bottom distances from anchor center).
14//! Landmarks are (dx, dy) offsets from anchor center for 5 keypoints.
15
16use std::path::Path;
17
18#[allow(unused_imports)]
19use image::GenericImageView; // needed by `DynamicImage::dimensions()` in some configurations
20use image::{DynamicImage, RgbImage};
21use ort::session::Session;
22use ort::value::TensorRef;
23
24use super::OnnxRuntime;
25
26/// A detected face with bounding box and landmarks
27#[derive(Debug, Clone)]
28pub struct DetectedFace {
29    /// Bounding box (x, y, width, height) in pixel coordinates
30    pub bbox: (f32, f32, f32, f32),
31
32    /// Normalized bounding box (0-1 range)
33    pub bbox_normalized: (f32, f32, f32, f32),
34
35    /// Detection confidence (0-1)
36    pub confidence: f32,
37
38    /// 5-point landmarks: left_eye, right_eye, nose, left_mouth, right_mouth
39    /// Each point is (x, y) in pixel coordinates
40    pub landmarks: [(f32, f32); 5],
41
42    /// Cropped and aligned face image (112x112)
43    pub aligned_face: Option<RgbImage>,
44}
45
46/// SCRFD Face Detector
47pub struct FaceDetector {
48    session: Option<Session>,
49    model_path: std::path::PathBuf,
50    cpu_fallback_attempted: bool,
51    input_size: (u32, u32),
52    confidence_threshold: f32,
53    nms_threshold: f32,
54}
55
56/// Per-stride output from the model
57struct StrideOutput {
58    scores: Vec<f32>,
59    bboxes: Vec<f32>,
60    landmarks: Vec<f32>,
61    num_anchors: usize,
62    stride: u32,
63}
64
65impl FaceDetector {
66    /// Load the SCRFD model with a specific thread count per session.
67    pub fn new_with_threads<P: AsRef<Path>>(
68        runtime: &OnnxRuntime,
69        model_path: P,
70        intra_threads: usize,
71    ) -> ort::Result<Self> {
72        let model_path = model_path.as_ref().to_path_buf();
73        let _ = runtime;
74        let session = OnnxRuntime::load_cpu_model_with_threads(&model_path, intra_threads)?;
75
76        Ok(Self {
77            session: Some(session),
78            model_path,
79            cpu_fallback_attempted: false,
80            input_size: (640, 640),
81            confidence_threshold: 0.5,
82            nms_threshold: 0.4,
83        })
84    }
85
86    /// Set confidence threshold for detection
87    pub fn with_confidence_threshold(mut self, threshold: f32) -> Self {
88        self.confidence_threshold = threshold;
89        self
90    }
91
92    /// Detect faces in an image
93    pub fn detect(&mut self, image: &DynamicImage) -> Vec<DetectedFace> {
94        let (orig_width, orig_height) = image.dimensions();
95
96        // Preprocess image to NCHW float tensor
97        let input_data = self.preprocess(image);
98
99        // Run inference
100        let outputs = match self.run_inference(&input_data) {
101            Ok(o) => o,
102            Err(e) => {
103                tracing::error!("Face detection inference failed: {}", e);
104                return Vec::new();
105            }
106        };
107
108        // Post-process outputs
109        let mut faces = self.postprocess(&outputs, orig_width, orig_height);
110
111        // Apply NMS
112        faces = self.non_max_suppression(faces);
113
114        // Align faces for embedding
115        for face in &mut faces {
116            face.aligned_face = Some(self.align_face(image, &face.landmarks));
117        }
118
119        faces
120    }
121
122    /// Detect faces with adaptive multi-scale fallback for high-res images.
123    ///
124    /// Pass 1: normal full-frame detection.
125    /// Pass 2 (fallback): overlapping high-res tiles if pass 1 found no faces
126    /// and image is large, to recover small/profile faces lost by global resizing.
127    pub fn detect_adaptive(&mut self, image: &DynamicImage) -> Vec<DetectedFace> {
128        let first_pass = self.detect(image);
129        if !first_pass.is_empty() {
130            return first_pass;
131        }
132
133        let (orig_w, orig_h) = image.dimensions();
134        if orig_w.max(orig_h) <= 2048 {
135            return first_pass;
136        }
137
138        let tile = 1600u32;
139        let step = 1200u32; // overlap for boundary faces
140        let mut all_faces = Vec::new();
141
142        let max_x = orig_w.saturating_sub(1);
143        let max_y = orig_h.saturating_sub(1);
144
145        let mut y = 0u32;
146        while y <= max_y {
147            let mut x = 0u32;
148            while x <= max_x {
149                let crop_w = tile.min(orig_w.saturating_sub(x)).max(1);
150                let crop_h = tile.min(orig_h.saturating_sub(y)).max(1);
151                let crop = image.crop_imm(x, y, crop_w, crop_h);
152
153                let mut local = self.detect(&crop);
154                if !local.is_empty() {
155                    for face in &mut local {
156                        let (bx, by, bw, bh) = face.bbox;
157                        let gx = bx + x as f32;
158                        let gy = by + y as f32;
159                        face.bbox = (gx, gy, bw, bh);
160                        face.bbox_normalized = (
161                            gx / orig_w as f32,
162                            gy / orig_h as f32,
163                            bw / orig_w as f32,
164                            bh / orig_h as f32,
165                        );
166
167                        for lm in &mut face.landmarks {
168                            lm.0 += x as f32;
169                            lm.1 += y as f32;
170                        }
171                    }
172                    all_faces.extend(local);
173                }
174
175                if x + step >= orig_w {
176                    break;
177                }
178                x += step;
179            }
180
181            if y + step >= orig_h {
182                break;
183            }
184            y += step;
185        }
186
187        if all_faces.is_empty() {
188            return all_faces;
189        }
190
191        self.non_max_suppression(all_faces)
192    }
193
194    /// Preprocess image for SCRFD: resize to 640x640, normalize, produce NCHW vec
195    fn preprocess(&self, image: &DynamicImage) -> Vec<f32> {
196        let (target_w, target_h) = self.input_size;
197
198        // Resize to target dimensions
199        let resized = image.resize_exact(target_w, target_h, image::imageops::FilterType::Triangle);
200
201        let rgb = resized.to_rgb8();
202
203        // Convert to NCHW float and normalize (mean=127.5, std=128)
204        let mut input = vec![0.0f32; (3 * target_h * target_w) as usize];
205        let hw = (target_h * target_w) as usize;
206
207        for y in 0..target_h {
208            for x in 0..target_w {
209                let pixel = rgb.get_pixel(x, y);
210                let idx = (y * target_w + x) as usize;
211                input[idx] = (pixel[0] as f32 - 127.5) / 128.0; // R channel
212                input[hw + idx] = (pixel[1] as f32 - 127.5) / 128.0; // G channel
213                input[2 * hw + idx] = (pixel[2] as f32 - 127.5) / 128.0; // B channel
214            }
215        }
216
217        input
218    }
219
220    /// Run ONNX inference and extract output tensors with their shapes
221    fn run_inference(&mut self, input_data: &[f32]) -> ort::Result<Vec<(Vec<i64>, Vec<f32>)>> {
222        match self.run_inference_once(input_data) {
223            Ok(output) => Ok(output),
224            Err(error) if !self.cpu_fallback_attempted => {
225                tracing::warn!(%error, "Detector inference failed; retrying once on CPU");
226                self.cpu_fallback_attempted = true;
227                self.session = None; // Release device memory before constructing the fallback.
228                self.session = Some(OnnxRuntime::load_cpu_model(&self.model_path)?);
229                self.run_inference_once(input_data)
230            }
231            Err(error) => Err(error),
232        }
233    }
234
235    fn run_inference_once(&mut self, input_data: &[f32]) -> ort::Result<Vec<(Vec<i64>, Vec<f32>)>> {
236        let (target_w, target_h) = self.input_size;
237
238        // Create input tensor (shape [1, 3, 640, 640])
239        let input_tensor = TensorRef::<f32>::from_array_view((
240            vec![1i64, 3, target_h as i64, target_w as i64],
241            input_data,
242        ))?;
243
244        let outputs = self
245            .session
246            .as_mut()
247            .ok_or_else(|| ort::Error::new("Detector session unavailable"))?
248            .run(ort::inputs![input_tensor])?;
249
250        // Extract all output tensors with shapes
251        let mut results = Vec::new();
252        for (_name, value) in outputs.iter() {
253            let (shape, data) = value.try_extract_tensor::<f32>()?;
254            results.push((shape.to_vec(), data.to_vec()));
255        }
256
257        Ok(results)
258    }
259
260    /// Classify and group the 9 output tensors into 3 stride groups.
261    ///
262    /// SCRFD outputs 9 tensors. We classify them by their last dimension:
263    ///   - dim=1 → scores
264    ///   - dim=4 → bounding boxes (anchor-distance format)
265    ///   - dim=10 → landmarks (5 keypoints * 2 coords)
266    ///
267    /// Within each type, they are ordered by descending anchor count (stride 8, 16, 32).
268    fn group_outputs(&self, outputs: &[(Vec<i64>, Vec<f32>)]) -> Vec<StrideOutput> {
269        let strides = [8u32, 16, 32];
270
271        let mut score_tensors: Vec<(usize, &Vec<f32>)> = Vec::new();
272        let mut bbox_tensors: Vec<(usize, &Vec<f32>)> = Vec::new();
273        let mut lmk_tensors: Vec<(usize, &Vec<f32>)> = Vec::new();
274
275        for (shape, data) in outputs {
276            let last_dim = *shape.last().unwrap_or(&0);
277            let num_anchors = if shape.len() >= 2 {
278                shape[shape.len() - 2] as usize
279            } else {
280                data.len() / last_dim as usize
281            };
282
283            match last_dim {
284                1 => score_tensors.push((num_anchors, data)),
285                4 => bbox_tensors.push((num_anchors, data)),
286                10 => lmk_tensors.push((num_anchors, data)),
287                _ => {
288                    tracing::debug!("Unknown output tensor shape: {:?}", shape);
289                }
290            }
291        }
292
293        // Sort each group by descending anchor count (stride 8 has most anchors)
294        score_tensors.sort_by_key(|x| std::cmp::Reverse(x.0));
295        bbox_tensors.sort_by_key(|x| std::cmp::Reverse(x.0));
296        lmk_tensors.sort_by_key(|x| std::cmp::Reverse(x.0));
297
298        let mut stride_outputs = Vec::new();
299
300        for i in 0..strides
301            .len()
302            .min(score_tensors.len())
303            .min(bbox_tensors.len())
304        {
305            let num_anchors = score_tensors[i].0;
306            let has_landmarks = i < lmk_tensors.len();
307
308            stride_outputs.push(StrideOutput {
309                scores: score_tensors[i].1.clone(),
310                bboxes: bbox_tensors[i].1.clone(),
311                landmarks: if has_landmarks {
312                    lmk_tensors[i].1.clone()
313                } else {
314                    vec![0.0; num_anchors * 10]
315                },
316                num_anchors,
317                stride: strides[i],
318            });
319        }
320
321        stride_outputs
322    }
323
324    /// Post-process SCRFD outputs to DetectedFace structs
325    ///
326    /// SCRFD uses anchor-based detection across 3 stride levels.
327    /// Each anchor center is at (col * stride + stride/2, row * stride + stride/2).
328    /// BBox outputs are distances from anchor center: (left, top, right, bottom).
329    /// Landmark outputs are (dx, dy) offsets from anchor center for each keypoint.
330    fn postprocess(
331        &self,
332        outputs: &[(Vec<i64>, Vec<f32>)],
333        orig_width: u32,
334        orig_height: u32,
335    ) -> Vec<DetectedFace> {
336        let mut faces = Vec::new();
337
338        if outputs.len() < 6 {
339            tracing::warn!(
340                "SCRFD: Expected at least 6 output tensors, got {}",
341                outputs.len()
342            );
343            return faces;
344        }
345
346        let stride_outputs = self.group_outputs(outputs);
347
348        let (input_w, input_h) = self.input_size;
349        let scale_x = orig_width as f32 / input_w as f32;
350        let scale_y = orig_height as f32 / input_h as f32;
351
352        for so in &stride_outputs {
353            let stride = so.stride as f32;
354            let grid_w = input_w as f32 / stride;
355            let grid_h = input_h as f32 / stride;
356            let grid_cols = grid_w as usize;
357            let grid_rows = grid_h as usize;
358            let anchors_per_cell = so.num_anchors / (grid_cols * grid_rows).max(1);
359
360            for row in 0..grid_rows {
361                for col in 0..grid_cols {
362                    for a in 0..anchors_per_cell {
363                        let idx = (row * grid_cols + col) * anchors_per_cell + a;
364                        if idx >= so.num_anchors {
365                            continue;
366                        }
367
368                        // Score — SCRFD already applies sigmoid internally,
369                        // so raw output is in [0, 1] range.
370                        let score = so.scores[idx];
371
372                        if score < self.confidence_threshold {
373                            continue;
374                        }
375
376                        // Anchor center in input image coords
377                        let cx = (col as f32 + 0.5) * stride;
378                        let cy = (row as f32 + 0.5) * stride;
379
380                        // Decode bounding box (distances from anchor center)
381                        let bbox_base = idx * 4;
382                        if bbox_base + 3 >= so.bboxes.len() {
383                            continue;
384                        }
385                        let dl = so.bboxes[bbox_base] * stride;
386                        let dt = so.bboxes[bbox_base + 1] * stride;
387                        let dr = so.bboxes[bbox_base + 2] * stride;
388                        let db = so.bboxes[bbox_base + 3] * stride;
389
390                        let x1 = (cx - dl) * scale_x;
391                        let y1 = (cy - dt) * scale_y;
392                        let x2 = (cx + dr) * scale_x;
393                        let y2 = (cy + db) * scale_y;
394
395                        // Clamp to image bounds
396                        let x1 = x1.max(0.0).min(orig_width as f32);
397                        let y1 = y1.max(0.0).min(orig_height as f32);
398                        let x2 = x2.max(0.0).min(orig_width as f32);
399                        let y2 = y2.max(0.0).min(orig_height as f32);
400
401                        let width = x2 - x1;
402                        let height = y2 - y1;
403
404                        if width < 10.0 || height < 10.0 {
405                            continue;
406                        }
407
408                        // Decode landmarks
409                        let lm_base = idx * 10;
410                        let mut lmks = [(0.0f32, 0.0f32); 5];
411                        if lm_base + 9 < so.landmarks.len() {
412                            for (j, lmk) in lmks.iter_mut().enumerate() {
413                                *lmk = (
414                                    (cx + so.landmarks[lm_base + j * 2] * stride) * scale_x,
415                                    (cy + so.landmarks[lm_base + j * 2 + 1] * stride) * scale_y,
416                                );
417                            }
418                        }
419
420                        faces.push(DetectedFace {
421                            bbox: (x1, y1, width, height),
422                            bbox_normalized: (
423                                x1 / orig_width as f32,
424                                y1 / orig_height as f32,
425                                width / orig_width as f32,
426                                height / orig_height as f32,
427                            ),
428                            confidence: score,
429                            landmarks: lmks,
430                            aligned_face: None,
431                        });
432                    }
433                }
434            }
435        }
436
437        tracing::debug!(
438            "SCRFD raw detections: {} (before NMS, threshold={})",
439            faces.len(),
440            self.confidence_threshold
441        );
442
443        faces
444    }
445
446    /// Non-maximum suppression to remove overlapping detections
447    fn non_max_suppression(&self, mut faces: Vec<DetectedFace>) -> Vec<DetectedFace> {
448        if faces.is_empty() {
449            return faces;
450        }
451
452        // Sort by confidence (descending)
453        faces.sort_by(|a, b| {
454            b.confidence
455                .partial_cmp(&a.confidence)
456                .unwrap_or(std::cmp::Ordering::Equal)
457        });
458
459        let mut keep = vec![true; faces.len()];
460
461        for i in 0..faces.len() {
462            if !keep[i] {
463                continue;
464            }
465
466            for j in (i + 1)..faces.len() {
467                if !keep[j] {
468                    continue;
469                }
470
471                let iou = self.calculate_iou(&faces[i].bbox, &faces[j].bbox);
472                if iou > self.nms_threshold {
473                    keep[j] = false;
474                }
475            }
476        }
477
478        faces
479            .into_iter()
480            .enumerate()
481            .filter(|(i, _)| keep[*i])
482            .map(|(_, f)| f)
483            .collect()
484    }
485
486    /// Calculate Intersection over Union for two bounding boxes
487    /// Each box is (x, y, width, height)
488    fn calculate_iou(&self, box1: &(f32, f32, f32, f32), box2: &(f32, f32, f32, f32)) -> f32 {
489        let (x1, y1, w1, h1) = *box1;
490        let (x2, y2, w2, h2) = *box2;
491
492        let xi1 = x1.max(x2);
493        let yi1 = y1.max(y2);
494        let xi2 = (x1 + w1).min(x2 + w2);
495        let yi2 = (y1 + h1).min(y2 + h2);
496
497        let inter_width = (xi2 - xi1).max(0.0);
498        let inter_height = (yi2 - yi1).max(0.0);
499        let inter_area = inter_width * inter_height;
500
501        let area1 = w1 * h1;
502        let area2 = w2 * h2;
503        let union_area = area1 + area2 - inter_area;
504
505        if union_area > 0.0 {
506            inter_area / union_area
507        } else {
508            0.0
509        }
510    }
511
512    /// Align face using all 5 landmarks via similarity transform onto the
513    /// canonical InsightFace 112x112 template. Falls back to eye-center crop
514    /// if the landmarks are degenerate (rare).
515    fn align_face(&self, image: &DynamicImage, landmarks: &[(f32, f32); 5]) -> RgbImage {
516        if let Some(aligned) = super::alignment::align_face_112(image, landmarks) {
517            return aligned;
518        }
519
520        // Degenerate landmarks: fall back to the old eye-center crop.
521        let left_eye = landmarks[0];
522        let right_eye = landmarks[1];
523        let eye_center = (
524            (left_eye.0 + right_eye.0) / 2.0,
525            (left_eye.1 + right_eye.1) / 2.0,
526        );
527        let eye_dist =
528            ((right_eye.0 - left_eye.0).powi(2) + (right_eye.1 - left_eye.1).powi(2)).sqrt();
529        let face_size = (eye_dist * 2.5).max(10.0);
530
531        let img_w = image.width();
532        let img_h = image.height();
533        let x = (eye_center.0 - face_size / 2.0).max(0.0) as u32;
534        let y = (eye_center.1 - face_size / 2.0).max(0.0) as u32;
535        let x = x.min(img_w.saturating_sub(1));
536        let y = y.min(img_h.saturating_sub(1));
537        let crop_w = (face_size as u32).min(img_w.saturating_sub(x)).max(1);
538        let crop_h = (face_size as u32).min(img_h.saturating_sub(y)).max(1);
539
540        let cropped = image.crop_imm(x, y, crop_w, crop_h);
541        let resized = cropped.resize_exact(112, 112, image::imageops::FilterType::Lanczos3);
542        resized.to_rgb8()
543    }
544}
545
546/// Estimate yaw angle (degrees) from 5-point SCRFD landmarks.
547///
548/// Uses the nose offset from the eyes-midpoint, normalised by
549/// inter-ocular distance. Positive = right-facing, negative = left-facing.
550/// The absolute value indicates how far the face is turned from frontal.
551pub fn estimate_yaw_from_landmarks(landmarks: &[(f32, f32); 5]) -> f32 {
552    let left_eye = landmarks[0];
553    let right_eye = landmarks[1];
554    let nose = landmarks[2];
555
556    let eye_center_x = (left_eye.0 + right_eye.0) / 2.0;
557    let eye_center_y = (left_eye.1 + right_eye.1) / 2.0;
558    let iod = ((right_eye.0 - left_eye.0).powi(2) + (right_eye.1 - left_eye.1).powi(2)).sqrt();
559
560    if iod < 1.0 {
561        return 0.0; // degenerate landmarks
562    }
563
564    let nose_offset_x = nose.0 - eye_center_x;
565    let _nose_offset_y = nose.1 - eye_center_y;
566
567    // The yaw is roughly the horizontal offset normalised by IOD.
568    // A small vertical correction accounts for head tilt.
569    let yaw_rad = (nose_offset_x / iod).atan();
570    let yaw_deg = yaw_rad.to_degrees();
571
572    // Return absolute yaw for gating purposes.
573    yaw_deg.abs()
574}
575
576#[cfg(test)]
577mod tests {
578    /// Helper to create a FaceDetector-like struct for testing IoU
579    struct IouTester;
580
581    impl IouTester {
582        fn calculate_iou(box1: &(f32, f32, f32, f32), box2: &(f32, f32, f32, f32)) -> f32 {
583            let (x1, y1, w1, h1) = *box1;
584            let (x2, y2, w2, h2) = *box2;
585
586            let xi1 = x1.max(x2);
587            let yi1 = y1.max(y2);
588            let xi2 = (x1 + w1).min(x2 + w2);
589            let yi2 = (y1 + h1).min(y2 + h2);
590
591            let inter_width = (xi2 - xi1).max(0.0);
592            let inter_height = (yi2 - yi1).max(0.0);
593            let inter_area = inter_width * inter_height;
594
595            let area1 = w1 * h1;
596            let area2 = w2 * h2;
597            let union_area = area1 + area2 - inter_area;
598
599            if union_area > 0.0 {
600                inter_area / union_area
601            } else {
602                0.0
603            }
604        }
605    }
606
607    #[test]
608    fn test_iou_same_box() {
609        let box1 = (0.0, 0.0, 100.0, 100.0);
610        assert!((IouTester::calculate_iou(&box1, &box1) - 1.0).abs() < 0.001);
611    }
612
613    #[test]
614    fn test_iou_non_overlapping() {
615        let box1 = (0.0, 0.0, 100.0, 100.0);
616        let box2 = (200.0, 200.0, 100.0, 100.0);
617        assert!((IouTester::calculate_iou(&box1, &box2) - 0.0).abs() < 0.001);
618    }
619
620    #[test]
621    fn test_iou_partial_overlap() {
622        let box1 = (0.0, 0.0, 100.0, 100.0);
623        let box2 = (50.0, 50.0, 100.0, 100.0);
624        let iou = IouTester::calculate_iou(&box1, &box2);
625        // Intersection: 50x50 = 2500, Union: 10000 + 10000 - 2500 = 17500
626        assert!((iou - 2500.0 / 17500.0).abs() < 0.001);
627    }
628
629    #[test]
630    fn test_estimate_yaw_frontal() {
631        use super::estimate_yaw_from_landmarks;
632        // Frontal face: eyes level, nose centered
633        let lmks = [
634            (100.0, 100.0), // left eye
635            (200.0, 100.0), // right eye
636            (150.0, 150.0), // nose (centered)
637            (120.0, 200.0), // left mouth
638            (180.0, 200.0), // right mouth
639        ];
640        let yaw = estimate_yaw_from_landmarks(&lmks);
641        assert!(yaw < 5.0, "frontal face yaw={} should be <5", yaw);
642    }
643
644    #[test]
645    fn test_estimate_yaw_profile() {
646        use super::estimate_yaw_from_landmarks;
647        // Right-facing face: nose offset to the right
648        let lmks = [
649            (100.0, 100.0), // left eye
650            (200.0, 100.0), // right eye
651            (220.0, 140.0), // nose (right offset)
652            (120.0, 200.0), // left mouth
653            (180.0, 200.0), // right mouth
654        ];
655        let yaw = estimate_yaw_from_landmarks(&lmks);
656        assert!(yaw > 10.0, "profile face yaw={} should be >10", yaw);
657    }
658}