Face detection in Rust con OpenCV

Mattepuffo's logo
Face detection in Rust con OpenCV

Face detection in Rust con OpenCV

In questo articolo vediamo come fare face detection in Rust usando OpenCV.

La prima cosa che dovete fare è installare OpenCV sul sistema.

Ovviamente dipende dall'OS.

Poi dovete scaricare il file haarcascade_frontalface_default.xml e metterlo nella root del progetto.

Poi nel vostro progetto aggiungete questa dipendenza:

[dependencies]
opencv = { version = "0.98.1", features = ["clang-runtime"] }

Non è detto che vi serva queall feature, anche qui penso dipenda dall'OS.

Io per ora ho testo il tutto solo su Linux.

Qui sotto un pò di codice:

use opencv::core::AlgorithmHint;
use opencv::{Result, core, highgui, imgproc, objdetect, prelude::*, videoio};

fn main() -> Result<()> {
    let window = "Face Detection - Rust";
    highgui::named_window(window, highgui::WINDOW_NORMAL)?;

    let mut face_detector =
        objdetect::CascadeClassifier::new("haarcascade_frontalface_default.xml")?;

    let mut cam = videoio::VideoCapture::new(0, videoio::CAP_ANY)?;

    let opened = videoio::VideoCapture::is_opened(&cam)?;
    if !opened {
        eprintln!("--- ERRORE ---");
        eprintln!("Non riesco ad accedere alla webcam.");
        eprintln!("Controlla che non sia usata da un'altra app (es. browser o Zoom).");
        return Ok(());
    }

    let mut frame = Mat::default();

    println!("Premi 'q' per uscire.");

    loop {
        cam.read(&mut frame)?;
        if frame.size()?.width == 0 {
            continue;
        }

        let mut gray = Mat::default();
        imgproc::cvt_color(
            &frame,
            &mut gray,
            imgproc::COLOR_BGR2GRAY,
            0,
            AlgorithmHint::ALGO_HINT_DEFAULT,
        )?;
        imgproc::equalize_hist(&gray, &mut gray.clone())?;

        let mut faces = core::Vector::<core::Rect>::new();
        face_detector.detect_multi_scale(
            &gray,
            &mut faces,
            1.1,
            7,
            0,
            core::Size::new(100, 100),
            core::Size::new(0, 0),
        )?;

        let count = faces.len();

        for face in &faces {
            imgproc::rectangle(
                &mut frame,
                face,
                core::Scalar::new(0.0, 255.0, 0.0, 0.0),
                2,
                imgproc::LINE_8,
                0,
            )?;
        }

        let text = format!("Volti: {}", count);
        imgproc::put_text(
            &mut frame,
            &text,
            core::Point::new(30, 50),
            imgproc::FONT_HERSHEY_SIMPLEX,
            1.2,
            core::Scalar::new(0.0, 255.0, 255.0, 0.0),
            3,
            imgproc::LINE_8,
            false,
        )?;

        highgui::imshow(window, &frame)?;

        // Uscita
        let key = highgui::wait_key(10)?;
        if key == 113 {
            break;
        }
    }

    Ok(())
}

Enjoy!


Condividi

Commentami!