YOLOV8 C++ opecv_dnn模块部署

废话不多说:opencv>=4.7.0

opencv编译不做解释,需要的话翻看别的博主的编译教程

代码饱含V5,V7,V8部署内容

头文件yoloV8.h

#pragma once
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
using namespace cv::dnn;
struct Detection
{int class_id{ 0 };//结果类别idfloat confidence{ 0.0 };//结果置信度cv::Rect box{};//矩形框
};
class Yolo {
public:bool readModel(cv::dnn::Net& net, std::string& netPath, bool isCuda);void drawPred(cv::Mat& img, std::vector<Detection> result, std::vector<cv::Scalar> color);virtual	vector<Detection> Detect(cv::Mat& SrcImg, cv::dnn::Net& net) = 0;float sigmoid_x(float x) { return static_cast<float>(1.f / (1.f + exp(-x))); }Mat formatToSquare(const cv::Mat& source){int col = source.cols;int row = source.rows;int _max = MAX(col, row);cv::Mat result = cv::Mat::zeros(_max, _max, CV_8UC3);source.copyTo(result(cv::Rect(0, 0, col, row)));return result;}const int netWidth = 640;   //ONNX图片输入宽度const int netHeight = 640;  //ONNX图片输入高度float modelConfidenceThreshold{ 0.0 };float modelScoreThreshold{ 0.0 };float modelNMSThreshold{ 0.0 };std::vector<std::string> classes = { "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" };
};class Yolov5 :public Yolo {
public:vector<Detection> Detect(Mat& SrcImg, Net& net);
private:float confidenceThreshold{ 0.25 };float nmsIoUThreshold{ 0.45 };
};class Yolov7 :public Yolo {
public:vector<Detection> Detect(Mat& SrcImg, Net& net);
private:float confidenceThreshold{ 0.25 };float nmsIoUThreshold{ 0.45 };const int strideSize = 3;   //stride sizeconst float netStride[4] = { 8.0, 16.0, 32.0, 64.0 };const float netAnchors[3][6] = { {12, 16, 19, 36, 40, 28},{36, 75, 76, 55, 72, 146},{142, 110, 192, 243, 459, 401} }; //yolov7-P5 anchors
};class Yolov8 :public Yolo {
public:vector<Detection> Detect(Mat& SrcImg, Net& net);
private:float confidenceThreshold{ 0.25 };float nmsIoUThreshold{ 0.70 };
};

源文件yoloV8.cpp:

