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

@@ -24,35 +24,38 @@ SHA-256: `db0898ae717b76b075d9bf563af315b29562e11f8df5027a1ef07b02bef6d81c`
# Capture face counting # Capture face counting
The bundled `haarcascade_frontalface_alt2.xml` and Faces are detected with OpenCV YuNet (`face_detection_yunet_2023mar.onnx`),
`haarcascade_eye_tree_eyeglasses.xml` are OpenCV Haar cascades from replacing the Haar face and eye cascades. The 228 KiB ONNX model is embedded in
https://github.com/opencv/opencv/tree/4.6.0/data/haarcascades. the executable, loaded once, and run with OpenCV DNN on CPU. OpenCV 4.8 or newer
Each XML includes its upstream license notice. They are embedded in the binary; with DNN and FaceDetectorYN buffer loading is required (tested with 4.10).
no model downloads or external model paths are needed at runtime.
Detection runs once per capture and at most twice per second for the live preview, Source: https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet
with the longest image edge capped at 640 px,
using a frontal-face cascade with an optional eye-pair check. When fewer than two
eyes are detected, the frontal-face result is accepted: missing eyes are not
reliable evidence of a side view. When two or more eyes are detected, a roughly
level, centered pair is required. Debug output includes the acceptance reason.
Faces below 40 px may be missed, and some turned faces may still pass the frontal
cascade. This is a best-effort side-view filter, not an exact gaze estimator. OpenCV is limited to
two threads. Validate counts and timings with representative group photos on the
kiosk before deployment; no accuracy or latency guarantee is implied.
The current capture is the clean mirrored 640×480 camera frame, before overlays. Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx
The app sends a JPEG to `lp -n COUNT -o fit-to-page` using the default CUPS printer
and its configured paper/media settings. Install the CUPS client (`lp`) and set
up the default printer on the kiosk. Zero accepted faces means no print job;
detection/printing errors are logged without stopping the preview or retrying a
possibly submitted job. Debug logs include candidate boxes, eye counts, rejected
faces, accepted face/copy count, detection duration and CUPS submission result.
Live preview rectangles show every frontal-face candidate: green (`#84bf65`) SHA-256: `8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4`
means accepted for printing; blue (`#4caee3`) means rejected by the eye-pair check.
Rectangles use mirrored camera coordinates and share the preview cover crop. License: MIT, reproduced in `YUNET_LICENSE`.
They are cached between samples and cleared by empty results or detection errors.
They never appear in detector inputs or the printed photo. Live sampling is quiet; Images retain their aspect ratio, with the longest edge resized to 320 px and
full per-face debug information is emitted for captures only. The preview is black padding to 320×320. Confidence threshold is 0.8, NMS threshold 0.3 and top K
sampled separately from capture, so counts can change with movement or lighting. 500. Predicted eye and nose landmarks filter strongly turned faces: the nose
projection must fall within the central 70% of the eye line, with eye separation
at least 23% of the face width. This tolerates roll and mirrored coordinates and
does not depend on a separate eye detector. It estimates frontal head orientation,
not eye gaze. Small, occluded or strongly tilted faces can still be missed;
validate group-photo accuracy and timings on the target kiosk.
The clean mirrored camera frame is counted once after capture. Debug logs retain
candidate boxes, confidence, accepted/rejected counts, intended copies and timing.
The count is passed to an intentionally empty `print_picture` hook. There is no
printer command, image encoding, file output or physical printing yet.
Face rectangles and live face inference are enabled only in debug builds
(`cargo run`); release builds (`cargo run --release`) have neither. The debug
worker samples at most twice per second, drops samples while busy, and expires
results after 1.5 seconds. Green (`#84bf65`) means accepted; blue (`#4caee3`) means
rejected for head orientation. Rectangles use mirrored camera coordinates and
share the preview crop, but never enter capture or detector input. Counts are
always recomputed on the captured frame and can differ from the last live sample.
OpenCV remains limited to two threads; actual kiosk latency needs measurement.

