//! Lightweight YuNet detection, shared by capture and debug-only live preview. use opencv::{ core::{self, Mat, Point2f, Rect, Size, Vector}, dnn, imgproc, objdetect, prelude::*, }; use std::time::Instant; pub struct Face { #[cfg_attr(not(debug_assertions), allow(dead_code))] pub bounds: Rect, pub accepted: bool, } #[cfg(debug_assertions)] /// BGR colors match the UI: green counts toward prints, blue is rejected. pub fn draw(frame: &mut Mat, faces: &[Face]) -> opencv::Result<()> { let thickness = (frame.cols().min(frame.rows()) / 240).max(1); for face in faces { let color = if face.accepted { core::Scalar::new(101.0, 191.0, 132.0, 0.0) } else { core::Scalar::new(227.0, 174.0, 76.0, 0.0) }; imgproc::rectangle(frame, face.bounds, color, thickness, imgproc::LINE_8, 0)?; } Ok(()) } pub struct Detector { net: core::Ptr, } impl Detector { pub fn new() -> opencv::Result { let bytes = Vector::from_slice(include_bytes!( "../models/face_detection_yunet_2023mar.onnx" )); Ok(Self { net: objdetect::FaceDetectorYN::create_1( "onnx", &bytes, &Vector::new(), Size::new(320, 320), 0.8, 0.3, 500, dnn::DNN_BACKEND_OPENCV, dnn::DNN_TARGET_CPU, )?, }) } pub fn count(&mut self, frame: &Mat) -> opencv::Result { Ok(self .detect(frame, true)? .iter() .filter(|face| face.accepted) .count()) } pub fn detect(&mut self, frame: &Mat, debug: bool) -> opencv::Result> { let start = Instant::now(); if frame.empty() { return Err(opencv::Error::new( core::StsBadArg, "Empty face detection image", )); } // Aspect-preserving resize and padding keep inference at 320x320. let scale = 320.0 / frame.cols().max(frame.rows()) as f64; let width = (frame.cols() as f64 * scale).round() as i32; let height = (frame.rows() as f64 * scale).round() as i32; let mut resized = Mat::default(); imgproc::resize( frame, &mut resized, Size::new(width, height), 0.0, 0.0, imgproc::INTER_LINEAR, )?; let mut padded = Mat::default(); core::copy_make_border( &resized, &mut padded, 0, 320 - height, 0, 320 - width, core::BORDER_CONSTANT, core::Scalar::all(0.0), )?; let mut rows = Mat::default(); self.net.detect(&padded, &mut rows)?; let mut faces = Vec::new(); for row in 0..rows.rows() { let value = |col| rows.at_2d::(row, col).copied(); let x = value(0)?; let y = value(1)?; let w = value(2)?; let h = value(3)?; let eye_a = Point2f::new(value(4)?, value(5)?); let eye_b = Point2f::new(value(6)?, value(7)?); let nose = Point2f::new(value(8)?, value(9)?); let accepted = facing_camera(eye_a, eye_b, nose, w); let bounds = map_bounds(x, y, w, h, Size::new(width, height), frame.size()?); if bounds.width <= 0 || bounds.height <= 0 { continue; } if debug { eprintln!( "[capture DEBUG] detector=yunet face={bounds:?} confidence={:.3} facing_camera={accepted}", value(14)? ); } faces.push(Face { bounds, accepted }); } if debug { let count = faces.iter().filter(|face| face.accepted).count(); eprintln!( "[capture DEBUG] detector=yunet candidates={} faces={count} rejected={} copies={count} detection_ms={} analysis=320x320", faces.len(), faces.len() - count, start.elapsed().as_millis() ); } Ok(faces) } } fn map_bounds(x: f32, y: f32, w: f32, h: f32, input: Size, output: Size) -> Rect { let sx = output.width as f32 / input.width as f32; let sy = output.height as f32 / input.height as f32; let left = (x * sx).floor().clamp(0.0, output.width as f32) as i32; let top = (y * sy).floor().clamp(0.0, output.height as f32) as i32; let right = ((x + w) * sx).ceil().clamp(0.0, output.width as f32) as i32; let bottom = ((y + h) * sy).ceil().clamp(0.0, output.height as f32) as i32; Rect::new(left, top, (right - left).max(0), (bottom - top).max(0)) } // Project the nose onto the eye line: rotation and selfie mirroring do not // change the test. Reject strongly offset noses and compressed eye separation. // This estimates frontal head orientation, not where a person's eyes are looking. fn facing_camera(a: Point2f, b: Point2f, nose: Point2f, width: f32) -> bool { let dx = b.x - a.x; let dy = b.y - a.y; let distance_sq = dx * dx + dy * dy; let nose_position = ((nose.x - a.x) * dx + (nose.y - a.y) * dy) / distance_sq; width.is_finite() && width > 0.0 && distance_sq.is_finite() && distance_sq.sqrt() >= width * 0.23 && (0.15..=0.85).contains(&nose_position) } #[cfg(debug_assertions)] pub struct LivePreview { sender: Option>, result: std::sync::Arc)>>, worker: Option>, last_sample: Instant, } #[cfg(debug_assertions)] impl LivePreview { pub fn new() -> opencv::Result { use std::sync::{Arc, Mutex, mpsc}; let (sender, receiver) = mpsc::sync_channel::(0); let result = Arc::new(Mutex::new((Instant::now(), Vec::new()))); let worker_result = Arc::clone(&result); let worker = std::thread::spawn(move || { let mut detector = match Detector::new() { Ok(detector) => detector, Err(error) => { eprintln!("[faces ERROR] Could not load debug face model: {error}"); return; } }; while let Ok(frame) = receiver.recv() { let started = Instant::now(); let faces = detector.detect(&frame, false).unwrap_or_else(|error| { eprintln!("[faces ERROR] Live detection failed: {error}"); Vec::new() }); *worker_result.lock().unwrap() = (started, faces); } }); Ok(Self { sender: Some(sender), result, worker: Some(worker), last_sample: Instant::now() - std::time::Duration::from_millis(500), }) } pub fn sample(&mut self, frame: &Mat) -> opencv::Result<()> { if self.last_sample.elapsed() >= std::time::Duration::from_millis(500) { // Drop samples while inference is busy: no backlog on the old kiosk CPU. let _ = self.sender.as_ref().unwrap().try_send(frame.try_clone()?); self.last_sample = Instant::now(); } Ok(()) } pub fn draw(&self, frame: &mut Mat) -> opencv::Result<()> { let result = self.result.lock().unwrap(); if result.0.elapsed() < std::time::Duration::from_millis(1500) { draw(frame, &result.1)?; } Ok(()) } } #[cfg(debug_assertions)] impl Drop for LivePreview { fn drop(&mut self) { self.sender.take(); if self.worker.take().unwrap().join().is_err() { eprintln!("[faces ERROR] Live detection worker panicked"); } } } #[cfg(test)] mod tests { use super::*; #[cfg(debug_assertions)] #[test] fn overlay_draws_all_candidates_in_status_colors_without_filling_faces() -> opencv::Result<()> { let mut frame = Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, core::Scalar::all(0.0))?; draw( &mut frame, &[ Face { bounds: Rect::new(50, 60, 100, 100), accepted: true, }, Face { bounds: Rect::new(200, 60, 100, 100), accepted: false, }, ], )?; assert_eq!( *frame.at_2d::(60, 50)?, core::Vec3b::from([101, 191, 132]) ); assert_eq!( *frame.at_2d::(60, 200)?, core::Vec3b::from([227, 174, 76]) ); assert_eq!( *frame.at_2d::(100, 100)?, core::Vec3b::from([0, 0, 0]) ); Ok(()) } #[test] fn head_orientation_tolerates_roll_and_mirroring_but_rejects_profiles() { let a = Point2f::new(20.0, 30.0); let b = Point2f::new(70.0, 40.0); let nose = Point2f::new(42.0, 60.0); assert!(facing_camera(a, b, nose, 100.0)); assert!(facing_camera(b, a, nose, 100.0)); assert!(!facing_camera(a, b, Point2f::new(75.0, 50.0), 100.0)); assert!(!facing_camera(a, Point2f::new(30.0, 30.0), nose, 100.0)); assert!(!facing_camera(a, a, nose, 100.0)); assert!(!facing_camera(a, b, Point2f::new(f32::NAN, 50.0), 100.0)); } #[test] fn bounds_scale_back_to_selfie_frame_and_clip_padding() { let input = Size::new(320, 240); let output = Size::new(640, 480); assert_eq!( map_bounds(150.0, 50.0, 80.0, 90.0, input, output), Rect::new(300, 100, 160, 180) ); assert_eq!( map_bounds(-10.0, 220.0, 50.0, 60.0, input, output), Rect::new(0, 440, 80, 40) ); assert_eq!(map_bounds(20.0, 250.0, 50.0, 40.0, input, output).height, 0); } #[test] fn bundled_yunet_runs_on_blank_capture() -> opencv::Result<()> { let mut detector = Detector::new()?; let frame = Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, core::Scalar::all(128.0))?; assert_eq!(detector.count(&frame)?, 0); Ok(()) } }