#include"yoloV8.h"bool Yolo::readModel(Net& net, string& netPath, bool isCuda = false) {try {net = readNetFromONNX(netPath);}catch (const std::exception&) {return false;}if (isCuda) {net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);}else {net.setPreferableBackend(cv::dnn::DNN_BACKEND_DEFAULT);net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);}return true;
}void Yolo::drawPred(Mat& img, vector<Detection> result, vector<Scalar> colors) {for (int i = 0; i < result.size(); ++i){Detection detection = result[i];cv::Rect box = detection.box;cv::Scalar color = colors[detection.class_id];// Detection boxcv::rectangle(img, box, color, 2);// Detection box textstd::string classString = classes[detection.class_id] + ' ' + std::to_string(detection.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(img, textBox, color, cv::FILLED);cv::putText(img, classString, cv::Point(box.x + 5, box.y - 10), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0, 0, 0), 2, 0);}
}//vector<Detection> Yolov5::Detect(Mat& img, Net& net) {
//
//	img = formatToSquare(img);
//	cv::Mat blob;
//	cv::dnn::blobFromImage(img, blob, 1.0 / 255.0, Size(netWidth, netHeight), cv::Scalar(), true, false);
//	net.setInput(blob);
//
//	std::vector<cv::Mat> outputs;
//	net.forward(outputs, net.getUnconnectedOutLayersNames());
//
//
//
//	float* pdata = (float*)outputs[0].data;
//	float x_factor = (float)img.cols / netWidth;
//	float y_factor = (float)img.rows / netHeight;
//
//	std::vector<int> class_ids;
//	std::vector<float> confidences;
//	std::vector<cv::Rect> boxes;
//
//	// yolov5 has an output of shape (batchSize, 25200, 85) (Num classes + box[x,y,w,h] + confidence[c])
//	int rows = outputs[0].size[1];
//	int dimensions = outputs[0].size[2];
//
//	for (int i = 0; i < rows; ++i)
//	{
//		float confidence = pdata[4];
//		if (confidence >= modelConfidenceThreshold)
//		{
//
//			cv::Mat scores(1, classes.size(), CV_32FC1, pdata + 5);
//			cv::Point class_id;
//			double max_class_score;
//
//			minMaxLoc(scores, 0, &max_class_score, 0, &class_id);
//
//			if (max_class_score > modelScoreThreshold)
//			{
//				confidences.push_back(confidence);
//				class_ids.push_back(class_id.x);
//
//				float x = pdata[0];
//				float y = pdata[1];
//				float w = pdata[2];
//				float h = pdata[3];
//
//				int left = int((x - 0.5 * w) * x_factor);
//				int top = int((y - 0.5 * h) * y_factor);
//
//				int width = int(w * x_factor);
//				int height = int(h * y_factor);
//
//				boxes.push_back(cv::Rect(left, top, width, height));
//			}
//		}
//		pdata += dimensions;
//	}
//
//	vector<int> nms_result;
//	NMSBoxes(boxes, confidences, confidenceThreshold, nmsIoUThreshold, nms_result);
//	vector<Detection> detections{};
//	for (unsigned long i = 0; i < nms_result.size(); ++i) {
//		int idx = nms_result[i];
//		Detection result;
//		result.class_id = class_ids[idx];
//		result.confidence = confidences[idx];
//		result.box = boxes[idx];
//		detections.push_back(result);
//	}
//	return detections;
//}
//
//vector<Detection> Yolov7::Detect(Mat& SrcImg, Net& net) {
//	Mat blob;
//	int col = SrcImg.cols;
//	int row = SrcImg.rows;
//	int maxLen = MAX(col, row);
//	Mat netInputImg = SrcImg.clone();
//	if (maxLen > 1.2 * col || maxLen > 1.2 * row) {
//		Mat resizeImg = Mat::zeros(maxLen, maxLen, CV_8UC3);
//		SrcImg.copyTo(resizeImg(Rect(0, 0, col, row)));
//		netInputImg = resizeImg;
//	}
//	vector<Ptr<Layer> > layer;
//	vector<string> layer_names;
//	layer_names = net.getLayerNames();
//	blobFromImage(netInputImg, blob, 1 / 255.0, cv::Size(netWidth, netHeight), cv::Scalar(0, 0, 0), true, false);
//	net.setInput(blob);
//	std::vector<cv::Mat> netOutput;
//	net.forward(netOutput, net.getUnconnectedOutLayersNames());
//#if CV_VERSION_MAJOR==4 && CV_VERSION_MINOR>6
//	std::sort(netOutput.begin(), netOutput.end(), [](Mat& A, Mat& B) {return A.size[2] > B.size[2]; });//opencv 4.6 三个output顺序为40 20 80,之前版本的顺序为80 40 20 
//#endif
//	std::vector<int> class_ids;//结果id数组
//	std::vector<float> confidences;//结果每个id对应置信度数组
//	std::vector<cv::Rect> boxes;//每个id矩形框
//	float ratio_h = (float)netInputImg.rows / netHeight;
//	float ratio_w = (float)netInputImg.cols / netWidth;
//	int net_width = classes.size() + 5;  //输出的网络宽度是类别数+5
//	for (int stride = 0; stride < strideSize; stride++) {    //stride
//		float* pdata = (float*)netOutput[stride].data;
//		int grid_x = (int)(netWidth / netStride[stride]);
//		int grid_y = (int)(netHeight / netStride[stride]);
//		// cv::Mat tmp(grid_x * grid_y * 3, classes.size() + 5, CV_32FC1, pdata);
//		for (int anchor = 0; anchor < 3; anchor++) {	//anchors
//			const float anchor_w = netAnchors[stride][anchor * 2];
//			const float anchor_h = netAnchors[stride][anchor * 2 + 1];
//			for (int i = 0; i < grid_y; i++) {
//				for (int j = 0; j < grid_x; j++) {
//					float confidence = sigmoid_x(pdata[4]); ;//获取每一行的box框中含有物体的概率
//					cv::Mat scores(1, classes.size(), CV_32FC1, pdata + 5);
//					Point classIdPoint;
//					double max_class_socre;
//					minMaxLoc(scores, 0, &max_class_socre, 0, &classIdPoint);
//					max_class_socre = sigmoid_x(max_class_socre);
//					if (max_class_socre * confidence >= confidenceThreshold) {
//						float x = (sigmoid_x(pdata[0]) * 2.f - 0.5f + j) * netStride[stride];  //x
//						float y = (sigmoid_x(pdata[1]) * 2.f - 0.5f + i) * netStride[stride];   //y
//						float w = powf(sigmoid_x(pdata[2]) * 2.f, 2.f) * anchor_w;   //w
//						float h = powf(sigmoid_x(pdata[3]) * 2.f, 2.f) * anchor_h;  //h
//						int left = (int)(x - 0.5 * w) * ratio_w + 0.5;
//						int top = (int)(y - 0.5 * h) * ratio_h + 0.5;
//						class_ids.push_back(classIdPoint.x);
//						confidences.push_back(max_class_socre * confidence);
//						boxes.push_back(Rect(left, top, int(w * ratio_w), int(h * ratio_h)));
//					}
//					pdata += net_width;//下一行
//				}
//			}
//		}
//	}
//
//	//执行非最大抑制以消除具有较低置信度的冗余重叠框(NMS)
//	vector<int> nms_result;
//	NMSBoxes(boxes, confidences, confidenceThreshold, nmsIoUThreshold, nms_result);
//	vector<Detection> detections{};
//	for (unsigned long i = 0; i < nms_result.size(); ++i) {
//		int idx = nms_result[i];
//		Detection result;
//		result.class_id = class_ids[idx];
//		result.confidence = confidences[idx];
//		result.box = boxes[idx];
//		detections.push_back(result);
//	}
//	return detections;
//}vector<Detection> Yolov8::Detect(Mat& modelInput, Net& net) {modelInput = formatToSquare(modelInput);cv::Mat blob;cv::dnn::blobFromImage(modelInput, blob, 1.0 / 255.0, Size(netWidth, netHeight), cv::Scalar(), true, false);net.setInput(blob);std::vector<cv::Mat> outputs;net.forward(outputs, net.getUnconnectedOutLayersNames());// yolov8 has an output of shape (batchSize, 84,  8400) (Num classes + box[x,y,w,h])int rows = outputs[0].size[2];int dimensions = outputs[0].size[1];outputs[0] = outputs[0].reshape(1, dimensions);cv::transpose(outputs[0], outputs[0]);float* data = (float*)outputs[0].data;// Mat detect_output(8400, 84, CV_32FC1, data);// 8400 = 80*80+40*40+20*20float x_factor = (float)modelInput.cols / netWidth;float y_factor = (float)modelInput.rows / netHeight;std::vector<int> class_ids;std::vector<float> confidences;std::vector<cv::Rect> boxes;for (int i = 0; i < rows; ++i){cv::Mat scores(1, classes.size(), CV_32FC1, data + 4);cv::Point class_id;double maxClassScore;minMaxLoc(scores, 0, &maxClassScore, 0, &class_id);if (maxClassScore > modelConfidenceThreshold){confidences.push_back(maxClassScore);class_ids.push_back(class_id.x);float x = data[0];float y = data[1];float w = data[2];float h = data[3];int left = int((x - 0.5 * w) * x_factor);int top = int((y - 0.5 * h) * y_factor);int width = int(w * x_factor);int height = int(h * y_factor);boxes.push_back(cv::Rect(left, top, width, height));}data += dimensions;}//执行非最大抑制以消除具有较低置信度的冗余重叠框(NMS)vector<int> nms_result;NMSBoxes(boxes, confidences, confidenceThreshold, nmsIoUThreshold, nms_result);vector<Detection> detections{};for (unsigned long i = 0; i < nms_result.size(); ++i) {int idx = nms_result[i];Detection result;result.class_id = class_ids[idx];result.confidence = confidences[idx];result.box = boxes[idx];detections.push_back(result);}return detections;
}

