C++ windows下使用openvino部署yoloV8

目录

准备版本:

准备事项:

选择配置界面:

下载界面:

​编辑  添加VS配置:

准备代码:

yolov8.h

yolov8.cpp

detect.cpp

如何找到并放置DLL: 


准备版本:

opencv 4.6.0

openvino 2024.0.0.14509

准备事项:

V8模型转换:  pt to xml

from ultralytics import YOLO

# Load a model
model = YOLO("./models\yolov8s.pt")  # load an official model

# Export the model
model.export(format="openvino")

 

openvino下载路径:点击跳转

选择配置界面:

下载界面:

  添加VS配置:

准备代码:

yolov8.h

#pragma once
#include<string>
#include <iostream>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include<openvino/openvino.hpp>
#include <fstream>
#include <vector>
#include <random>


struct Config {
	float confThreshold;
	float nmsThreshold;
	float scoreThreshold;
	int inpWidth;
	int inpHeight;
	std::string onnx_path;
};

struct Resize
{
	cv::Mat resized_image;
	int dw;
	int dh;
};

struct Detection {
	int class_id;
	float confidence;
	cv::Rect box;
};

class YOLOV8 {
public:
	YOLOV8(Config config);
	~YOLOV8();
	void detect(cv::Mat& frame);

private:
	float confThreshold;
	float nmsThreshold;
	float scoreThreshold;
	int inpWidth;
	int inpHeight;
	float rx;   // the width ratio of original image and resized image
	float ry;   // the height ratio of original image and resized image
	std::string onnx_path;
	Resize resize;
	ov::Tensor input_tensor;
	ov::InferRequest infer_request;
	ov::CompiledModel compiled_model;
	void initialmodel();
	void preprocess_img(cv::Mat& frame);
	void postprocess_img(cv::Mat& frame, float* detections, ov::Shape& output_shape);
};

yolov8.cpp

#include"yolov8.h"
#include<iostream>
#include<string>
#include<time.h>

using namespace cv;
using namespace std;
using namespace dnn;

const vector<string> coconame = { "person",
        "bicycle",
        "car",
        "motorcycle",
        "airplane",
        "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",
        "couch",
        "potted plant",
        "bed",
        "dining table",
        "toilet",
        "tv",
        "laptop",
        "mouse",
        "remote",
        "keyboard",
        "cell phone",
        "microwave",
        "oven",
        "toaster",
        "sink",
        "refrigerator",
        "book",
        "clock",
        "vase",
        "scissors",
        "teddy bear",
        "hair drier",
        "toothbrush" };

YOLOV8::YOLOV8(Config config) {
    this->confThreshold = config.confThreshold;
    this->nmsThreshold = config.nmsThreshold;
    this->scoreThreshold = config.scoreThreshold;
    this->inpWidth = config.inpWidth;
    this->inpHeight = config.inpHeight;
    this->onnx_path = config.onnx_path;
    this->initialmodel();

}
YOLOV8::~YOLOV8() {}
void YOLOV8::detect(Mat& frame) {
    preprocess_img(frame);
    infer_request.infer();
    const ov::Tensor& output_tensor = infer_request.get_output_tensor();
    ov::Shape output_shape = output_tensor.get_shape();
    float* detections = output_tensor.data<float>();
    this->postprocess_img(frame, detections, output_shape);
}

void YOLOV8::initialmodel() {
    ov::Core core;
    std::shared_ptr<ov::Model> model = core.read_model(this->onnx_path);
    ov::preprocess::PrePostProcessor ppp = ov::preprocess::PrePostProcessor(model);

    ppp.input().tensor().set_element_type(ov::element::u8).set_layout("NHWC").set_color_format(ov::preprocess::ColorFormat::RGB);
    ppp.input().preprocess().convert_element_type(ov::element::f32).convert_color(ov::preprocess::ColorFormat::RGB).scale({ 255, 255, 255 });// .scale({ 112, 112, 112 });
    ppp.input().model().set_layout("NCHW");
    ppp.output().tensor().set_element_type(ov::element::f32);
    model = ppp.build();
    this->compiled_model = core.compile_model(model, "CPU");
    this->infer_request = compiled_model.create_infer_request();
}

void YOLOV8::preprocess_img(Mat& frame) {
    try {
        float width = frame.cols;
        float height = frame.rows;
        cv::Size new_shape = cv::Size(inpWidth, inpHeight);
        float r = float(new_shape.width / max(width, height));
        int new_unpadW = int(round(width * r));
        int new_unpadH = int(round(height * r));

        cv::resize(frame, resize.resized_image, cv::Size(new_unpadW, new_unpadH), 0, 0, cv::INTER_AREA);
        resize.dw = new_shape.width - new_unpadW;
        resize.dh = new_shape.height - new_unpadH;
        cv::Scalar color = cv::Scalar(100, 100, 100);
        cv::copyMakeBorder(resize.resized_image, resize.resized_image, 0, resize.dh, 0, resize.dw, cv::BORDER_CONSTANT, color);

        this->rx = (float)frame.cols / (float)(resize.resized_image.cols - resize.dw);
        this->ry = (float)frame.rows / (float)(resize.resized_image.rows - resize.dh);
        float* input_data = (float*)resize.resized_image.data;
        input_tensor = ov::Tensor(compiled_model.input().get_element_type(), compiled_model.input().get_shape(), input_data);
        infer_request.set_input_tensor(input_tensor);
    }
    catch (const std::exception& e) {
        std::cerr << "exception: " << e.what() << std::endl;
    }
    catch (...) {
        std::cerr << "unknown exception" << std::endl;
    }

}

