use std::time::{Duration, Instant}; use opencv::{ core::{self, Mat, Point, Scalar, Size, Vector}, dnn, imgproc, prelude::*, }; pub const DETECTION_INTERVAL: Duration = Duration::from_millis(250); const STALE_AFTER: Duration = Duration::from_millis(750); #[derive(Clone, Copy, Debug)] pub struct Palm { pub x: f32, pub y: f32, pub radius: f32, } pub struct Detector { net: dnn::Net, hand_pose: crate::hand_pose::HandPose, anchors: Vec<(f32, f32)>, } impl Detector { pub fn new() -> opencv::Result { // Embed the weights so launching from another directory also works. let bytes = Vector::from_slice(include_bytes!( "../models/palm_detection_mediapipe_2023feb.onnx" )); let mut net = dnn::read_net_from_onnx_buffer(&bytes)?; net.set_preferable_backend(dnn::DNN_BACKEND_OPENCV)?; net.set_preferable_target(dnn::DNN_TARGET_CPU)?; let mut anchors = Vec::new(); for (grid, repeats) in [(24, 2), (12, 6)] { for y in 0..grid { for x in 0..grid { for _ in 0..repeats { anchors.push(( (x as f32 + 0.5) / grid as f32, (y as f32 + 0.5) / grid as f32, )); } } } } Ok(Self { net, anchors, hand_pose: crate::hand_pose::HandPose::new()?, }) } pub fn detect(&mut self, frame: &Mat) -> opencv::Result> { let scale = 192.0 / frame.cols().max(frame.rows()) as f32; let width = (frame.cols() as f32 * scale) as i32; let height = (frame.rows() as f32 * scale) as i32; let left = (192 - width) / 2; let top = (192 - height) / 2; 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, top, 192 - height - top, left, 192 - width - left, core::BORDER_CONSTANT, Scalar::all(0.0), )?; let mut rgb = Mat::default(); imgproc::cvt_color_def(&padded, &mut rgb, imgproc::COLOR_BGR2RGB)?; let mut normalized = Mat::default(); rgb.convert_to(&mut normalized, core::CV_32F, 1.0 / 255.0, 0.0)?; // This model expects NHWC rather than the usual OpenCV NCHW blob. let input = normalized.reshape_nd(1, &[1, 192, 192, 3])?; self.net.set_input_def(&input)?; let mut outputs: Vector = Vector::new(); self.net .forward(&mut outputs, &self.net.get_unconnected_out_layers_names()?)?; let boxes = outputs.get(0)?; let scores = outputs.get(1)?; let boxes = boxes.data_typed::()?; let scores = scores.data_typed::()?; if boxes.len() != self.anchors.len() * 18 || scores.len() != self.anchors.len() { return Err(opencv::Error::new( core::StsError, "Unexpected palm model output shape", )); } // Track the most confident palm; duplicate anchors need no NMS for a single result. let best = scores .iter() .enumerate() .filter(|(_, s)| s.is_finite()) .max_by(|a, b| a.1.total_cmp(b.1)); let Some((i, &score)) = best else { return Ok(None); }; if 1.0 / (1.0 + (-score).exp()) < 0.6 { return Ok(None); } let b = &boxes[i * 18..][..18]; let (ax, ay) = self.anchors[i]; let palm = Palm { x: (b[0] + ax * 192.0 - left as f32) / scale, y: (b[1] + ay * 192.0 - top as f32) / scale, radius: b[2].max(b[3]) * 0.5 / scale, }; if !(palm.x.is_finite() && palm.y.is_finite() && palm.radius.is_finite() && palm.radius >= 5.0 && palm.x >= 0.0 && palm.y >= 0.0 && palm.x < frame.cols() as f32 && palm.y < frame.rows() as f32) { return Ok(None); } let mut landmarks = [[0.0; 2]; 7]; for (j, point) in landmarks.iter_mut().enumerate() { point[0] = (b[4 + j * 2] + ax * 192.0 - left as f32) / scale; point[1] = (b[5 + j * 2] + ay * 192.0 - top as f32) / scale; } Ok(self.hand_pose.is_open(frame, &landmarks)?.then_some(palm)) } } #[derive(Default)] pub struct Tracker { palm: Option, anchor: Option, steady_since: Option, last_seen: Option, rendered: Option, rendered_at: Option, } impl Tracker { pub fn update(&mut self, palm: Option, now: Instant) { let Some(palm) = palm else { // Keep the outline through a brief missed sample, but stop progress. // A fist cannot complete the timer using an older open-hand result. self.steady_since = None; if !self.has_palm(now) { *self = Self::default(); } return; }; let steady = self.anchor.is_some_and(|anchor| { (palm.x - anchor.x).hypot(palm.y - anchor.y) <= (anchor.radius * 0.25).max(8.0) && (palm.radius - anchor.radius).abs() <= anchor.radius * 0.25 }) && self .last_seen .is_some_and(|seen| now.duration_since(seen) < STALE_AFTER); if !steady || self.steady_since.is_none() { self.anchor = Some(palm); self.steady_since = Some(now); } if !self.has_palm(now) { self.rendered = None; self.rendered_at = None; } self.palm = Some(palm); self.last_seen = Some(now); } fn visible(&self, now: Instant) -> Option<(Palm, f64)> { if now.duration_since(self.last_seen?) >= STALE_AFTER { return None; } let elapsed = self .steady_since .map_or(0.0, |since| now.duration_since(since).as_secs_f64()); Some((self.palm?, (elapsed - 1.0).clamp(0.0, 1.0))) } pub fn complete(&self, now: Instant) -> bool { self.visible(now) .is_some_and(|(_, progress)| progress >= 1.0) } pub fn has_palm(&self, now: Instant) -> bool { self.last_seen .is_some_and(|seen| now.duration_since(seen) < STALE_AFTER) } fn smooth(&mut self, now: Instant) -> Option<(Palm, f64)> { let Some((target, progress)) = self.visible(now) else { self.rendered = None; self.rendered_at = None; return None; }; // Time-based exponential smoothing, updated at camera frame rate rather // than inference rate. Keep raw detections for the steadiness check. let palm = match (self.rendered, self.rendered_at) { (Some(previous), Some(at)) => { let alpha = 1.0 - (-now.duration_since(at).as_secs_f32() / 0.16).exp(); Palm { x: previous.x + (target.x - previous.x) * alpha, y: previous.y + (target.y - previous.y) * alpha, radius: previous.radius + (target.radius - previous.radius) * alpha, } } _ => target, }; self.rendered = Some(palm); self.rendered_at = Some(now); Some((palm, progress)) } pub fn draw(&mut self, frame: &mut Mat, now: Instant) -> opencv::Result<()> { let Some((palm, progress)) = self.smooth(now) else { return Ok(()); }; let center = Point::new(palm.x.round() as i32, palm.y.round() as i32); let radius = (palm.radius.round() as i32).clamp(1, frame.cols().max(frame.rows())); // OpenCV colors are BGR: primary #84bf65, secondary #4caee3. let primary = Scalar::new(101.0, 191.0, 132.0, 0.0); let secondary = Scalar::new(227.0, 174.0, 76.0, 0.0); if progress > 0.0 { let mut overlay = frame.try_clone()?; imgproc::ellipse( &mut overlay, center, Size::new(radius, radius), -90.0, 0.0, progress * 360.0, primary, -1, imgproc::LINE_AA, 0, )?; let mut blended = Mat::default(); core::add_weighted(&overlay, 0.4, frame, 0.6, 0.0, &mut blended, -1)?; *frame = blended; } imgproc::circle( frame, center, radius, if progress > 0.0 { primary } else { secondary }, 2, imgproc::LINE_AA, 0, ) } } #[cfg(test)] mod tests { use super::*; fn palm(x: f32) -> Option { Some(Palm { x, y: 100.0, radius: 40.0, }) } #[test] fn dwell_then_fill_and_reset() { let start = Instant::now(); let mut tracker = Tracker::default(); for ms in [0, 250, 500, 750, 1000, 1250, 1500, 1750, 2000] { let now = start + Duration::from_millis(ms); tracker.update(palm(100.0), now); assert_eq!(tracker.complete(now), ms >= 2000); assert_eq!( tracker.visible(now).unwrap().1, ((ms as f64 / 1000.0) - 1.0).clamp(0.0, 1.0) ); } let now = start + Duration::from_millis(2250); tracker.update(palm(120.0), now); assert_eq!(tracker.visible(now).unwrap().1, 0.0); tracker.update(None, now); assert_eq!(tracker.visible(now).unwrap().1, 0.0); assert!(tracker.visible(now + STALE_AFTER).is_none()); } #[test] fn drift_and_stale_results_reset() { let start = Instant::now(); let mut tracker = Tracker::default(); tracker.update(palm(100.0), start); tracker.update(palm(108.0), start + Duration::from_millis(250)); tracker.update(palm(116.0), start + Duration::from_millis(500)); assert_eq!( tracker.steady_since, Some(start + Duration::from_millis(500)) ); assert!( tracker .visible(start + Duration::from_millis(1250)) .is_none() ); tracker.update(palm(116.0), start + Duration::from_secs(2)); assert_eq!( tracker.visible(start + Duration::from_secs(2)).unwrap().1, 0.0 ); } #[test] fn missed_sample_keeps_outline_but_restarts_dwell() { let start = Instant::now(); let mut tracker = Tracker::default(); tracker.update(palm(100.0), start); tracker.update(palm(100.0), start + Duration::from_millis(500)); tracker.update(None, start + Duration::from_millis(750)); assert!(tracker.has_palm(start + Duration::from_millis(750))); assert_eq!( tracker .visible(start + Duration::from_millis(750)) .unwrap() .1, 0.0 ); tracker.update(palm(100.0), start + Duration::from_millis(1000)); assert_eq!(tracker.steady_since, Some(start + Duration::from_secs(1))); } #[test] fn smoothing_interpolates_and_reacquisition_does_not_fly_across_screen() { let start = Instant::now(); let mut tracker = Tracker::default(); tracker.update(palm(100.0), start); tracker.smooth(start); tracker.update(palm(140.0), start + Duration::from_millis(250)); let x = tracker .smooth(start + Duration::from_millis(250)) .unwrap() .0 .x; assert!(x > 100.0 && x < 140.0); let x2 = tracker .smooth(start + Duration::from_millis(283)) .unwrap() .0 .x; assert!(x2 > x && x2 < 140.0); tracker.update(palm(400.0), start + Duration::from_secs(2)); assert_eq!( tracker.smooth(start + Duration::from_secs(2)).unwrap().0.x, 400.0 ); } #[test] fn bundled_model_runs() -> opencv::Result<()> { let mut detector = Detector::new()?; assert_eq!(detector.anchors.len(), 2016); let frame = Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, Scalar::all(0.0))?; assert!(detector.detect(&frame)?.is_none()); Ok(()) } }