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 imagefloat ry;   // the height ratio of original image and resized imagestd::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 boxstd::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 textstd::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所在目录:

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/41324.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

大模型成为软件和数据工程师

前言 想象一下这样一个世界&#xff1a;人工智能伙伴负责编码工作&#xff0c;让软件和数据工程师释放他们的创造天赋来应对未来的技术挑战&#xff01; 想象一下&#xff1a;你是一名软件工程师&#xff0c;埋头于堆积如山的代码中&#xff0c;淹没在无数的错误中&#xff0…

基于React和TypeScript的开源白板项目(Github项目分享)

在学习前端开发的过程中&#xff0c;有时候我们需要一些有趣的项目来提升我们的技能。今天我要给大家介绍的是一个非常酷的项目——NinjaSketch&#xff0c;这是一个用React和TypeScript构建的简易白板工具。这个项目使用了Rough.js来实现手绘风格的效果。尽管这个应用不是响应…

【UE5.3】笔记8 添加碰撞,检测碰撞

添加碰撞 打开BP_Food,添加Box Collision组件&#xff0c;与unity类似&#xff1a; 调整Box Collision的大小到刚好包裹物体&#xff0c;通过调整缩放和盒体范围来控制大小&#xff0c;一般先调整缩放找个大概大小&#xff0c;然后调整盒体范围进行微调。 碰撞检测 添加好碰撞…

基于jeecgboot-vue3的Flowable流程-集成仿钉钉流程(二)增加基本的发起人审批与多用户多实例

因为这个项目license问题无法开源&#xff0c;更多技术支持与服务请加入我的知识星球。 1、AssigneeNode 增加approvalText public abstract class AssigneeNode extends Node {// 审批对象private AssigneeTypeEnum assigneeType;// 表单内人员private String formUser;// 表…

Python从0到100(三十七):数据提取的概念和数据分类

1. 爬虫中数据的分类 在爬虫开发过程中,我们会遇到多种类型的数据。了解这些数据的类型对于有效地提取和解析信息至关重要。 结构化数据 结构化数据是指具有固定格式和模式的数据,常见的结构化数据格式包括JSON和XML。 处理方式:可以直接转换为Python的字典或列表等数据类…

SCI一区级 | Matlab实现BO-Transformer-LSTM多特征分类预测/故障诊断

SCI一区级 | Matlab实现BO-Transformer-LSTM多特征分类预测/故障诊断 目录 SCI一区级 | Matlab实现BO-Transformer-LSTM多特征分类预测/故障诊断效果一览基本介绍程序设计参考资料 效果一览 基本介绍 1.【SCI一区级】Matlab实现BO-Transformer-LSTM特征分类预测/故障诊断&…

C语言 | Leetcode C语言题解之第214题最短回文串

题目&#xff1a; 题解&#xff1a; char* shortestPalindrome(char* s) {int n strlen(s);int fail[n 1];memset(fail, -1, sizeof(fail));for (int i 1; i < n; i) {int j fail[i - 1];while (j ! -1 && s[j 1] ! s[i]) {j fail[j];}if (s[j 1] s[i]) {f…

HTML【详解】超链接 a 标签的四大功能(页面跳转、页内滚动【锚点】、页面刷新、文件下载)

超链接 a 标签主要有以下功能&#xff1a; 跳转到其他页面 <a href"https://www.baidu.com/" target"_blank" >百度</a>href&#xff1a;目标页面的 url 地址或同网站的其他页面地址&#xff0c;如 detail.htmltarget&#xff1a;打开目标页面…

PLL和CDR的内部结构及其区别

比较PLL和CDR的内部结构及其区别&#xff1a; 基本结构&#xff1a; PLL&#xff08;相位锁定环&#xff09;&#xff1a; 相位检测器环路滤波器压控振荡器&#xff08;VCO&#xff09;分频器&#xff08;可选&#xff0c;用于频率合成&#xff09; CDR&#xff08;时钟数据恢复…

