feat: show throttled live face detection rectangles
This commit is contained in:
@@ -30,7 +30,8 @@ https://github.com/opencv/opencv/tree/4.6.0/data/haarcascades.
|
|||||||
Each XML includes its upstream license notice. They are embedded in the binary;
|
Each XML includes its upstream license notice. They are embedded in the binary;
|
||||||
no model downloads or external model paths are needed at runtime.
|
no model downloads or external model paths are needed at runtime.
|
||||||
|
|
||||||
Detection runs once per capture, with the longest image edge capped at 640 px,
|
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
|
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
|
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
|
reliable evidence of a side view. When two or more eyes are detected, a roughly
|
||||||
@@ -47,3 +48,11 @@ 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
|
detection/printing errors are logged without stopping the preview or retrying a
|
||||||
possibly submitted job. Debug logs include candidate boxes, eye counts, rejected
|
possibly submitted job. Debug logs include candidate boxes, eye counts, rejected
|
||||||
faces, accepted face/copy count, detection duration and CUPS submission result.
|
faces, accepted face/copy count, detection duration and CUPS submission result.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|||||||
@@ -101,7 +101,8 @@ fn submit_print(
|
|||||||
.stdin(Stdio::piped())
|
.stdin(Stdio::piped())
|
||||||
.stdout(Stdio::piped())
|
.stdout(Stdio::piped())
|
||||||
.stderr(Stdio::piped())
|
.stderr(Stdio::piped())
|
||||||
.spawn()?;
|
.spawn()
|
||||||
|
.map_err(|error| format!("Could not start CUPS lp print command: {error}. Install the CUPS client and ensure lp is on PATH."))?;
|
||||||
let written = child
|
let written = child
|
||||||
.stdin
|
.stdin
|
||||||
.take()
|
.take()
|
||||||
|
|||||||
79
src/faces.rs
79
src/faces.rs
@@ -1,4 +1,4 @@
|
|||||||
//! Capture-only CPU detection; no inference or allocations on preview frames.
|
//! CPU face detection shared by capture counting and a throttled live overlay.
|
||||||
use opencv::{
|
use opencv::{
|
||||||
core::{self, Mat, Rect, Size, Vector},
|
core::{self, Mat, Rect, Size, Vector},
|
||||||
imgproc, objdetect,
|
imgproc, objdetect,
|
||||||
@@ -6,6 +6,27 @@ use opencv::{
|
|||||||
};
|
};
|
||||||
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 bounds: Rect,
|
||||||
|
pub accepted: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 {
|
pub struct Detector {
|
||||||
faces: objdetect::CascadeClassifier,
|
faces: objdetect::CascadeClassifier,
|
||||||
eyes: objdetect::CascadeClassifier,
|
eyes: objdetect::CascadeClassifier,
|
||||||
@@ -29,6 +50,14 @@ impl Detector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn count(&mut self, frame: &Mat) -> opencv::Result<usize> {
|
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();
|
let start = Instant::now();
|
||||||
let mut small = Mat::default();
|
let mut small = Mat::default();
|
||||||
let scale = (640.0 / frame.cols().max(frame.rows()) as f64).min(1.0);
|
let scale = (640.0 / frame.cols().max(frame.rows()) as f64).min(1.0);
|
||||||
@@ -55,6 +84,7 @@ impl Detector {
|
|||||||
Size::default(),
|
Size::default(),
|
||||||
)?;
|
)?;
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
|
let mut detections = Vec::with_capacity(faces.len());
|
||||||
for face in faces.iter() {
|
for face in faces.iter() {
|
||||||
let upper = Mat::roi(
|
let upper = Mat::roi(
|
||||||
&equalized,
|
&equalized,
|
||||||
@@ -74,11 +104,23 @@ impl Detector {
|
|||||||
let reason = acceptance_reason(&eye_boxes, face.width);
|
let reason = acceptance_reason(&eye_boxes, face.width);
|
||||||
let accepted = reason != "unbalanced_eye_pair";
|
let accepted = reason != "unbalanced_eye_pair";
|
||||||
count += usize::from(accepted);
|
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 {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"[capture DEBUG] face={face:?} eyes={} facing_camera={accepted} reason={reason}",
|
"[capture DEBUG] face={face:?} eyes={} facing_camera={accepted} reason={reason}",
|
||||||
eyes.len()
|
eyes.len()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
if debug {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"[capture DEBUG] candidates={} faces={count} rejected={} copies={count} detection_ms={} analysis={}x{}",
|
"[capture DEBUG] candidates={} faces={count} rejected={} copies={count} detection_ms={} analysis={}x{}",
|
||||||
faces.len(),
|
faces.len(),
|
||||||
@@ -87,7 +129,8 @@ impl Detector {
|
|||||||
equalized.cols(),
|
equalized.cols(),
|
||||||
equalized.rows()
|
equalized.rows()
|
||||||
);
|
);
|
||||||
Ok(count)
|
}
|
||||||
|
Ok(detections)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,6 +168,38 @@ fn frontal_eye_pair(eyes: &[Rect], width: i32) -> bool {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
#[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]
|
#[test]
|
||||||
fn missing_eyes_do_not_discard_frontal_faces() {
|
fn missing_eyes_do_not_discard_frontal_faces() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
17
src/main.rs
17
src/main.rs
@@ -104,6 +104,8 @@ 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");
|
||||||
@@ -117,6 +119,18 @@ 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.
|
||||||
|
// 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();
|
||||||
|
}
|
||||||
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);
|
||||||
@@ -132,6 +146,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
tracker_guard.draw(&mut frame, now)?;
|
tracker_guard.draw(&mut frame, now)?;
|
||||||
}
|
}
|
||||||
drop(tracker_guard);
|
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)?;
|
||||||
let preview = PreviewFrame {
|
let preview = PreviewFrame {
|
||||||
buffer: frame_to_buffer(&frame)?,
|
buffer: frame_to_buffer(&frame)?,
|
||||||
hand_detected,
|
hand_detected,
|
||||||
|
|||||||
Reference in New Issue
Block a user