21
models/YUNET_LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Shiqi Yu <shiqi.yu@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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::{ use opencv::{
core::{self, Mat, Rect, Size, Vector}, core::{self, Mat, Point2f, Rect, Size, Vector},
imgproc, objdetect, dnn, imgproc, objdetect,
prelude::*, prelude::*,
}; };
use std::time::Instant; use std::time::Instant;
pub const PREVIEW_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
pub struct Face { pub struct Face {
#[cfg_attr(not(debug_assertions), allow(dead_code))]
pub bounds: Rect, pub bounds: Rect,
pub accepted: bool, pub accepted: bool,
} }
#[cfg(debug_assertions)]
/// BGR colors match the UI: green counts toward prints, blue is rejected. /// BGR colors match the UI: green counts toward prints, blue is rejected.
pub fn draw(frame: &mut Mat, faces: &[Face]) -> opencv::Result<()> { pub fn draw(frame: &mut Mat, faces: &[Face]) -> opencv::Result<()> {
let thickness = (frame.cols().min(frame.rows()) / 240).max(1); 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 { pub struct Detector {
faces: objdetect::CascadeClassifier, net: core::Ptr<objdetect::FaceDetectorYN>,
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)
} }
impl Detector { impl Detector {
pub fn new() -> opencv::Result<Self> { pub fn new() -> opencv::Result<Self> {
let bytes = Vector::from_slice(include_bytes!(
"../models/face_detection_yunet_2023mar.onnx"
));
Ok(Self { Ok(Self {
faces: cascade(include_str!("../models/haarcascade_frontalface_alt2.xml"))?, net: objdetect::FaceDetectorYN::create_1(
eyes: cascade(include_str!( "onnx",
"../models/haarcascade_eye_tree_eyeglasses.xml" &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>> { pub fn detect(&mut self, frame: &Mat, debug: bool) -> opencv::Result<Vec<Face>> {
let start = Instant::now(); let start = Instant::now();
let mut small = Mat::default(); if frame.empty() {
let scale = (640.0 / frame.cols().max(frame.rows()) as f64).min(1.0); 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( imgproc::resize(
frame, frame,
&mut small, &mut resized,
Size::default(), Size::new(width, height),
scale, 0.0,
scale, 0.0,
imgproc::INTER_AREA, imgproc::INTER_LINEAR,
)?; )?;
let mut gray = Mat::default(); let mut padded = Mat::default();
imgproc::cvt_color_def(&small, &mut gray, imgproc::COLOR_BGR2GRAY)?; core::copy_make_border(
let mut equalized = Mat::default(); &resized,
imgproc::equalize_hist(&gray, &mut equalized)?; &mut padded,
let mut faces = Vector::<Rect>::new();
self.faces.detect_multi_scale(
&equalized,
&mut faces,
1.15,
4,
0, 0,
Size::new(40, 40), 320 - height,
Size::default(), 0,
320 - width,
core::BORDER_CONSTANT,
core::Scalar::all(0.0),
)?; )?;
let mut count = 0; let mut rows = Mat::default();
let mut detections = Vec::with_capacity(faces.len()); self.net.detect(&padded, &mut rows)?;
for face in faces.iter() { let mut faces = Vec::new();
let upper = Mat::roi( for row in 0..rows.rows() {
&equalized, let value = |col| rows.at_2d::<f32>(row, col).copied();
Rect::new(face.x, face.y, face.width, face.height * 3 / 5), let x = value(0)?;
)?; let y = value(1)?;
let mut eyes = Vector::<Rect>::new(); let w = value(2)?;
self.eyes.detect_multi_scale( let h = value(3)?;
&upper, let eye_a = Point2f::new(value(4)?, value(5)?);
&mut eyes, let eye_b = Point2f::new(value(6)?, value(7)?);
1.1, let nose = Point2f::new(value(8)?, value(9)?);
3, let accepted = facing_camera(eye_a, eye_b, nose, w);
0, let bounds = map_bounds(x, y, w, h, Size::new(width, height), frame.size()?);
Size::new((face.width / 10).max(6), (face.height / 10).max(6)), if bounds.width <= 0 || bounds.height <= 0 {
Size::new(face.width / 2, face.height / 3), continue;
)?; }
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,
});
if debug { if debug {
eprintln!( eprintln!(
"[capture DEBUG] face={face:?} eyes={} facing_camera={accepted} reason={reason}", "[capture DEBUG] detector=yunet face={bounds:?} confidence={:.3} facing_camera={accepted}",
eyes.len() value(14)?
); );
} }
faces.push(Face { bounds, accepted });
} }
if debug { if debug {
let count = faces.iter().filter(|face| face.accepted).count();
eprintln!( 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(),
faces.len() - count, faces.len() - count,
start.elapsed().as_millis(), start.elapsed().as_millis()
equalized.cols(),
equalized.rows()
); );
} }
Ok(detections) Ok(faces)
} }
} }
// Missing eyes are inconclusive: glasses, reflections and closed eyes can all fn map_bounds(x: f32, y: f32, w: f32, h: f32, input: Size, output: Size) -> Rect {
// defeat the eye cascade on an otherwise valid frontal-face detection. let sx = output.width as f32 / input.width as f32;
fn acceptance_reason(eyes: &[Rect], width: i32) -> &'static str { let sy = output.height as f32 / input.height as f32;
if eyes.len() < 2 { let left = (x * sx).floor().clamp(0.0, output.width as f32) as i32;
"frontal_face_eye_check_inconclusive" let top = (y * sy).floor().clamp(0.0, output.height as f32) as i32;
} else if frontal_eye_pair(eyes, width) { let right = ((x + w) * sx).ceil().clamp(0.0, output.width as f32) as i32;
"frontal_face_and_eye_pair" let bottom = ((y + h) * sy).ceil().clamp(0.0, output.height as f32) as i32;
} else { Rect::new(left, top, (right - left).max(0), (bottom - top).max(0))
"unbalanced_eye_pair"
}
} }
// Two separated, roughly level eyes on opposite sides of the face. This is a // Project the nose onto the eye line: rotation and selfie mirroring do not
// conservative frontal-view heuristic, not a gaze or head-pose estimator. // change the test. Reject strongly offset noses and compressed eye separation.
fn frontal_eye_pair(eyes: &[Rect], width: i32) -> bool { // This estimates frontal head orientation, not where a person's eyes are looking.
eyes.iter().any(|left| { fn facing_camera(a: Point2f, b: Point2f, nose: Point2f, width: f32) -> bool {
eyes.iter().any(|right| { let dx = b.x - a.x;
let lx = left.x + left.width / 2; let dy = b.y - a.y;
let rx = right.x + right.width / 2; let distance_sq = dx * dx + dy * dy;
let ly = left.y + left.height / 2; let nose_position = ((nose.x - a.x) * dx + (nose.y - a.y) * dy) / distance_sq;
let ry = right.y + right.height / 2; width.is_finite()
lx < width / 2 && width > 0.0
&& rx > width / 2 && distance_sq.is_finite()
&& rx - lx >= width / 4 && distance_sq.sqrt() >= width * 0.23
&& rx - lx <= width * 7 / 10 && (0.15..=0.85).contains(&nose_position)
&& (ly - ry).abs() <= width / 8 }
&& (lx + rx - width).abs() <= width / 5
#[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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[cfg(debug_assertions)]
#[test] #[test]
fn overlay_draws_all_candidates_in_status_colors_without_filling_faces() -> opencv::Result<()> { fn overlay_draws_all_candidates_in_status_colors_without_filling_faces() -> opencv::Result<()> {
let mut frame = let mut frame =
@@ -201,37 +253,35 @@ mod tests {
} }
#[test] #[test]
fn missing_eyes_do_not_discard_frontal_faces() { fn head_orientation_tolerates_roll_and_mirroring_but_rejects_profiles() {
assert_eq!( let a = Point2f::new(20.0, 30.0);
acceptance_reason(&[], 164), let b = Point2f::new(70.0, 40.0);
"frontal_face_eye_check_inconclusive" let nose = Point2f::new(42.0, 60.0);
); assert!(facing_camera(a, b, nose, 100.0));
assert_eq!( assert!(facing_camera(b, a, nose, 100.0));
acceptance_reason(&[Rect::new(20, 22, 16, 12)], 100), assert!(!facing_camera(a, b, Point2f::new(75.0, 50.0), 100.0));
"frontal_face_eye_check_inconclusive" assert!(!facing_camera(a, Point2f::new(30.0, 30.0), nose, 100.0));
); assert!(!facing_camera(a, a, nose, 100.0));
assert_eq!( assert!(!facing_camera(a, b, Point2f::new(f32::NAN, 50.0), 100.0));
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"
);
} }
#[test] #[test]
fn rejects_profile_duplicates_and_unbalanced_eyes() { fn bounds_scale_back_to_selfie_frame_and_clip_padding() {
let eye = |x, y| Rect::new(x, y, 16, 12); let input = Size::new(320, 240);
assert!(frontal_eye_pair(&[eye(20, 22), eye(64, 24)], 100)); let output = Size::new(640, 480);
assert!(!frontal_eye_pair(&[], 100)); assert_eq!(
assert!(!frontal_eye_pair(&[eye(20, 22)], 100)); map_bounds(150.0, 50.0, 80.0, 90.0, input, output),
assert!(!frontal_eye_pair(&[eye(20, 22), eye(23, 22)], 100)); Rect::new(300, 100, 160, 180)
assert!(!frontal_eye_pair(&[eye(20, 22), eye(64, 40)], 100)); );
assert!(!frontal_eye_pair(&[eye(0, 22), eye(45, 22)], 100)); 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] #[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 mut detector = Detector::new()?;
let frame = let frame =
Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, core::Scalar::all(128.0))?; 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 detector = palm::Detector::new()?;
let mut face_detector = faces::Detector::new()?; let mut face_detector = faces::Detector::new()?;
#[cfg(debug_assertions)]
let mut live_faces = faces::LivePreview::new()?;
let ui = AppWindow::new()?; let ui = AppWindow::new()?;
ui.window() ui.window()
@@ -104,8 +106,6 @@ fn main() -> Result<(), Box<dyn Error>> {
); );
let mut sequence = capture::Sequence::default(); let mut sequence = capture::Sequence::default();
let mut last_detection = Instant::now() - palm::DETECTION_INTERVAL; 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) { while worker_running.load(Ordering::Relaxed) {
if !camera_log.run(|| cam.read(&mut frame))? || frame.empty() { if !camera_log.run(|| cam.read(&mut frame))? || frame.empty() {
eprintln!("Camera stopped providing frames"); eprintln!("Camera stopped providing frames");
@@ -119,26 +119,16 @@ fn main() -> Result<(), Box<dyn Error>> {
let _ = detection_tx.try_send(frame.try_clone()?); let _ = detection_tx.try_send(frame.try_clone()?);
last_detection = now; last_detection = now;
} }
// Run face analysis at most twice per second on the clean selfie frame. #[cfg(debug_assertions)]
// Cache rectangles between samples; replace them even on empty results. live_faces.sample(&frame)?;
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();
}
let mut tracker_guard = tracker.lock().unwrap(); let mut tracker_guard = tracker.lock().unwrap();
let hand_detected = tracker_guard.has_palm(now); let hand_detected = tracker_guard.has_palm(now);
let take_picture = sequence.tick(tracker_guard.complete(now), hand_detected, now); let take_picture = sequence.tick(tracker_guard.complete(now), hand_detected, now);
if take_picture { 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); drop(tracker_guard);
if let Err(error) = capture::take_picture(&frame, &mut face_detector) { 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(); tracker_guard = tracker.lock().unwrap();
} }
@@ -148,7 +138,8 @@ fn main() -> Result<(), Box<dyn Error>> {
drop(tracker_guard); drop(tracker_guard);
// Draw only after capture and palm sampling so printed photos and // Draw only after capture and palm sampling so printed photos and
// detector inputs never contain debug rectangles. // detector inputs never contain debug rectangles.
faces::draw(&mut frame, &live_faces)?; #[cfg(debug_assertions)]
live_faces.draw(&mut frame)?;
let preview = PreviewFrame { let preview = PreviewFrame {
buffer: frame_to_buffer(&frame)?, buffer: frame_to_buffer(&frame)?,
hand_detected, hand_detected,