feat: use YuNet face detection with debug-only live boxes

This commit is contained in:
2026-11-10 15:03:18 +01:00
parent 9cf760e7a6
commit 838becdd70
7 changed files with 237 additions and 43510 deletions

View File

@@ -1,18 +1,18 @@
//! CPU face detection shared by capture counting and a throttled live overlay.
//! Lightweight YuNet detection, shared by capture and debug-only live preview.
use opencv::{
core::{self, Mat, Rect, Size, Vector},
imgproc, objdetect,
core::{self, Mat, Point2f, Rect, Size, Vector},
dnn, imgproc, objdetect,
prelude::*,
};
use std::time::Instant;
pub const PREVIEW_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
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);
@@ -28,24 +28,26 @@ pub fn draw(frame: &mut Mat, faces: &[Face]) -> opencv::Result<()> {
}
pub struct Detector {
faces: objdetect::CascadeClassifier,
eyes: objdetect::CascadeClassifier,
}
fn cascade(xml: &str) -> opencv::Result<objdetect::CascadeClassifier> {
let storage = core::FileStorage::new(xml, core::FileStorage_MEMORY, "")?;
let mut classifier = objdetect::CascadeClassifier::default()?;
classifier.read(&storage.get_first_top_level_node()?)?;
Ok(classifier)
net: core::Ptr<objdetect::FaceDetectorYN>,
}
impl Detector {
pub fn new() -> opencv::Result<Self> {
let bytes = Vector::from_slice(include_bytes!(
"../models/face_detection_yunet_2023mar.onnx"
));
Ok(Self {
faces: cascade(include_str!("../models/haarcascade_frontalface_alt2.xml"))?,
eyes: cascade(include_str!(
"../models/haarcascade_eye_tree_eyeglasses.xml"
))?,
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,
)?,
})
}
@@ -59,115 +61,165 @@ impl Detector {
pub fn detect(&mut self, frame: &Mat, debug: bool) -> opencv::Result<Vec<Face>> {
let start = Instant::now();
let mut small = Mat::default();
let scale = (640.0 / frame.cols().max(frame.rows()) as f64).min(1.0);
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 small,
Size::default(),
scale,
scale,
imgproc::INTER_AREA,
&mut resized,
Size::new(width, height),
0.0,
0.0,
imgproc::INTER_LINEAR,
)?;
let mut gray = Mat::default();
imgproc::cvt_color_def(&small, &mut gray, imgproc::COLOR_BGR2GRAY)?;
let mut equalized = Mat::default();
imgproc::equalize_hist(&gray, &mut equalized)?;
let mut faces = Vector::<Rect>::new();
self.faces.detect_multi_scale(
&equalized,
&mut faces,
1.15,
4,
let mut padded = Mat::default();
core::copy_make_border(
&resized,
&mut padded,
0,
Size::new(40, 40),
Size::default(),
320 - height,
0,
320 - width,
core::BORDER_CONSTANT,
core::Scalar::all(0.0),
)?;
let mut count = 0;
let mut detections = Vec::with_capacity(faces.len());
for face in faces.iter() {
let upper = Mat::roi(
&equalized,
Rect::new(face.x, face.y, face.width, face.height * 3 / 5),
)?;
let mut eyes = Vector::<Rect>::new();
self.eyes.detect_multi_scale(
&upper,
&mut eyes,
1.1,
3,
0,
Size::new((face.width / 10).max(6), (face.height / 10).max(6)),
Size::new(face.width / 2, face.height / 3),
)?;
let eye_boxes = eyes.to_vec();
let reason = acceptance_reason(&eye_boxes, face.width);
let accepted = reason != "unbalanced_eye_pair";
count += usize::from(accepted);
detections.push(Face {
bounds: Rect::new(
face.x * frame.cols() / equalized.cols(),
face.y * frame.rows() / equalized.rows(),
face.width * frame.cols() / equalized.cols(),
face.height * frame.rows() / equalized.rows(),
),
accepted,
});
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::<f32>(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] face={face:?} eyes={} facing_camera={accepted} reason={reason}",
eyes.len()
"[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] candidates={} faces={count} rejected={} copies={count} detection_ms={} analysis={}x{}",
"[capture DEBUG] detector=yunet candidates={} faces={count} rejected={} copies={count} detection_ms={} analysis=320x320",
faces.len(),
faces.len() - count,
start.elapsed().as_millis(),
equalized.cols(),
equalized.rows()
start.elapsed().as_millis()
);
}
Ok(detections)
Ok(faces)
}
}
// Missing eyes are inconclusive: glasses, reflections and closed eyes can all
// defeat the eye cascade on an otherwise valid frontal-face detection.
fn acceptance_reason(eyes: &[Rect], width: i32) -> &'static str {
if eyes.len() < 2 {
"frontal_face_eye_check_inconclusive"
} else if frontal_eye_pair(eyes, width) {
"frontal_face_and_eye_pair"
} else {
"unbalanced_eye_pair"
}
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))
}
// Two separated, roughly level eyes on opposite sides of the face. This is a
// conservative frontal-view heuristic, not a gaze or head-pose estimator.
fn frontal_eye_pair(eyes: &[Rect], width: i32) -> bool {
eyes.iter().any(|left| {
eyes.iter().any(|right| {
let lx = left.x + left.width / 2;
let rx = right.x + right.width / 2;
let ly = left.y + left.height / 2;
let ry = right.y + right.height / 2;
lx < width / 2
&& rx > width / 2
&& rx - lx >= width / 4
&& rx - lx <= width * 7 / 10
&& (ly - ry).abs() <= width / 8
&& (lx + rx - width).abs() <= width / 5
// 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<std::sync::mpsc::SyncSender<Mat>>,
result: std::sync::Arc<std::sync::Mutex<(Instant, Vec<Face>)>>,
worker: Option<std::thread::JoinHandle<()>>,
last_sample: Instant,
}
#[cfg(debug_assertions)]
impl LivePreview {
pub fn new() -> opencv::Result<Self> {
use std::sync::{Arc, Mutex, mpsc};
let mut detector = Detector::new()?;
let (sender, receiver) = mpsc::sync_channel::<Mat>(0);
let result = Arc::new(Mutex::new((Instant::now(), Vec::new())));
let worker_result = Arc::clone(&result);
let worker = std::thread::spawn(move || {
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 =
@@ -201,37 +253,35 @@ mod tests {
}
#[test]
fn missing_eyes_do_not_discard_frontal_faces() {
assert_eq!(
acceptance_reason(&[], 164),
"frontal_face_eye_check_inconclusive"
);
assert_eq!(
acceptance_reason(&[Rect::new(20, 22, 16, 12)], 100),
"frontal_face_eye_check_inconclusive"
);
assert_eq!(
acceptance_reason(&[Rect::new(20, 22, 16, 12), Rect::new(64, 24, 16, 12)], 100),
"frontal_face_and_eye_pair"
);
assert_eq!(
acceptance_reason(&[Rect::new(20, 22, 16, 12), Rect::new(64, 40, 16, 12)], 100),
"unbalanced_eye_pair"
);
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 rejects_profile_duplicates_and_unbalanced_eyes() {
let eye = |x, y| Rect::new(x, y, 16, 12);
assert!(frontal_eye_pair(&[eye(20, 22), eye(64, 24)], 100));
assert!(!frontal_eye_pair(&[], 100));
assert!(!frontal_eye_pair(&[eye(20, 22)], 100));
assert!(!frontal_eye_pair(&[eye(20, 22), eye(23, 22)], 100));
assert!(!frontal_eye_pair(&[eye(20, 22), eye(64, 40)], 100));
assert!(!frontal_eye_pair(&[eye(0, 22), eye(45, 22)], 100));
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_cascades_run_on_blank_capture() -> opencv::Result<()> {
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))?;

View File

@@ -48,6 +48,8 @@ fn main() -> Result<(), Box<dyn Error>> {
let mut detector = palm::Detector::new()?;
let mut face_detector = faces::Detector::new()?;
#[cfg(debug_assertions)]
let mut live_faces = faces::LivePreview::new()?;
let ui = AppWindow::new()?;
ui.window()
@@ -104,8 +106,6 @@ fn main() -> Result<(), Box<dyn Error>> {
);
let mut sequence = capture::Sequence::default();
let mut last_detection = Instant::now() - palm::DETECTION_INTERVAL;
let mut last_faces = Instant::now() - faces::PREVIEW_INTERVAL;
let mut live_faces = Vec::new();
while worker_running.load(Ordering::Relaxed) {
if !camera_log.run(|| cam.read(&mut frame))? || frame.empty() {
eprintln!("Camera stopped providing frames");
@@ -119,26 +119,16 @@ fn main() -> Result<(), Box<dyn Error>> {
let _ = detection_tx.try_send(frame.try_clone()?);
last_detection = now;
}
// Run face analysis at most twice per second on the clean selfie frame.
// Cache rectangles between samples; replace them even on empty results.
if now.duration_since(last_faces) >= faces::PREVIEW_INTERVAL {
live_faces = match face_detector.detect(&frame, false) {
Ok(faces) => faces,
Err(error) => {
eprintln!("[faces ERROR] Live detection failed: {error}");
Vec::new()
}
};
last_faces = Instant::now();
}
#[cfg(debug_assertions)]
live_faces.sample(&frame)?;
let mut tracker_guard = tracker.lock().unwrap();
let hand_detected = tracker_guard.has_palm(now);
let take_picture = sequence.tick(tracker_guard.complete(now), hand_detected, now);
if take_picture {
// Detection must not hold the palm tracker lock while processing or spooling.
// Release the palm tracker lock while analyzing the captured frame.
drop(tracker_guard);
if let Err(error) = capture::take_picture(&frame, &mut face_detector) {
eprintln!("[capture ERROR] Face counting / printing failed: {error}");
eprintln!("[capture ERROR] Face counting failed: {error}");
}
tracker_guard = tracker.lock().unwrap();
}
@@ -148,7 +138,8 @@ fn main() -> Result<(), Box<dyn Error>> {
drop(tracker_guard);
// Draw only after capture and palm sampling so printed photos and
// detector inputs never contain debug rectangles.
faces::draw(&mut frame, &live_faces)?;
#[cfg(debug_assertions)]
live_faces.draw(&mut frame)?;
let preview = PreviewFrame {
buffer: frame_to_buffer(&frame)?,
hand_detected,