windows电脑网络重置后wifi列表消失怎么办?

我们的电脑网络偶尔会出现异常&#xff0c;我们通常会下意识选择网络诊断&#xff0c;运行完诊断后一般会让我们选择重置网络&#xff0c;然而&#xff0c;重置后wifi列表突然消失&#xff0c;无法愉快地上网了&#xff0c;找了一圈&#xff0c;都说是更改适配器选项&#xff0…

4、SSD主控

简述 主控是个片上系统&#xff0c;由硬件和固件组成一个功能完整的系统&#xff1b;上文所述的FTL就属于主控的固件范畴。主控闪存构成了整个SSD&#xff0c;在闪存确定的情况下&#xff0c;主控就反映了各家SSD的差异。实时上各家SSD的差异也主要反应在主控上&#xff0c;毕…

小学英语语法

目录 a和an的用法名词的单复数be动词和人称代词&#xff08;主格&#xff09;指示代词形容词物主代词名词所有格双重所有格方位介词some&#xff0c;any和no的用法How many和How much的用法情态动词can的用法祈使句人称代词&#xff08;宾格&#xff09;常见实义动词的用法一般…

【Odoo开源ERP】别把ERP与进销存软件混为一谈

导读&#xff1a;企业使用ERP软件能够实现管理升级&#xff0c;多方信息集成&#xff0c;按照既定策略逻辑运算&#xff0c;生成计划建议&#xff0c;减少人力成本&#xff0c;提高准确率的同时提高经营能力。 ERP&#xff0c;是MRP II的下一代软件&#xff0c;除了MRP II已有的…

项目一 nfs 共享服务器 Haproxy 代理 Keepalive 高可用集群

深入理解程序的数据存储 配置NFS服务器 配置ansible环境

满足GMSL静电防护要求的方案

什么是GMSL&#xff1f;它是做什么用的&#xff1f;它有什么优点&#xff1f;设计GMSL防静电有啥难度&#xff1f; 带着这些疑问我们先了解下什么是GMSL。 一&#xff0e;简述 GMSL GMSL&#xff08;Gigabit Multimedia Serial Link&#xff09;即千兆多媒体串行链路&#xf…

每日复盘-20240705

今日关注&#xff1a; 20240705 六日涨幅最大: ------1--------300391--------- 长药控股 五日涨幅最大: ------1--------300391--------- 长药控股 四日涨幅最大: ------1--------300391--------- 长药控股 三日涨幅最大: ------1--------300391--------- 长药控股 二日涨幅最…

【qt】如何通过域名获得IP地址?

域名是什么呢?像www.baidu.com的baidu.com就是域名. 域名相当于是网站的门牌号. 域名可以通过 DNS 解析将其转换为对应的 IP 地址. 用我们获取IP地址的方式就可以,但是现在没有可以用另一种方法. 槽函数的实现: void MainWindow::lookupHost(const QHostInfo &hostInf…

c++重定向输出和输出(竞赛讲解)

1.命令行重定向 在命令行中指定输出文件 指令 .\重定向学习.exe > 1.txt 效果 命令行输入和输出 指令 .\重定向学习.exe < 2.txt > 1.txt 效果 代码 #include<bits/stdc++.h> using namespace std; int n; int main(){cin>>n;for(int i=0;i<n;i…

Docker:二、常用命令

&#x1f341;docker常用命令 官方帮助文档&#xff1a;https://docs.docker.com/reference/ &#x1f332;帮助命令&#xff08;版本信息&#xff09; docker -v # 显示docker版本 docker version # 显示docker版本信息 docker info # 显示docker系统信息 docker 命…

信号量(semaphore)

一、信号量简介 前面介绍的消息队列主要用于传输数据&#xff1a;任务与任务之间、任务与中断之间 在有些情况下&#xff0c;不需要传输数据&#xff0c;只需要传递状态即可 • 车开出停车位&#xff0c;你的车可以停进来了 • 课已经录制完成&#xff0c;你可以进行观看了 1.…