Skip to main content

apple_vision/humans/
mod.rs

1//! Human-rectangle detection (`VNDetectHumanRectanglesRequest`) —
2//! lightweight person bounding boxes without joint skeletons.
3
4use core::ffi::c_char;
5use core::ptr;
6use std::ffi::CString;
7use std::path::Path;
8
9use crate::error::{from_swift, VisionError};
10use crate::ffi;
11use crate::recognize_text::BoundingBox;
12
13/// One detected person.
14#[derive(Debug, Clone, PartialEq)]
15pub struct DetectedHuman {
16    pub bounding_box: BoundingBox,
17    pub confidence: f32,
18    /// `true` if the detection was constrained to upper body only.
19    pub upper_body_only: bool,
20}
21
22/// Detect humans in the image at `path`. Set `upper_body_only=true`
23/// for selfie / chest-up framing (macOS 12+); set to `false` for
24/// full-body detection.
25///
26/// # Errors
27///
28/// Returns [`VisionError::ImageLoadFailed`] / [`VisionError::RequestFailed`].
29pub fn detect_human_rectangles_in_path(
30    path: impl AsRef<Path>,
31    upper_body_only: bool,
32) -> Result<Vec<DetectedHuman>, VisionError> {
33    let path_str = path
34        .as_ref()
35        .to_str()
36        .ok_or_else(|| VisionError::InvalidArgument("non-UTF-8 path".into()))?;
37    let path_c = CString::new(path_str)
38        .map_err(|e| VisionError::InvalidArgument(format!("path NUL byte: {e}")))?;
39
40    let mut out_array: *mut core::ffi::c_void = ptr::null_mut();
41    let mut out_count: usize = 0;
42    let mut err_msg: *mut c_char = ptr::null_mut();
43
44    let status = unsafe {
45        ffi::vn_detect_human_rectangles_in_path(
46            path_c.as_ptr(),
47            upper_body_only,
48            &mut out_array,
49            &mut out_count,
50            &mut err_msg,
51        )
52    };
53    if status != ffi::status::OK {
54        return Err(unsafe { from_swift(status, err_msg) });
55    }
56    if out_array.is_null() || out_count == 0 {
57        return Ok(Vec::new());
58    }
59    let typed = out_array.cast::<ffi::HumanObservationRaw>();
60    let mut v = Vec::with_capacity(out_count);
61    for i in 0..out_count {
62        let r = unsafe { &*typed.add(i) };
63        v.push(DetectedHuman {
64            bounding_box: BoundingBox {
65                x: r.bbox_x,
66                y: r.bbox_y,
67                width: r.bbox_w,
68                height: r.bbox_h,
69            },
70            confidence: r.confidence,
71            upper_body_only: r.upper_body_only,
72        });
73    }
74    unsafe { ffi::vn_human_observations_free(out_array, out_count) };
75    Ok(v)
76}