Just set of functions to utilize YOLO v3, v4, v7 and v8 version with OpenCV's DNN module

Overview

Package

Object detection utilities in Rust programming language for YOLO-based neural networks in OpenCV ecosystem

This crate provides some basic structures and methods for solving object detections tasks via OpenCV's DNN module. Currently implemented and tested workflows:

Network type Darknet ONNX
YOLO v3 tiny
YOLO v4 tiny
YOLO v7 tiny
YOLO v3 ❓ (need to test)
YOLO v4 ❓ (need to test)
YOLO v7 ❓ (need to test)
YOLO v8 n ❌ (is it even possible?)

Table of Contents

About

- Why?

Well, I just tired a bit of boilerplating (model initializing, postprocessing functions and etc.) in my both private and public projects.

- When it is usefull?

Well, there are several circumstances when you may need this crate:

  • You need to use YOLO as your neural network base;
  • You do not want use Pytorch / Tensorflow / Jax or any other DL/ML framework (someday it may happen to use pure ONNX without OpenCV features in this crate - PR's are welcome);
  • You need to use OpenCV's DNN module to initialize neural network;

- Why no YOLOv5?

I think there is a difference in postprocessing stuff between v8 and v5 version. I need more time to investigate what should be done exactly to make v5 work.

- What OpenCV's version is tested?

I've tested it with v4.7.0. Rust bindings version: v0.66.0

- Is wrapper structures are thread safe?

I'm not sure it is intended to be used in multiple threads (PR's are welcome). But I think you should use some queue mechanism if you want to give "async" acces to provided structs.

