fix: tolerate natural hand poses and smooth palm tracking

This commit is contained in:
2026-11-08 12:50:54 +01:00
parent 524a9ec4b7
commit ae004379a7
3 changed files with 123 additions and 16 deletions

View File

@@ -20,4 +20,4 @@ Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models
SHA-256: `db0898ae717b76b075d9bf563af315b29562e11f8df5027a1ef07b02bef6d81c` SHA-256: `db0898ae717b76b075d9bf563af315b29562e11f8df5027a1ef07b02bef6d81c`
`src/hand_pose.rs` rotates and crops the detected hand, requires at least 0.8 hand confidence, and checks all five fingers for extension using 3D landmarks. Rejected poses reset the dwell/progress timer. This verifies an open hand, not whether the palm side rather than the back faces the camera. Thresholds may need tuning for the camera and viewing distance. `src/hand_pose.rs` rotates and crops the detected hand, requires at least 0.65 hand confidence, and checks all five fingers for extension using 3D landmarks. Finger extension tolerates natural curvature and a relaxed thumb while rejecting curled fingers and fists. Rejected poses reset the dwell/progress timer; the outline persists for up to 750 ms after the last accepted sample to avoid flicker. This verifies an open hand, not whether the palm side rather than the back faces the camera. Thresholds may need tuning for the camera and viewing distance.

View File

@@ -92,7 +92,7 @@ impl HandPose {
"Unexpected hand confidence shape", "Unexpected hand confidence shape",
)); ));
} }
if !confidence[0].is_finite() || confidence[0] < 0.8 { if !confidence[0].is_finite() || confidence[0] < 0.65 {
return Ok(false); return Ok(false);
} }
// World coordinates preserve joint angles when the hand is tilted. // World coordinates preserve joint angles when the hand is tilted.
@@ -124,7 +124,7 @@ fn straight(points: &[[f32; 3]; 21], ids: [usize; 4]) -> bool {
let p = ids.map(|i| points[i]); let p = ids.map(|i| points[i]);
let path = distance(p[0], p[1]) + distance(p[1], p[2]) + distance(p[2], p[3]); 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. // A bent finger's endpoint distance is shorter than its joint-chain length.
path > 1e-5 && distance(p[0], p[3]) / path >= 0.9 path > 1e-5 && distance(p[0], p[3]) / path >= 0.82
} }
fn is_open_hand(points: &[[f32; 3]; 21]) -> bool { fn is_open_hand(points: &[[f32; 3]; 21]) -> bool {
@@ -139,15 +139,15 @@ fn is_open_hand(points: &[[f32; 3]; 21]) -> bool {
for base in [5, 9, 13, 17] { for base in [5, 9, 13, 17] {
if !straight(points, [base, base + 1, base + 2, base + 3]) if !straight(points, [base, base + 1, base + 2, base + 3])
|| distance(points[base + 3], points[0]) || distance(points[base + 3], points[0])
< distance(points[base + 1], points[0]) + palm_length * 0.2 < distance(points[base + 1], points[0]) + palm_length * 0.1
{ {
return false; return false;
} }
} }
// Also require an extended thumb away from the index knuckle. // Also require an extended thumb away from the index knuckle.
straight(points, [1, 2, 3, 4]) straight(points, [1, 2, 3, 4])
&& distance(points[4], points[5]) > palm_length * 0.6 && distance(points[4], points[5]) > palm_length * 0.35
&& distance(points[4], points[0]) > distance(points[2], points[0]) + palm_length * 0.15 && distance(points[4], points[0]) > distance(points[2], points[0]) + palm_length * 0.08
} }
#[cfg(test)] #[cfg(test)]
@@ -183,6 +183,15 @@ mod tests {
} }
assert!(!is_open_hand(&fist)); assert!(!is_open_hand(&fist));
} }
#[test]
fn allows_natural_finger_curvature() {
let mut p = open();
p[6][0] += 0.2;
p[7][0] -= 0.1;
p[8][0] += 0.1;
assert!(is_open_hand(&p));
}
#[test] #[test]
fn rotation_scale_and_invalid_landmarks() { 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]); let p = open().map(|[x, y, z]| [y * 0.1 + 2.0, -x * 0.1 + 1.0, z * 0.1]);

View File