main.CPP

#include "yoloV8.h"
#include <iostream>
#include<opencv2//opencv.hpp>
#include<math.h>#define USE_CUDA false //use opencv-cudausing namespace std;
using namespace cv;
using namespace dnn;int main()
{string img_path = "./bus.jpg";string model_path3 = "./yolov8n.onnx";Mat img = imread(img_path);vector<Scalar> color;srand(time(0));for (int i = 0; i < 80; i++) {int b = rand() % 256;int g = rand() % 256;int r = rand() % 256;color.push_back(Scalar(b, g, r));}/*Yolov5 yolov5; Net net1;Mat img1 = img.clone();bool isOK = yolov5.readModel(net1, model_path1, USE_CUDA);if (isOK) {cout << "read net ok!" << endl;}else {cout << "read onnx model failed!";return -1;}vector<Detection> result1 = yolov5.Detect(img1, net1);yolov5.drawPred(img1, result1, color);Mat dst = img1({ 0, 0, img.cols, img.rows });imwrite("results/yolov5.jpg", dst);Yolov7 yolov7; Net net2;Mat img2 = img.clone();isOK = yolov7.readModel(net2, model_path2, USE_CUDA);if (isOK) {cout << "read net ok!" << endl;}else {cout << "read onnx model failed!";return -1;}vector<Detection> result2 = yolov7.Detect(img2, net2);yolov7.drawPred(img2, result2, color);dst = img2({ 0, 0, img.cols, img.rows });imwrite("results/yolov7.jpg", dst);*/Yolov8 yolov8; Net net3;Mat img3 = img.clone();bool isOK = yolov8.readModel(net3, model_path3, USE_CUDA);if (isOK) {cout << "read net ok!" << endl;}else {cout << "read onnx model failed!";return -1;}vector<Detection> result3 = yolov8.Detect(img3, net3);yolov8.drawPred(img3, result3, color);Mat dst = img3({ 0, 0, img.cols, img.rows });cv::imshow("aaa", dst);imwrite("./yolov8.jpg", dst);cv::waitKey(0);return 0;
}