Prerequisites

  • For sure you must have OpenCV installed with DNN extra module. If you need to ulitize power of GPU/OpenVINO then you need to consider corresponding extra modules too.

    I love to use this Makefile with little adjustment (OpenCV's version / enabling python bindings) for my needs.

  • Prepare neural network: train it or get pretrained one. I provide pretty simple Bash scripts to download "small" versions of YOLO

Usage

There are some examples, but let me guide you step-by-step

  1. Add this crate to your's Cargo.toml:

    cargo add od_opencv
  2. Add OpenCV's bindings crate to Cargo.toml also:

    # I'm using 0.66 version
    cargo add [email protected]
  3. Download pretrained or use your own neural network.

    I will use pretrained weights from prerequisites section

  4. Import "basic" OpenCV stuff in yours main.rs file:

    use opencv::{
        core::{Scalar, Vector},
        imgcodecs::imread,
        imgcodecs::imwrite,
        imgproc::LINE_4,
        imgproc::rectangle,
        dnn::DNN_BACKEND_CUDA, // I will utilize my GPU to perform faster inference. Your way may vary
        dnn::DNN_TARGET_CUDA,
    };
  5. Import crate

    use od_opencv::{
        model_format::ModelFormat,
        // I'll use YOLOv8 by Ultralytics.
        // If you prefer traditional YOLO, then import it as:
        // model_classic::ModelYOLOClassic
        model_ultralytics::ModelUltralyticsV8
    };
  6. Prepare model

    // Define classes (in this case we consider 80 COCO labels)
    let classes_labels: Vec<&str> = vec!["person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed", "diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"];
    
    // Define format for OpenCV's DNN module
    let mf = ModelFormat::ONNX;
    
    // Define model's input size
    let net_width = 640;
    let net_height = 640;
    
    // Initialize model itself
    let mut model = ModelUltralyticsV8::new_from_file("pretrained/yolov8n.onnx", None, (net_width, net_height), mf, DNN_BACKEND_CUDA, DNN_TARGET_CUDA, vec![]).unwrap();
    
    // Read image into the OpenCV's Mat object
    // Define it as mutable since we are going to put bounding boxes onto it.
    let mut frame = imread("images/dog.jpg", 1).unwrap();
    
    // Feed forward image through the model
    let (bboxes, class_ids, confidences) = model.forward(&frame, 0.25, 0.4).unwrap();
    
    // Process results
    for (i, bbox) in bboxes.iter().enumerate() {
        // Place bounding boxes onto the image
        rectangle(&mut frame, *bbox, Scalar::from((0.0, 255.0, 0.0)), 2, LINE_4, 0).unwrap();
        // Debug output to stdin
        println!("Class: {}", classes_labels[class_ids[i]]);
        println!("\tBounding box: {:?}", bbox);
        println!("\tConfidences: {}", confidences[i]);
    }
    
    // Finally save the updated image to the file system
    imwrite("images/dog_yolov8_n.jpg", &frame, &Vector::new()).unwrap();
  7. You are good to go

    cargo run
  8. If anything is going wrong, feel free to open an issue

References

You might also like...
PNG decoding and encoding library in pure Rust

PNG Decoder/Encoder PNG decoder/encoder in pure Rust. It contains all features required to handle the entirety of the PngSuite by Willem van Schack. p

Refract - A guided AVIF/JPEG XL/WebP conversion utility for JPEG and PNG sources.
Refract - A guided AVIF/JPEG XL/WebP conversion utility for JPEG and PNG sources.

Refract GTK Refract is a guided image conversion tool written in Rust for x86-64 Linux systems with GTK. It takes JPEG and PNG image sources and produ

Encoding and decoding images in Rust
Encoding and decoding images in Rust

Image Maintainers: @HeroicKatora, @fintelia How to contribute An Image Processing Library This crate provides basic image processing functions and met

Rust library to get image size and format without loading/decoding

imageinfo-rs Rust library to get image size and format without loading/decoding. The imageinfo don't get image format by file ext name, but infer by f

🖼️Combines a Javascript and WASM file into a single executable polygot PNG+HTML file.

WASIMAGE Combines a Javascript and WASM file into a single executable polygot PNG+HTML file. Usage: cargo install wasimage wasimage --wasm-file my.was

Simple image metadata scrubber. Will remove EXIF, XMP and IPTC metadata.

Simple image metadata scrubber. Will remove EXIF, XMP and IPTC metadata.

Rust Lean Image Viewer - Fast and configurable image viewer inspired by JPEGView by David Kleiner
Rust Lean Image Viewer - Fast and configurable image viewer inspired by JPEGView by David Kleiner

Rust Lean Image Viewer - Fast and configurable image viewer inspired by JPEGView by David Kleiner

mico (minimalistic config file format) encoder and decoder

mico This library implements a parser and emitter for mico (minimalistic config file format). Format example: Name: mico Description: minimalistic con

Image processing proxy and API, created to allow faster media delivery for the Holaplex storefront.

Description imgopt is an image processing proxy with a very simple API, created to download and dynamically scaledown, convert, and cache different me

Owner
Dimitrii Lopanov
Golang dev (computer vision / telemetry) Mail: [email protected] Telegram: https://t.me/sexyk
Dimitrii Lopanov
😱 Dead fast thumbnail library for browser and NodeJs! Built with Rust 🦀 and WebAssembly 🕸

thumbo-core ?? Dead fast thumbnail library for browser and NodeJs Built with Rust ?? & WebAssembly ?? ?? About thumbo-core is a thubnail library for b

Victor Aremu 12 Dec 2, 2022
Takes a folder of images (as a palette), and an image, and figures out how to tile the palette to resemble the image!

Takes a folder of images (as a palette), and an image, and figures out how to tile the palette to resemble the image!

Jacob 258 Dec 30, 2022
Encoding and decoding images in Rust

Image Maintainers: @HeroicKatora, @fintelia How to contribute An Image Processing Library This crate provides basic image processing functions and met

image-rs 3.5k Jan 9, 2023
Convert and save photomode screenshots from Red Dead Redemption 2 to JPEG format.

RDR2 Screenshot converter Convert and save photomode screenshots from Red Dead Redemption 2 to JPEG format. QuickStart Just download the executable fi

Timofey Gelazoniya 12 Sep 29, 2022
Classical Rainbow Triangle using Rust and Vulkan via vulkano bindings

Vulkano Rainbow Triangle Classical Rainbow Triangle using Rust and Vulkan via vulkano bindings. Based on the vulkano triangle example Quick Start $ ca

Tsoding 14 Dec 30, 2022
Lust is a static image server designed to automatically convert uploaded image to several formats and preset sizes

What is Lust? Lust is a static image server designed to automatically convert uploaded image to several formats and preset sizes with scaling in mind.

Harrison Burt 242 Dec 22, 2022
A linear algebra and mathematics library for computer graphics.

cgmath-rs A linear algebra and mathematics library for computer graphics. The library provides: vectors: Vector2, Vector3, Vector4 square matrices: Ma

rustgd 998 Jan 2, 2023
Signed distance field font and image command line tool based on OpenCL.

SDFTool Signed distance field font and image command line tool based on OpenCL. Build Windows Run cargo build --release in Visual Studio developer x64

弦语蝶梦 7 Oct 16, 2022
A programming language where comments are the first-class citizen and ASCII art flowcharts are the controls!

regretti ?? A programming language where comments are the first-class citizen and ASCII art flowcharts are the controls! Made for Lang Jam (jam0001) t

Mufeed VH 15 Dec 27, 2022
@Buildspace project creating a Web3 Solana Dapp with React and Rust

buildspace Solana GIF Portal Project Welcome ?? To get started with this course, clone this repo and follow these commands: Run npm install at the roo

Nick Fragakis 2 Jul 22, 2022