150 lines
4.4 KiB
Rust
150 lines
4.4 KiB
Rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
|
|
|
use std::{
|
|
error::Error,
|
|
sync::{
|
|
Arc, Mutex,
|
|
atomic::{AtomicBool, Ordering},
|
|
mpsc,
|
|
},
|
|
thread,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use opencv::{core::Mat, imgproc, prelude::*, videoio};
|
|
use slint::{Rgb8Pixel, SharedPixelBuffer};
|
|
|
|
slint::include_modules!();
|
|
|
|
mod hand_pose;
|
|
mod palm;
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
let mut cam =
|
|
videoio::VideoCapture::new(0, videoio::CAP_V4L2).expect("Failed to get video capture");
|
|
let mut frame = Mat::default();
|
|
|
|
let codec = videoio::VideoWriter::fourcc('M', 'J', 'P', 'G')?;
|
|
|
|
for (property, value) in [
|
|
(videoio::CAP_PROP_FOURCC, codec as f64),
|
|
(videoio::CAP_PROP_FRAME_WIDTH, 640.0),
|
|
(videoio::CAP_PROP_FRAME_HEIGHT, 480.0),
|
|
] {
|
|
if !cam.set(property, value)? {
|
|
eprintln!("Camera rejected property {property}");
|
|
}
|
|
}
|
|
|
|
for _ in 0..30 {
|
|
if !cam.read(&mut frame)? || frame.empty() {
|
|
return Err("Failed to capture a frame".into());
|
|
}
|
|
}
|
|
|
|
let mut detector = palm::Detector::new()?;
|
|
let ui = AppWindow::new()?;
|
|
|
|
ui.window()
|
|
.on_close_requested(|| slint::CloseRequestResponse::KeepWindowShown);
|
|
|
|
let latest_frame = Arc::new(Mutex::new(Some(frame_to_buffer(&frame)?)));
|
|
let running = Arc::new(AtomicBool::new(true));
|
|
|
|
let worker_frame = Arc::clone(&latest_frame);
|
|
let worker_running = Arc::clone(&running);
|
|
|
|
let tracker = Arc::new(Mutex::new(palm::Tracker::default()));
|
|
let detection_tracker = Arc::clone(&tracker);
|
|
// A rendezvous channel drops samples while inference is busy, avoiding a backlog.
|
|
let (detection_tx, detection_rx) = mpsc::sync_channel::<Mat>(0);
|
|
let detection_worker = thread::spawn(move || {
|
|
while let Ok(sample) = detection_rx.recv() {
|
|
let result = match detector.detect(&sample) {
|
|
Ok(palm) => palm,
|
|
Err(error) => {
|
|
eprintln!("Palm detection error: {error}");
|
|
None
|
|
}
|
|
};
|
|
detection_tracker
|
|
.lock()
|
|
.unwrap()
|
|
.update(result, Instant::now());
|
|
}
|
|
});
|
|
|
|
let worker = thread::spawn(move || -> opencv::Result<()> {
|
|
let mut last_detection = Instant::now() - palm::DETECTION_INTERVAL;
|
|
while worker_running.load(Ordering::Relaxed) {
|
|
if !cam.read(&mut frame)? || frame.empty() {
|
|
eprintln!("Camera stopped providing frames");
|
|
break;
|
|
}
|
|
|
|
let now = Instant::now();
|
|
if now.duration_since(last_detection) >= palm::DETECTION_INTERVAL {
|
|
let _ = detection_tx.try_send(frame.try_clone()?);
|
|
last_detection = now;
|
|
}
|
|
tracker.lock().unwrap().draw(&mut frame, now)?;
|
|
let buffer = frame_to_buffer(&frame)?;
|
|
|
|
// Replace any undisplayed frame with the newest one.
|
|
*worker_frame.lock().unwrap() = Some(buffer);
|
|
}
|
|
|
|
Ok(())
|
|
});
|
|
|
|
let ui_handle = ui.as_weak();
|
|
let timer = slint::Timer::default();
|
|
|
|
timer.start(
|
|
slint::TimerMode::Repeated,
|
|
Duration::from_millis(33),
|
|
move || {
|
|
let buffer = latest_frame.lock().unwrap().take();
|
|
|
|
if let (Some(app), Some(buffer)) = (ui_handle.upgrade(), buffer) {
|
|
app.set_video_frame(slint::Image::from_rgb8(buffer));
|
|
}
|
|
},
|
|
);
|
|
|
|
// Keep `timer` alive while the interface is running.
|
|
let result = ui.run();
|
|
|
|
timer.stop();
|
|
running.store(false, Ordering::Relaxed);
|
|
|
|
// Wait for the current camera read to finish and release the camera.
|
|
match worker.join() {
|
|
Ok(Ok(())) => {}
|
|
Ok(Err(error)) => eprintln!("Capture error: {error}"),
|
|
Err(_) => eprintln!("Capture thread panicked"),
|
|
}
|
|
|
|
if detection_worker.join().is_err() {
|
|
eprintln!("Palm detection thread panicked");
|
|
}
|
|
|
|
result?;
|
|
Ok(())
|
|
}
|
|
|
|
fn frame_to_buffer(frame: &Mat) -> opencv::Result<SharedPixelBuffer<Rgb8Pixel>> {
|
|
let mut rgb = Mat::default();
|
|
|
|
imgproc::cvt_color_def(frame, &mut rgb, imgproc::COLOR_BGR2RGB)?;
|
|
|
|
// Ensure the bytes are contiguous.
|
|
let rgb = rgb.try_clone()?;
|
|
|
|
Ok(SharedPixelBuffer::<Rgb8Pixel>::clone_from_slice(
|
|
rgb.data_bytes()?,
|
|
rgb.cols() as u32,
|
|
rgb.rows() as u32,
|
|
))
|
|
}
|