feat: add palm detection and open-hand verification

This commit is contained in:
2026-11-08 12:47:27 +01:00
parent a99bd2e69c
commit 524a9ec4b7
8 changed files with 947 additions and 16 deletions

211
src/hand_pose.rs Normal file
View File

@@ -0,0 +1,211 @@
//! Second-stage open-hand verification using MediaPipe's 21 hand landmarks.
use opencv::{
core::{self, Mat, Scalar, Size, Vector},
dnn, imgproc,
prelude::*,
};
pub struct HandPose {
net: dnn::Net,
}
impl HandPose {
pub fn new() -> opencv::Result<Self> {
let bytes = Vector::from_slice(include_bytes!(
"../models/handpose_estimation_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)?;
Ok(Self { net })
}
pub fn is_open(&mut self, frame: &Mat, palm: &[[f32; 2]; 7]) -> opencv::Result<bool> {
// Orient wrist -> middle knuckle upwards, then enlarge the landmark box
// 3x and shift it towards the fingers, matching OpenCV Zoo's hand crop.
let dx = palm[2][0] - palm[0][0];
let dy = palm[2][1] - palm[0][1];
let length = dx.hypot(dy);
if !length.is_finite() || length < 2.0 {
return Ok(false);
}
let right = [-dy / length, dx / length];
let down = [-dx / length, -dy / length];
let mut min = [f32::INFINITY; 2];
let mut max = [f32::NEG_INFINITY; 2];
for p in palm {
if !p.iter().all(|v| v.is_finite()) {
return Ok(false);
}
let rotated = [
p[0] * right[0] + p[1] * right[1],
p[0] * down[0] + p[1] * down[1],
];
for axis in 0..2 {
min[axis] = min[axis].min(rotated[axis]);
max[axis] = max[axis].max(rotated[axis]);
}
}
let width = max[0] - min[0];
let height = max[1] - min[1];
let side = 3.0 * width.max(height);
if side < 10.0 || !side.is_finite() {
return Ok(false);
}
let cx = (max[0] + min[0]) * 0.5;
let cy = (max[1] + min[1]) * 0.5 - height * 0.4;
let s = 224.0 / side;
let affine = Mat::from_slice_2d(&[
[s * right[0], s * right[1], 112.0 - s * cx],
[s * down[0], s * down[1], 112.0 - s * cy],
])?;
let mut crop = Mat::default();
imgproc::warp_affine(
frame,
&mut crop,
&affine,
Size::new(224, 224),
imgproc::INTER_LINEAR,
core::BORDER_CONSTANT,
Scalar::all(0.0),
)?;
let mut rgb = Mat::default();
imgproc::cvt_color_def(&crop, &mut rgb, imgproc::COLOR_BGR2RGB)?;
let mut normalized = Mat::default();
rgb.convert_to(&mut normalized, core::CV_32F, 1.0 / 255.0, 0.0)?;
let input = normalized.reshape_nd(1, &[1, 224, 224, 3])?;
self.net.set_input_def(&input)?;
let mut outputs: Vector<Mat> = Vector::new();
self.net
.forward(&mut outputs, &self.net.get_unconnected_out_layers_names()?)?;
if outputs.len() != 4 {
return Err(opencv::Error::new(
core::StsError,
"Unexpected hand pose output count",
));
}
let confidence = outputs.get(1)?;
let confidence = confidence.data_typed::<f32>()?;
if confidence.len() != 1 {
return Err(opencv::Error::new(
core::StsError,
"Unexpected hand confidence shape",
));
}
if !confidence[0].is_finite() || confidence[0] < 0.8 {
return Ok(false);
}
// World coordinates preserve joint angles when the hand is tilted.
let world = outputs.get(3)?;
let world = world.data_typed::<f32>()?;
if world.len() != 63 {
return Err(opencv::Error::new(
core::StsError,
"Unexpected hand landmark shape",
));
}
let mut landmarks = [[0.0; 3]; 21];
for (point, xyz) in landmarks.iter_mut().zip(world.as_chunks::<3>().0) {
point.copy_from_slice(xyz);
}
Ok(is_open_hand(&landmarks))
}
}
fn distance(a: [f32; 3], b: [f32; 3]) -> f32 {
a.iter()
.zip(b)
.map(|(a, b)| (a - b).powi(2))
.sum::<f32>()
.sqrt()
}
fn straight(points: &[[f32; 3]; 21], ids: [usize; 4]) -> bool {
let p = ids.map(|i| points[i]);
let path = distance(p[0], p[1]) + distance(p[1], p[2]) + distance(p[2], p[3]);
// A bent finger's endpoint distance is shorter than its joint-chain length.
path > 1e-5 && distance(p[0], p[3]) / path >= 0.9
}
fn is_open_hand(points: &[[f32; 3]; 21]) -> bool {
if !points.iter().flatten().all(|v| v.is_finite()) {
return false;
}
let palm_length = distance(points[0], points[9]);
if palm_length < 1e-5 {
return false;
}
// All four fingers must be straight and extend beyond their knuckles.
for base in [5, 9, 13, 17] {
if !straight(points, [base, base + 1, base + 2, base + 3])
|| distance(points[base + 3], points[0])
< distance(points[base + 1], points[0]) + palm_length * 0.2
{
return false;
}
}
// Also require an extended thumb away from the index knuckle.
straight(points, [1, 2, 3, 4])
&& distance(points[4], points[5]) > palm_length * 0.6
&& distance(points[4], points[0]) > distance(points[2], points[0]) + palm_length * 0.15
}
#[cfg(test)]
mod tests {
use super::*;
fn open() -> [[f32; 3]; 21] {
let mut p = [[0.0; 3]; 21];
for (base, x) in [(5, -0.4), (9, 0.0), (13, 0.35), (17, 0.65)] {
for j in 0..4 {
p[base + j] = [x, 1.0 + j as f32 * 0.35, 0.0];
}
}
for j in 0..4 {
p[1 + j] = [-0.3 - j as f32 * 0.3, 0.3 + j as f32 * 0.1, 0.0];
}
p
}
#[test]
fn requires_all_fingers_and_thumb_open() {
let p = open();
assert!(is_open_hand(&p));
for base in [5, 9, 13, 17] {
let mut bent = p;
bent[base + 3] = [bent[base][0], 0.8, 0.15];
assert!(!is_open_hand(&bent));
}
let mut thumb = p;
thumb[4] = thumb[5];
assert!(!is_open_hand(&thumb));
let mut fist = p;
for base in [5, 9, 13, 17] {
fist[base + 3] = [fist[base][0], 0.8, 0.15];
}
assert!(!is_open_hand(&fist));
}
#[test]
fn rotation_scale_and_invalid_landmarks() {
let p = open().map(|[x, y, z]| [y * 0.1 + 2.0, -x * 0.1 + 1.0, z * 0.1]);
assert!(is_open_hand(&p));
assert!(!is_open_hand(&[[0.0; 3]; 21]));
let mut invalid = open();
invalid[8][0] = f32::NAN;
assert!(!is_open_hand(&invalid));
}
#[test]
fn bundled_hand_model_runs() -> opencv::Result<()> {
let mut model = HandPose::new()?;
let frame = Mat::new_rows_cols_with_default(480, 640, core::CV_8UC3, Scalar::all(0.0))?;
let palm = [
[300.0, 280.0],
[280.0, 220.0],
[300.0, 210.0],
[320.0, 220.0],
[340.0, 240.0],
[270.0, 260.0],
[270.0, 240.0],
];
assert!(!model.is_open(&frame, &palm)?);
Ok(())
}
}

View File

@@ -3,11 +3,12 @@
use std::{
error::Error,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
atomic::{AtomicBool, Ordering},
mpsc,
},
thread,
time::Duration,
time::{Duration, Instant},
};
use opencv::{core::Mat, imgproc, prelude::*, videoio};
@@ -15,8 +16,12 @@ 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 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')?;
@@ -37,13 +42,11 @@ fn main() -> Result<(), Box<dyn Error>> {
}
}
let mut detector = palm::Detector::new()?;
let ui = AppWindow::new()?;
ui.window().on_close_requested(|| {
slint::CloseRequestResponse::KeepWindowShown
});
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));
@@ -51,13 +54,40 @@ fn main() -> Result<(), Box<dyn Error>> {
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.
@@ -95,20 +125,18 @@ fn main() -> Result<(), Box<dyn 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>> {
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,
)?;
imgproc::cvt_color_def(frame, &mut rgb, imgproc::COLOR_BGR2RGB)?;
// Ensure the bytes are contiguous.
let rgb = rgb.try_clone()?;

265
src/palm.rs Normal file
View File

@@ -0,0 +1,265 @@
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<Self> {
// 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<Option<Palm>> {
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<Mat> = 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::<f32>()?;
let scores = scores.data_typed::<f32>()?;
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.7 {
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<Palm>,
anchor: Option<Palm>,
steady_since: Option<Instant>,
last_seen: Option<Instant>,
}
impl Tracker {
pub fn update(&mut self, palm: Option<Palm>, now: Instant) {
let Some(palm) = palm else {
*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.anchor = Some(palm);
self.steady_since = Some(now);
}
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 = now.duration_since(self.steady_since?).as_secs_f64();
Some((self.palm?, (elapsed - 1.0).clamp(0.0, 1.0)))
}
pub fn draw(&self, frame: &mut Mat, now: Instant) -> opencv::Result<()> {
let Some((palm, progress)) = self.visible(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()));
let color = Scalar::new(80.0, 230.0, 100.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,
color,
-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, color, 2, imgproc::LINE_AA, 0)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn palm(x: f32) -> Option<Palm> {
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.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!(tracker.visible(now).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 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(())
}
}