opencv编译需要时间久,GPU版本可以达到实时,有问题先尝试解决,搞定不了私信留言。

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

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

相关文章

【Less-CSS】初识Less,使编写 CSS 变得简洁

初识Less&#xff0c;使编写 CSS 变得简洁 1.Less简述2.LESS 原理及使用方式3.示例4.less语法5.Easy Less插件 作为一门标记性语言&#xff0c;CSS 的语法相对简单&#xff0c;对使用者的要求较低&#xff0c;但同时也带来一些问题&#xff1a;CSS 需要书写大量看似没有逻辑的代…

Linux系统编程——线程的学习

学习参考博文&#xff1a; Linux多线程编程初探 Linux系统编程学习相关博文 Linux系统编程——文件编程的学习Linux系统编程——进程的学习Linux系统编程——进程间通信的学习Linux系统编程——网络编程的学习 Linux系统编程——线程的学习 一、概述1. 进程与线程的区别2. 使…

Python爬虫从端到端抓取网页

网页抓取和 REST API 简介 网页抓取是使用计算机程序以自动方式从网站提取和解析数据的过程。这是创建用于研究和学习的数据集的有用技术。虽然网页抓取通常涉及解析和处理 HTML 文档&#xff0c;但某些平台还提供 REST API 来以机器可读格式&#xff08;如 JSON&#xff09;检…

【C++】C++ 类中的 this 指针用法 ③ ( 全局函数 与 成员函数 相互转化 | 有参构造函数设置默认参数值 | 返回匿名对象与返回引用 )

文章目录 一、全局函数 与 成员函数 相互转化1、成员函数转为全局函数 - 多了一个参数2、全局函数转为成员函数 - 通过 this 指针隐藏操作数 二、有参构造函数设置默认参数值三、返回匿名对象与返回引用四、完整代码示例 一、全局函数 与 成员函数 相互转化 1、成员函数转为全局…

一、vue2的基础语法巩固

一、定义&#xff1a;是一个渐进式的JavaScript框架 二、特点&#xff1a; 减少了大量的DOM操作编写 &#xff0c;可以更专注于逻辑操作分离数据和界面的呈现&#xff0c;降低了代码耦合度(前端端分离)支持组件化开发&#xff0c;更利于中大型项目的代码组织 vue2核心功能&a…

【Linux】生产消费模型 + 线程池

文章目录 &#x1f4d6; 前言1. 生产消费模型2. 阻塞队列2.1 成员变量&#xff1a;2.2 入队(push)和出队(pop)&#xff1a;2.3 封装与测试运行&#xff1a;2.3 - 1 对代码进一步封装2.3 - 2 分配运算任务2.3 - 3 测试与运行 3. 循环阻塞队列3.1 POSIX信号量&#xff1a;3.1 - 1…

Python 解释器配置需要注意什么?

Python是一种广泛使用的编程语言&#xff0c;被用于开发各种类型的软件应用程序。在Python中&#xff0c;解释器是负责将Python代码转换为机器语言的程序。 因此&#xff0c;正确配置Python解释器是非常重要的&#xff0c;这有助于提高代码的性能、可读性和可维护性。下面将探…

vue3中使用editor.js

第一步安装依赖 npm i editorjs/editorjs --save 第二步创建editor.vue插件 <template><div><div id"editorjs" :style"width: props.width px;height: props.height px;"></div></div> </template> <scrip…

WKB近似

WKB方法用于研究一种特定类型的微分方程的全局性质 很有用这种特定的微分方程形如&#xff1a; 经过一些不是特别复杂的推导&#xff0c;我们可以得到他的WKB近似解。 该近似解的选择取决于函数和参数的性质同时&#xff0c;我们默认函数的定义域为当恒大于零,时&#xff1a; 当…

