feat: use YuNet face detection with debug-only live boxes
This commit is contained in:
@@ -24,35 +24,38 @@ SHA-256: `db0898ae717b76b075d9bf563af315b29562e11f8df5027a1ef07b02bef6d81c`
|
||||
|
||||
# Capture face counting
|
||||
|
||||
The bundled `haarcascade_frontalface_alt2.xml` and
|
||||
`haarcascade_eye_tree_eyeglasses.xml` are OpenCV Haar cascades from
|
||||
https://github.com/opencv/opencv/tree/4.6.0/data/haarcascades.
|
||||
Each XML includes its upstream license notice. They are embedded in the binary;
|
||||
no model downloads or external model paths are needed at runtime.
|
||||
Faces are detected with OpenCV YuNet (`face_detection_yunet_2023mar.onnx`),
|
||||
replacing the Haar face and eye cascades. The 228 KiB ONNX model is embedded in
|
||||
the executable, loaded once, and run with OpenCV DNN on CPU. OpenCV 4.8 or newer
|
||||
with DNN and FaceDetectorYN buffer loading is required (tested with 4.10).
|
||||
|
||||
Detection runs once per capture and at most twice per second for the live preview,
|
||||
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.
|
||||
Source: https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet
|
||||
|
||||
The current capture is the clean mirrored 640×480 camera frame, before overlays.
|
||||
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.
|
||||
Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx
|
||||
|
||||
Live preview rectangles show every frontal-face candidate: green (`#84bf65`)
|
||||
means accepted for printing; blue (`#4caee3`) means rejected by the eye-pair check.
|
||||
Rectangles use mirrored camera coordinates and share the preview cover crop.
|
||||
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;
|
||||
full per-face debug information is emitted for captures only. The preview is
|
||||
sampled separately from capture, so counts can change with movement or lighting.
|
||||
SHA-256: `8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4`
|
||||
|
||||
License: MIT, reproduced in `YUNET_LICENSE`.
|
||||
|
||||
Images retain their aspect ratio, with the longest edge resized to 320 px and
|
||||
black padding to 320×320. Confidence threshold is 0.8, NMS threshold 0.3 and top K
|
||||
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
21
models/YUNET_LICENSE
Normal 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.
|
||||
BIN
models/face_detection_yunet_2023mar.onnx
Normal file
BIN
models/face_detection_yunet_2023mar.onnx
Normal file
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
302
src/faces.rs
302
src/faces.rs
@@ -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))?;
|
||||
|
||||
25
src/main.rs
25
src/main.rs
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user