diff --git a/models/HANDPOSE_LICENSE b/models/HANDPOSE_LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/models/HANDPOSE_LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/models/LICENSE b/models/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/models/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/models/README.md b/models/README.md new file mode 100644 index 0000000..983f932 --- /dev/null +++ b/models/README.md @@ -0,0 +1,23 @@ +# Palm detection model + +`palm_detection_mediapipe_2023feb.onnx` is the floating-point MediaPipe palm detector distributed by OpenCV Zoo, under Apache 2.0 (see LICENSE). + +Source: https://github.com/opencv/opencv_zoo/tree/main/models/palm_detection_mediapipe + +Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/palm_detection_mediapipe/palm_detection_mediapipe_2023feb.onnx + +SHA-256: `78ff51c38496b7fc8b8ebdb6cc8c1abb02fa6c38427c6848254cdaba57fcce7c` + +The weights are embedded in the executable. Inference and preprocessing are implemented in `src/palm.rs`, following OpenCV Zoo's `mp_palmdet.py` reference. No download is needed at runtime. + +## Open-hand verification + +`handpose_estimation_mediapipe_2023feb.onnx` provides 21 hand landmarks for second-stage verification. Distributed under Apache 2.0 (see HANDPOSE_LICENSE). + +Source and preprocessing reference: https://github.com/opencv/opencv_zoo/tree/main/models/handpose_estimation_mediapipe + +Weights: https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/handpose_estimation_mediapipe/handpose_estimation_mediapipe_2023feb.onnx + +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. diff --git a/models/handpose_estimation_mediapipe_2023feb.onnx b/models/handpose_estimation_mediapipe_2023feb.onnx new file mode 100644 index 0000000..87456a6 Binary files /dev/null and b/models/handpose_estimation_mediapipe_2023feb.onnx differ diff --git a/models/palm_detection_mediapipe_2023feb.onnx b/models/palm_detection_mediapipe_2023feb.onnx new file mode 100644 index 0000000..2b15a2a Binary files /dev/null and b/models/palm_detection_mediapipe_2023feb.onnx differ diff --git a/src/hand_pose.rs b/src/hand_pose.rs new file mode 100644 index 0000000..c89649a --- /dev/null +++ b/src/hand_pose.rs @@ -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 { + 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 { + // 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 = 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::()?; + 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::()?; + 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::() + .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(()) + } +} diff --git a/src/main.rs b/src/main.rs index 70560ed..b0d275a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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> { - 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> { } } - - + 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> { 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::(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> { 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> { +fn frame_to_buffer(frame: &Mat) -> opencv::Result> { 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()?; diff --git a/src/palm.rs b/src/palm.rs new file mode 100644 index 0000000..03b443f --- /dev/null +++ b/src/palm.rs @@ -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 { + // 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.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, + anchor: Option, + steady_since: Option, + last_seen: Option, +} + +impl Tracker { + pub fn update(&mut self, palm: Option, 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 { + 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(()) + } +}