Compare commits
5 Commits
085a5e9cc0
...
838becdd70
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
838becdd70 | ||
|
|
9cf760e7a6 | ||
|
|
6437261a65 | ||
|
|
994c78cc26 | ||
|
|
2e21946300 |
@@ -21,3 +21,41 @@ Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models
|
||||
SHA-256: `db0898ae717b76b075d9bf563af315b29562e11f8df5027a1ef07b02bef6d81c`
|
||||
|
||||
`src/hand_pose.rs` rotates and crops the detected hand, requires at least 0.65 hand confidence, and checks all five fingers for extension using 3D landmarks. Finger extension tolerates natural curvature and a relaxed thumb while rejecting curled fingers and fists. Rejected poses reset the dwell/progress timer; the outline persists for up to 750 ms after the last accepted sample to avoid flicker. This verifies an open hand, not whether the palm side rather than the back faces the camera. Thresholds may need tuning for the camera and viewing distance.
|
||||
|
||||
# Capture face counting
|
||||
|
||||
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).
|
||||
|
||||
Source: https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet
|
||||
|
||||
Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx
|
||||
|
||||
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.
@@ -60,8 +60,20 @@ impl Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_picture() {
|
||||
// TODO: Take a picture here after the countdown. No capture or file writes yet.
|
||||
/// Count the captured, clean selfie frame and pass the intended copies to the
|
||||
/// print hook. Printer integration is intentionally left unimplemented.
|
||||
pub fn take_picture(
|
||||
frame: &opencv::core::Mat,
|
||||
detector: &mut crate::faces::Detector,
|
||||
) -> opencv::Result<()> {
|
||||
let copies = detector.count(frame)?;
|
||||
eprintln!("[capture DEBUG] faces={copies} requested_copies={copies} printing=unimplemented");
|
||||
print_picture(frame, copies);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_picture(_frame: &opencv::core::Mat, _copies: usize) {
|
||||
// TODO: Implement printing.
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
291
src/faces.rs
Normal file
291
src/faces.rs
Normal file
@@ -0,0 +1,291 @@
|
||||
//! 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<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 {
|
||||
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<usize> {
|
||||
Ok(self
|
||||
.detect(frame, true)?
|
||||
.iter()
|
||||
.filter(|face| face.accepted)
|
||||
.count())
|
||||
}
|
||||
|
||||
pub fn detect(&mut self, frame: &Mat, debug: bool) -> opencv::Result<Vec<Face>> {
|
||||
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::<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] 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<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 =
|
||||
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::<core::Vec3b>(60, 50)?,
|
||||
core::Vec3b::from([101, 191, 132])
|
||||
);
|
||||
assert_eq!(
|
||||
*frame.at_2d::<core::Vec3b>(60, 200)?,
|
||||
core::Vec3b::from([227, 174, 76])
|
||||
);
|
||||
assert_eq!(
|
||||
*frame.at_2d::<core::Vec3b>(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(())
|
||||
}
|
||||
}
|
||||
29
src/main.rs
29
src/main.rs
@@ -23,6 +23,7 @@ slint::include_modules!();
|
||||
mod camera;
|
||||
mod capture;
|
||||
mod diagnostics;
|
||||
mod faces;
|
||||
mod hand_pose;
|
||||
mod palm;
|
||||
|
||||
@@ -33,6 +34,7 @@ struct PreviewFrame {
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
core::set_num_threads(2)?;
|
||||
if let Err(error) = diagnostics::log_runtime() {
|
||||
eprintln!("Failed to read OpenCV runtime diagnostics: {error}");
|
||||
}
|
||||
@@ -45,6 +47,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
mirror_frame(&mut frame)?;
|
||||
|
||||
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()
|
||||
@@ -114,15 +119,27 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let _ = detection_tx.try_send(frame.try_clone()?);
|
||||
last_detection = now;
|
||||
}
|
||||
let mut tracker = tracker.lock().unwrap();
|
||||
let hand_detected = tracker.has_palm(now);
|
||||
if sequence.tick(tracker.complete(now), hand_detected, now) {
|
||||
capture::take_picture();
|
||||
#[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 {
|
||||
// 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 failed: {error}");
|
||||
}
|
||||
tracker_guard = tracker.lock().unwrap();
|
||||
}
|
||||
if sequence.tracking() {
|
||||
tracker.draw(&mut frame, now)?;
|
||||
tracker_guard.draw(&mut frame, now)?;
|
||||
}
|
||||
drop(tracker);
|
||||
drop(tracker_guard);
|
||||
// Draw only after capture and palm sampling so printed photos and
|
||||
// detector inputs never contain debug rectangles.
|
||||
#[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