From 5d13f4606a18e0b031c83dfef723b2a355c6a19d Mon Sep 17 00:00:00 2001 From: r0r-5chach Date: Mon, 20 May 2024 01:52:51 +0100 Subject: [PATCH] pupil completed --- src/features.rs | 59 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 8 deletions(-) diff --git a/src/features.rs b/src/features.rs index 5d9dcbc..f563f66 100644 --- a/src/features.rs +++ b/src/features.rs @@ -1,11 +1,54 @@ - -pub struct Point { - x: f64, - y: f64, -} +use opencv::{core, imgproc, types}; pub struct Pupil { - pub iris_frame: String, - pub threshold: String, - pub coordinates: Point, + pub iris_frame: core::Mat, + pub threshold: f64, + pub coordinates: core::Point, +} +impl Pupil { + pub fn new(eye_frame: core::Mat, threshold: f64) -> Self { + let iris_frame = image_processing::(&eye_frame, threshold).unwrap(); + let mut contours = types::VectorOfVectorOfPoint::new(); + + let _ = imgproc::find_contours(&iris_frame, &mut contours, imgproc::RETR_TREE, imgproc::CHAIN_APPROX_NONE, core::Point::new(0,0)); + + let mut contours: Vec = contours.into_iter().collect(); + + contours.sort_by(|a, b| { + let area_a = imgproc::contour_area(&a, false).unwrap(); + let area_b = imgproc::contour_area(&b, false).unwrap(); + area_a.partial_cmp(&area_b).unwrap() + }); + + let largest_contour = contours.get(contours.len() - 2).unwrap(); + let moments = imgproc::moments(&largest_contour, false).unwrap(); + let mut x = 0.0; + let mut y = 0.0; + + if moments.m00 != 0.0 { + x = moments.m10 / moments.m00; + y = moments.m01 / moments.m00; + } + + let coordinates = core::Point::new(x as i32, y as i32); + + Self { + iris_frame, + threshold, + coordinates, + } + } +} + +pub fn image_processing(eye_frame: &core::Mat, threshold: f64) -> Result { + let kernel = core::Mat::new_rows_cols_with_default(3,3, core::CV_8U, core::Scalar::all(1.0))?; + let mut new_frame = core::Mat::default(); + + let _ = imgproc::bilateral_filter(eye_frame, &mut new_frame, 10, 15.0, 15.0, core::BORDER_DEFAULT); + + let _ = imgproc::erode(&new_frame.clone(), &mut new_frame, &kernel, core::Point::new(-1,-1), 3, core::BORDER_CONSTANT, core::Scalar::all(0.0)); + + imgproc::threshold(&new_frame.clone(), &mut new_frame, threshold, 255.0, imgproc::THRESH_BINARY)?; + + Ok(new_frame) }