feat: print captured photos per detected frontal face

This commit is contained in:
2026-11-10 14:49:59 +01:00
parent 085a5e9cc0
commit 2e21946300
6 changed files with 43587 additions and 8 deletions

View File

@@ -60,14 +60,91 @@ impl Sequence {
}
}
pub fn take_picture() {
// TODO: Take a picture here after the countdown. No capture or file writes yet.
/// Submit the clean, mirrored camera frame to the default CUPS printer.
/// JPEG travels over stdin, so captured photos are never left in temporary files.
pub fn take_picture(
frame: &opencv::core::Mat,
detector: &mut crate::faces::Detector,
) -> Result<(), Box<dyn std::error::Error>> {
use opencv::{core::Vector, imgcodecs};
let copies = detector.count(frame)?;
if copies == 0 {
eprintln!("[capture DEBUG] No frontal faces; skipping print job");
return Ok(());
}
let mut jpeg = Vector::<u8>::new();
if !imgcodecs::imencode(".jpg", frame, &mut jpeg, &Vector::new())? {
return Err("Could not encode captured image".into());
}
submit_print(
jpeg.as_slice(),
copies,
&mut std::process::Command::new("lp"),
)
}
fn submit_print(
jpeg: &[u8],
copies: usize,
command: &mut std::process::Command,
) -> Result<(), Box<dyn std::error::Error>> {
use std::{io::Write, process::Stdio};
let mut child = command
.args([
"-n",
&copies.to_string(),
"-t",
"winf photobooth",
"-o",
"fit-to-page",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let written = child
.stdin
.take()
.ok_or("Printer stdin unavailable")?
.write_all(jpeg);
// Reap lp even if writing fails; never retry an ambiguously submitted job.
let output = child.wait_with_output()?;
if !output.status.success() {
return Err(format!(
"lp failed ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr)
)
.into());
}
written?;
eprintln!(
"[capture DEBUG] Submitted copies={copies}: {}",
String::from_utf8_lossy(&output.stdout).trim()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn printer_receives_copy_count_and_image_and_reports_failure() {
use std::process::Command;
let mut printer = Command::new("sh");
printer.args(["-c", r#"test "$1" = -n && test "$2" = 3 && test "$4" = 'winf photobooth' && test "$6" = fit-to-page && test "$(cat)" = photo"#, "mock-lp"]);
submit_print(b"photo", 3, &mut printer).unwrap();
let mut failing = Command::new("sh");
failing.args(["-c", "cat >/dev/null; echo unavailable >&2; exit 1"]);
assert!(
submit_print(b"photo", 2, &mut failing)
.unwrap_err()
.to_string()
.contains("unavailable")
);
}
#[test]
fn flash_countdown_and_single_capture_then_release() {
let start = Instant::now();

132
src/faces.rs Normal file
View File

@@ -0,0 +1,132 @@
//! Capture-only CPU detection; no inference or allocations on preview frames.
use opencv::{
core::{self, Mat, Rect, Size, Vector},
imgproc, objdetect,
prelude::*,
};
use std::time::Instant;
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)
}
impl Detector {
pub fn new() -> opencv::Result<Self> {
Ok(Self {
faces: cascade(include_str!("../models/haarcascade_frontalface_alt2.xml"))?,
eyes: cascade(include_str!(
"../models/haarcascade_eye_tree_eyeglasses.xml"
))?,
})
}
pub fn count(&mut self, frame: &Mat) -> opencv::Result<usize> {
let start = Instant::now();
let mut small = Mat::default();
let scale = (640.0 / frame.cols().max(frame.rows()) as f64).min(1.0);
imgproc::resize(
frame,
&mut small,
Size::default(),
scale,
scale,
imgproc::INTER_AREA,
)?;
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,
0,
Size::new(40, 40),
Size::default(),
)?;
let mut count = 0;
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 accepted = frontal_eye_pair(&eyes.to_vec(), face.width);
count += usize::from(accepted);
eprintln!(
"[capture DEBUG] face={face:?} eyes={} facing_camera={accepted}",
eyes.len()
);
}
eprintln!(
"[capture DEBUG] candidates={} faces={count} rejected={} copies={count} detection_ms={} analysis={}x{}",
faces.len(),
faces.len() - count,
start.elapsed().as_millis(),
equalized.cols(),
equalized.rows()
);
Ok(count)
}
}
// 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
})
})
}
#[cfg(test)]
mod tests {
use super::*;
#[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));
}
#[test]
fn bundled_cascades_run_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(())
}
}

View File

@@ -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,7 @@ fn main() -> Result<(), Box<dyn Error>> {
mirror_frame(&mut frame)?;
let mut detector = palm::Detector::new()?;
let mut face_detector = faces::Detector::new()?;
let ui = AppWindow::new()?;
ui.window()
@@ -114,15 +117,21 @@ 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();
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.
drop(tracker_guard);
if let Err(error) = capture::take_picture(&frame, &mut face_detector) {
eprintln!("[capture ERROR] Face counting / printing 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);
let preview = PreviewFrame {
buffer: frame_to_buffer(&frame)?,
hand_detected,