void YOLOV8::postprocess_img(Mat& frame, float* detections, ov::Shape& output_shape) {
    std::vector<cv::Rect> boxes;
    vector<int> class_ids;
    vector<float> confidences;
    int out_rows = output_shape[1];
    int out_cols = output_shape[2];
    const cv::Mat det_output(out_rows, out_cols, CV_32F, (float*)detections);

    for (int i = 0; i < det_output.cols; ++i) {
        const cv::Mat classes_scores = det_output.col(i).rowRange(4, 84);
        cv::Point class_id_point;
        double score;
        cv::minMaxLoc(classes_scores, nullptr, &score, nullptr, &class_id_point);

        if (score > 0.3) {
            const float cx = det_output.at<float>(0, i);
            const float cy = det_output.at<float>(1, i);
            const float ow = det_output.at<float>(2, i);
            const float oh = det_output.at<float>(3, i);
            cv::Rect box;
            box.x = static_cast<int>((cx - 0.5 * ow));
            box.y = static_cast<int>((cy - 0.5 * oh));
            box.width = static_cast<int>(ow);
            box.height = static_cast<int>(oh);

            boxes.push_back(box);
            class_ids.push_back(class_id_point.y);
            confidences.push_back(score);
        }
    }

    std::vector<int> nms_result;
    cv::dnn::NMSBoxes(boxes, confidences, this->scoreThreshold, this->nmsThreshold, nms_result);

    std::vector<Detection> output;
    for (int i = 0; i < nms_result.size(); i++)
    {
        Detection result;
        int idx = nms_result[i];
        result.class_id = class_ids[idx];
        result.confidence = confidences[idx];
        result.box = boxes[idx];
        output.push_back(result);
    }
    cout << "output_size:" << output.size() << endl;

    for (int i = 0; i < output.size(); i++)
    {
        auto detection = output[i];
        auto box = detection.box;
        auto classId = detection.class_id;
        // if (classId != 0) continue;
        auto confidence = detection.confidence;

        box.x = this->rx * box.x;
        box.y = this->ry * box.y;
        box.width = this->rx * box.width;
        box.height = this->ry * box.height;

        float xmax = box.x + box.width;
        float ymax = box.y + box.height;

        // detection box
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<int> dis(100, 255);
        cv::Scalar color = cv::Scalar(dis(gen),
            dis(gen),
            dis(gen));
        cv::rectangle(frame, cv::Point(box.x, box.y), cv::Point(xmax, ymax), color, 3);

        // Detection box text
        std::string classString = coconame[classId] + ' ' + std::to_string(confidence).substr(0, 4);
        cv::Size textSize = cv::getTextSize(classString, cv::FONT_HERSHEY_DUPLEX, 1, 2, 0);
        cv::Rect textBox(box.x, box.y - 40, textSize.width + 10, textSize.height + 20);
        cv::rectangle(frame, textBox, color, cv::FILLED);
        cv::putText(frame, classString, cv::Point(box.x + 5, box.y - 10), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0, 0, 0), 2, 0);

        // cv::rectangle(frame, cv::Point(box.x, box.y - 20), cv::Point(xmax, box.y), cv::Scalar(0, 255, 0), cv::FILLED);
        // cv::putText(frame, coconame[classId], cv::Point(box.x, box.y - 5), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
    }
}

detect.cpp

# include"yolov8.h"