@@ -106,7 +106,7 @@ impl Detector {
let Some((i, &score)) = best else { let Some((i, &score)) = best else {
return Ok(None); return Ok(None);
}; };
if 1.0 / (1.0 + (-score).exp()) < 0.7 { if 1.0 / (1.0 + (-score).exp()) < 0.6 {
return Ok(None); return Ok(None);
} }
let b = &boxes[i * 18..][..18]; let b = &boxes[i * 18..][..18];
@@ -142,12 +142,19 @@ pub struct Tracker {
anchor: Option<Palm>, anchor: Option<Palm>,
steady_since: Option<Instant>, steady_since: Option<Instant>,
last_seen: Option<Instant>, last_seen: Option<Instant>,
rendered: Option<Palm>,
rendered_at: Option<Instant>,
} }
impl Tracker { impl Tracker {
pub fn update(&mut self, palm: Option<Palm>, now: Instant) { pub fn update(&mut self, palm: Option<Palm>, now: Instant) {
let Some(palm) = palm else { let Some(palm) = palm else {
*self = Self::default(); // 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; return;
}; };
let steady = self.anchor.is_some_and(|anchor| { let steady = self.anchor.is_some_and(|anchor| {
@@ -156,10 +163,14 @@ impl Tracker {
}) && self }) && self
.last_seen .last_seen
.is_some_and(|seen| now.duration_since(seen) < STALE_AFTER); .is_some_and(|seen| now.duration_since(seen) < STALE_AFTER);
if !steady { if !steady || self.steady_since.is_none() {
self.anchor = Some(palm); self.anchor = Some(palm);
self.steady_since = Some(now); self.steady_since = Some(now);
} }
if !self.has_palm(now) {
self.rendered = None;
self.rendered_at = None;
}
self.palm = Some(palm); self.palm = Some(palm);
self.last_seen = Some(now); self.last_seen = Some(now);
} }
@@ -168,17 +179,50 @@ impl Tracker {
if now.duration_since(self.last_seen?) >= STALE_AFTER { if now.duration_since(self.last_seen?) >= STALE_AFTER {
return None; return None;
} }
let elapsed = now.duration_since(self.steady_since?).as_secs_f64(); 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))) Some((self.palm?, (elapsed - 1.0).clamp(0.0, 1.0)))
} }
pub fn draw(&self, frame: &mut Mat, now: Instant) -> opencv::Result<()> { pub fn has_palm(&self, now: Instant) -> bool {
let Some((palm, progress)) = self.visible(now) else { 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(()); return Ok(());
}; };
let center = Point::new(palm.x.round() as i32, palm.y.round() as i32); 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 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); // 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 { if progress > 0.0 {
let mut overlay = frame.try_clone()?; let mut overlay = frame.try_clone()?;
imgproc::ellipse( imgproc::ellipse(
@@ -188,7 +232,7 @@ impl Tracker {
-90.0, -90.0,
0.0, 0.0,
progress * 360.0, progress * 360.0,
color, primary,
-1, -1,
imgproc::LINE_AA, imgproc::LINE_AA,
0, 0,
@@ -197,7 +241,15 @@ impl Tracker {
core::add_weighted(&overlay, 0.4, frame, 0.6, 0.0, &mut blended, -1)?; core::add_weighted(&overlay, 0.4, frame, 0.6, 0.0, &mut blended, -1)?;
*frame = blended; *frame = blended;
} }
imgproc::circle(frame, center, radius, color, 2, imgproc::LINE_AA, 0) imgproc::circle(
frame,
center,
radius,
if progress > 0.0 { primary } else { secondary },
2,
imgproc::LINE_AA,
0,
)
} }
} }
@@ -228,7 +280,8 @@ mod tests {
tracker.update(palm(120.0), now); tracker.update(palm(120.0), now);
assert_eq!(tracker.visible(now).unwrap().1, 0.0); assert_eq!(tracker.visible(now).unwrap().1, 0.0);
tracker.update(None, now); tracker.update(None, now);
assert!(tracker.visible(now).is_none()); assert_eq!(tracker.visible(now).unwrap().1, 0.0);
assert!(tracker.visible(now + STALE_AFTER).is_none());
} }
#[test] #[test]
@@ -254,6 +307,51 @@ mod tests {
); );
} }
#[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] #[test]
fn bundled_model_runs() -> opencv::Result<()> { fn bundled_model_runs() -> opencv::Result<()> {
let mut detector = Detector::new()?; let mut detector = Detector::new()?;