44.java教程

目录 一、Java 教程。 &#xff08;1&#xff09;我的第一个 JAVA 程序。 &#xff08;2&#xff09;Java 简介。 &#xff08;2.1&#xff09;java简介。 &#xff08;2.2&#xff09;主要特性。 &#xff08;2.3&#xff09;发展历史。 &#xff08;2.4&#xff09;J…

iOS应用程序的签名、重签名和安装测试

目录 前言 打开要处理的IPA文件 设置签名使用的证书和描述文件 开始ios ipa重签名 前言 ipa编译出来后&#xff0c;或者ipa进行修改后&#xff0c;需要进行重新签名才能安装到测试手机&#xff0c;或者提交app store供apple 商店审核上架。ipaguard有签名和重签名功能&…

吴恩达ChatGPT《Finetuning Large Language Models》笔记

课程地址&#xff1a;https://learn.deeplearning.ai/finetuning-large-language-models/lesson/1/introduction Introduction 动机&#xff1a;虽然编写提示词&#xff08;Prompt&#xff09;可以让LLM按照指示执行任务&#xff0c;比如提取文本中的关键词&#xff0c;或者对…

React中setState的原理及深层理解

1.为什么使用setState React并没有实现类似于Vue2中的Object.defineProperty或者Vue3中的Proxy的方式来监听数据的变化 我们必须通过setState来告知React数据已经发生了变化 setState方法是从Component中继承过来的。 2.setState异步更新 setState设计为异步&#xff0c;可…

PHY6230低成本遥控灯控芯片国产蓝牙BLE5.2 2.4G SoC

高性价比的低功耗高性能蓝牙5.2系统级芯片&#xff0c;适用多种PC/手机外设连接场景。 高性能多模射频收发机&#xff1a; 通过硬件模块的充分复用实现高性能多模数字收发机。发射机&#xff0c;最大发射功率10dBm&#xff1b;BLE 1Mbps速率接收机灵敏度达到-96dBm&#xff1…

解决Vue设置图片的动态src不生效的问题

一、问题描述 在vue项目中&#xff0c;想要动态设置img的src时&#xff0c;此时发现图片会加载失败。在Vue代码中是这样写的&#xff1a; 在Vue的data中是这样写的&#xff1a; 我的图片在根目录下的static里面&#xff1a; 但是在页面上这个图片却无法加载出来。 二、解决方案…

五、核支持向量机算法(NuSVC,Nu-Support Vector Classification)(有监督学习)

和支持向量分类(Nu-Support Vector Classification)&#xff0c;与 SVC 类似&#xff0c;但使用一个参数来控制支持向量的数量&#xff0c;其实现基于libsvm 一、算法思路 本质都是SVM中的一种优化&#xff0c;原理都类似&#xff0c;详细算法思路可以参考博文&#xff1a;三…

10分钟让你拿下Linux常用命令,网安运维测试人员必掌握!

文章目录 一、目录操作 1、批量操作 二、文件操作三、文件内容操作&#xff08;查看日志&#xff0c;更改配置文件&#xff09; 1、grep(检索文件内容)2、awk(数据统计)3、sed(替换文件内容)4、管道操作符|5、cut(数据裁剪) 四、系统日志位置五、创建与删除软连接六、压缩和解压…

虹科案例 | ELPRO帮助客户实现符合GDP标准的温度监测和高效的温度数据管理

文章来源&#xff1a;虹科环境监测技术 点击阅读原文&#xff1a;https://mp.weixin.qq.com/s/wwIPx_GK3ywqWr5BABC4KQ 在本案例研究中&#xff0c;虹科ELPRO帮助客户 ● 实施了温度监测解决方案&#xff0c;以一致的数据结构获取各国和各种运输方式的数据; ● 通过将温度数据上…

https跳过SSL认证时是不是就是不加密的,相当于http?

https跳过SSL认证时是不是就是不加密的,相当于http?&#xff0c;其实不是&#xff0c;HTTPS跳过SSL认证并不相当于HTTP&#xff0c;也不意味着没有加密。请注意以下几点&#xff1a; HTTPS&#xff08;Hypertext Transfer Protocol Secure&#xff09;本质上是在HTTP的基础上…

【postgresql】ERROR: column “xxxx.id“ must appear in the GROUP BY

org.postgresql.util.PSQLException: ERROR: column "xxx.id" must appear in the GROUP BY clause or be used in an aggregate function 错误&#xff1a;列“XXXX.id”必须出现在GROUP BY子句中或在聚合函数中使用 在mysql中是正常使用的&#xff0c;在postgre…