int main(int argc, char* argv[]) {

    try {
        //if (argc != 3) {
        //    std::cout << "Usage:" << argv[0] << " <path_to_model> <path_to_image>" << std::endl;
        //    return EXIT_FAILURE;
        //}

        //const std::string input_model_path{ argv[1] };
        //const std::string input_image_path{ argv[2] };
        std::string input_model_path = "E:\\yoloV8\\ultralytics-main\\models\\yolov8s_openvino_model\\yolov8s.xml";
        std::string input_image_path = "E:\\yoloV8\\ultralytics-main\\ultralytics\\assets\\bus.jpg";
        Config config = { 0.2,0.4,0.4,640,640, input_model_path };
        clock_t start, end;
        cv::Mat img = cv::imread(input_image_path);

        YOLOV8 yolomodel(config);
        start = clock();
        yolomodel.detect(img);
        end = clock();
        std::cout << "infer time = " << double(end - start) / CLOCKS_PER_SEC << "s" << std::endl;
        cv::imwrite("./result.jpg", img);
    }
    catch (const std::exception& ex) {
        std::cerr << ex.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;

}

如何找到并放置DLL: 

为了防止程序运行缺少dll  可以把dll全部拷贝到程序输出所在目录里 也就是exe所在目录

dll所在目录:

 

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: YOLOv5是一种基于深度学习的目标检测算法,而OpenVINO是英特尔开发的用于神经网络模型优化和部署的工具集。 首先,YOLOv5可以在训练过程中生成模型权重,这些权重包含了检测目标的特征信息。然后,使用OpenVINO可以将YOLOv5训练得到的模型进行优化和部署。 在YOLOv5 c OpenVINO部署过程中,首先需要将YOLOv5的模型转换为OpenVINO支持的IR(Intermediate Representation)格式。这可以通过OpenVINO提供的Model Optimizer工具来完成,该工具可以将YOLOv5模型的权重和配置文件转换为OpenVINO可用的中间表示格式。 转换完成后,就可以使用OpenVINO进行模型的部署OpenVINO提供了一系列可以用于优化和加速神经网络的计算库和工具。例如,可以使用OpenVINO的Inference Engine库来加载和运行转换后的模型,并利用英特尔的硬件加速功能提高推理速度和效率。 此外,OpenVINO还提供了一些用于适配不同硬件平台的示例代码和优化技术。例如,可以使用OpenVINO的Hardware-Aware Optimizations工具来针对特定的硬件平台进行优化,以实现更好的性能表现。 总结来说,YOLOv5 c OpenVINO部署是将基于深度学习的目标检测算法YOLOv5转换为OpenVINO支持的中间表示格式,并使用OpenVINO进行模型的优化和部署。通过利用OpenVINO提供的硬件加速和优化技术,可以提高模型的推理速度和效率。 ### 回答2: YOLOv5是一个用于目标检测的深度学习模型,而OpenVINO是一种用于模型部署和优化的开源工具包。将YOLOv5模型部署OpenVINO中,可以提高模型的推理性能并适应不同的硬件环境。 首先,要将YOLOv5模型转换为OpenVINO支持的IR格式。IR(中间表示)格式是一种中间表达,能够将深度学习模型转换为可在不同硬件上执行的优化形式。可以使用OpenVINO提供的Model Optimizer工具来进行模型转换。该工具将根据模型的结构和权重生成IR文件。 接下来,在部署模型之前,需要选择适当的推理引擎。OpenVINO提供了多种推理引擎,例如CPU、GPU、VPU等。根据硬件环境的特性选择最优的推理引擎。 在进行实际的部署前,需要编写一个推理脚本来加载IR文件并执行推理操作。脚本需要指定输入图像、处理结果以及模型的基本参数,例如置信度阈值、IOU阈值等。可以使用OpenVINO提供的Python API来编写推理脚本。 最后,可以在硬件设备上运行推理脚本来进行目标检测。通过OpenVINO的优化,模型的推理速度可以得到明显的提升,并且可以在不同硬件环境中进行部署,如服务器、边缘设备等。 总之,将YOLOv5模型部署OpenVINO需要进行模型转换、选择推理引擎、编写推理脚本等步骤。这样可以提高模型的推理性能,并使其适应不同的硬件环境。 ### 回答3: YOLOv5是一个流行的目标检测算法,其在计算机视觉领域具有广泛的应用。OpenVINO是英特尔开发的一个工具套件,用于优化和部署深度学习模型。 YOLOv5-C是YOLOv5系列中的一个变种,其相对较小而轻量化,适合在资源受限的设备上进行部署OpenVINO可以用于将训练好的YOLOv5-C模型进行加速和优化,并将其部署到不同的设备上。 在使用OpenVINO部署YOLOv5-C模型时,首先需要使用OpenVINO的Model Optimizer工具将模型转换为OpenVINO可识别的格式。这个工具可以自动进行网络层级别的优化和压缩,以减少模型的大小和计算量。 转换完成后,可以使用OpenVINO的Inference Engine进行模型推理。Inference Engine是一个优化的推理引擎,可以在各种硬件设备上高效地运行深度学习模型。它提供了API和示例代码,使得在不同平台上进行部署变得更加简单和便捷。 通过使用OpenVINO部署YOLOv5-C模型,可以获得更高的推理性能和更低的延迟。这对于一些应用场景,如实时目标检测和视频分析,非常重要。此外,OpenVINO还支持边缘设备、嵌入式系统和云计算平台,使得模型可以在多种场景下灵活部署和应用。 总而言之,使用OpenVINO部署YOLOv5-C模型可以实现对模型的优化和加速,使得在各种设备上实现高效的目标检测应用成为可能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芝士是只猫

开源使得世界变得更美丽

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值