使用opencv4.7.0部署yolov5

news/2024/7/10 22:47:06 标签: YOLO

yolov5原理和部署原理就不说了,想了解的可以看看这篇部署原理文章

#include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

//using namespace cv;
//using namespace dnn;
//using namespace std;
int index = 0;


struct Net_config
{
	float confThreshold; // Confidence threshold
	float nmsThreshold;  // Non-maximum suppression threshold
	float objThreshold;  //Object Confidence threshold
	std::string modelpath;
};

int endsWith(std::string s, std::string sub) {
	return s.rfind(sub) == (s.length() - sub.length()) ? 1 : 0;
}


class YOLO
{
public:
	YOLO(Net_config config);
	std::tuple<std::vector<cv::Rect>, std::vector<int>> detect(cv::Mat& frame);
private:
	float* anchors;
	int num_stride;
	int inpWidth;
	int inpHeight;
	std::vector<std::string> class_names;
	int num_class;
	
	float confThreshold;
	float nmsThreshold;
	float objThreshold;
	const bool keep_ratio = true;
	cv::dnn::Net net;
	void drawPred(float conf, int left, int top, int right, int bottom, cv::Mat& frame, int classid);
	cv::Mat resize_image(cv::Mat srcimg, int *newh, int *neww, int *top, int *left);



};

YOLO::YOLO(Net_config config)
{
	this->confThreshold = config.confThreshold;
	this->nmsThreshold = config.nmsThreshold;
	this->objThreshold = config.objThreshold;

	this->net = cv::dnn::readNet(config.modelpath);
	std::ifstream ifs("D:\\project_prj\\deeplearn\\yolov5\\class.names");
	std::string line;
	while (getline(ifs, line)) this->class_names.push_back(line);
	this->num_class = class_names.size();

	
		
	this->num_stride = 3;
	this->inpHeight = 640;
	this->inpWidth = 640;
	
}

cv::Mat YOLO::resize_image(cv::Mat srcimg, int *newh, int *neww, int *top, int *left)
{
	int srch = srcimg.rows, srcw = srcimg.cols;
	*newh = this->inpHeight;
	*neww = this->inpWidth;
	cv::Mat dstimg;
	if (this->keep_ratio && srch != srcw) {
		float hw_scale = (float)srch / srcw;
		if (hw_scale > 1) {
			*newh = this->inpHeight;
			*neww = int(this->inpWidth / hw_scale);
			resize(srcimg, dstimg, cv::Size(*neww, *newh), cv::INTER_AREA);
			*left = int((this->inpWidth - *neww) * 0.5);
			copyMakeBorder(dstimg, dstimg, 0, 0, *left, this->inpWidth - *neww - *left, cv::BORDER_CONSTANT, 114);
		}
		else {
			*newh = (int)this->inpHeight * hw_scale;
			*neww = this->inpWidth;
			resize(srcimg, dstimg, cv::Size(*neww, *newh), cv::INTER_AREA);
			*top = (int)(this->inpHeight - *newh) * 0.5;
			copyMakeBorder(dstimg, dstimg, *top, this->inpHeight - *newh - *top, 0, 0, cv::BORDER_CONSTANT, 114);
		}
	}
	else {
		resize(srcimg, dstimg, cv::Size(*neww, *newh), cv::INTER_AREA);
	}
	return dstimg;
}

void YOLO::drawPred(float conf, int left, int top, int right, int bottom, cv::Mat& frame, int classid)   // Draw the predicted bounding box
{
	//Draw a rectangle displaying the bounding box
	if(classid==0)
		cv::rectangle(frame, cv::Point(left, top), cv::Point(right, bottom), cv::Scalar(0, 0, 255), 2);
	else
		cv::rectangle(frame, cv::Point(left, top), cv::Point(right, bottom), cv::Scalar(0, 255, 0), 2);

	//Get the label for the class name and its confidence
	std::string label = cv::format("%.2f", conf);
	label = this->class_names[classid] + ":" + label;

	//Display the label at the top of the bounding box
	int baseLine;
	cv::Size labelSize = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
	top = std::max(top, labelSize.height);
	if(classid == 0)
		//rectangle(frame, Point(left, top - int(1.5 * labelSize.height)), Point(left + int(1.5 * labelSize.width), top + baseLine), Scalar(0, 255, 0), FILLED);
		cv::putText(frame, label, cv::Point(left, top), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 0, 255), 1);
	else
		cv::putText(frame, label, cv::Point(left, top), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 255, 0), 1);
}

std::tuple<std::vector<cv::Rect>, std::vector<int>> YOLO::detect(cv::Mat& frame)
{
	int newh = 0, neww = 0, padh = 0, padw = 0;
	cv::Mat dstimg = this->resize_image(frame, &newh, &neww, &padh, &padw);
	cv::Mat blob = cv::dnn::blobFromImage(dstimg, 1 / 255.0, cv::Size(this->inpWidth, this->inpHeight), cv::Scalar(0, 0, 0), true, false);
	this->net.setInput(blob);
	std::vector<cv::Mat> outs;
	this->net.forward(outs, this->net.getUnconnectedOutLayersNames());

	int num_proposal = outs[0].size[1];
	int nout = outs[0].size[2];
	if (outs[0].dims > 2)
	{
		outs[0] = outs[0].reshape(0, num_proposal);
	}
	/generate proposals
	std::vector<float> confidences;
	std::vector<cv::Rect> boxes;

	std::vector<int> classIds;
	float ratioh = (float)frame.rows / newh, ratiow = (float)frame.cols / neww;
	int n = 0, q = 0, i = 0, j = 0, row_ind = 0; ///xmin,ymin,xamx,ymax,box_score,class_score
	float* pdata = (float*)outs[0].data;
	
	for (int i = 0; i < 25200 / 7; i++)
	{
		float cx = pdata[i * 7+0];
		float cy = pdata[i * 7+1];
		float w = pdata[i * 7 + 2];
		float h = pdata[i * 7 + 3];
		float score = pdata[i * 7 + 4];
		if (score < this->objThreshold)
			continue;

		float class_num1 = pdata[i * 7 + 5];
		float class_num2 = pdata[i * 7 + 6];
		
		int left = int((cx - padw - 0.5 * w) * ratiow);
		int top = int((cy - padh - 0.5 * h) * ratioh);
		float max_class_socre = class_num1 > class_num2 ? class_num1 : class_num2;
		if (class_num1 > class_num2)
		{
			max_class_socre = class_num1;

			classIds.push_back(0);
		}
		else
		{
			max_class_socre = class_num2;

			classIds.push_back(1);
		}

		confidences.push_back(max_class_socre);
		boxes.push_back(cv::Rect(left, top, (int)(w * ratiow), (int)(h * ratioh)));
		

	}


	// Perform non maximum suppression to eliminate redundant overlapping boxes with
	// lower confidences
	
	std::vector<cv::Rect> result_;
	std::vector<int> class_;
	std::vector<int> indices;
	cv::dnn::NMSBoxes(boxes, confidences, this->confThreshold, this->nmsThreshold, indices);
	for (size_t i = 0; i < indices.size(); ++i)
	{
		int idx = indices[i];
		cv::Rect box = boxes[idx];
		result_.emplace_back(box);
		class_.emplace_back(classIds[idx]);
		this->drawPred(confidences[idx], box.x, box.y,
			box.x + box.width, box.y + box.height, frame, classIds[idx]);
	}


	imwrite("D:\\project_prj\\deeplearn\\yolov5\\result\\" + std::to_string(index++) + ".jpg", frame);
	//std::cout << "done" << std::endl;
	//delete pdata;
	return std::make_tuple(result_, class_);
}



int main()
{
	Net_config yolo_nets = { 0.60, 0.5, 0.60, "D:\\project_prj\\run\\best_detectcircle_1.onnx" };
	YOLO yolo_model(yolo_nets);
	//string imgpath = "D:\\20230817-144309.jpg";

	std::string path = "C:\\datas_samll";
	std::vector<cv::String> result;
	cv::glob(path, result);
	for (auto x : result)
	{
		std::cout << x << std::endl;
		cv::Mat srcimg = cv::imread(x);
		auto result = yolo_model.detect(srcimg);
	}
	


}


http://www.niftyadmin.cn/n/4950152.html

相关文章

Mongodb Ubuntu安装

Mongodb Ubuntu安装 1.更新软件源导入MongoDB的GPG密钥 sudo apt update sudo apt install -y dirmngr wget gnupg apt-transport-https ca-certificates software-properties-common gnupgwget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add…

负载均衡下的webshell

文章目录 1.场景描述2.在蚁剑里添加 Shell3.因为负载均衡而出现的问题4.问题解决方案4.1 方案14.2 方案24.3 方案3 1.场景描述 当前手里有一个以docker部署的Tomcat负载均衡环境。主机对外ip和端口为192.168.100.130:18080 我们假设其为一个真实的业务系统&#xff0c;存在一…

中间件(下)

1、中间件与性能优化的关系&#xff1a; 中间件与性能优化之间存在密切的关系&#xff0c;特别是在构建复杂的分布式系统、处理高并发、实现异步通信等情况下。中间件可以在性能优化方面发挥重要作用&#xff0c;但同时&#xff0c;不当的中间件选择和配置也可能导致性能问题。…

隧道代理技术解析:为批量数据采集提供强大支持

嘿&#xff01;作为一名专业的爬虫程序员&#xff0c;我今天要和大家分享一个强大的技术&#xff0c;它能够为批量数据采集提供强大的支持——隧道代理技术。如果你在进行大规模数据采集任务时遇到了IP封禁和限制的问题&#xff0c;那么这项技术将是你的救星。废话不多说&#…

Azure Bastion的简单使用

什么是Azure Bastion Azure Bastion 是一个提供安全远程连接到 Azure 虚拟机&#xff08;VM&#xff09;的服务。传统上&#xff0c;访问 VM 需要使用公共 IP 或者设立 VPN 连接&#xff0c;这可能存在一些安全风险。Azure Bastion 提供了一种更安全的方式&#xff0c;它是一个…

[Flutter]有的时候调用setState(() {})报错?

先看FlutterSDK的原生类State中有一个变量mounted。 abstract class State<T extends StatefulWidget> with Diagnosticable {/// mounted的作用是&#xff0c;此State对象当前是否在树中。/// 在创建State对象之后&#xff0c;在调用initState之前&#xff0c;框架通过…

【Java 动态数据统计图】动态数据统计思路案例(动态,排序,数组)四(116)

需求&#xff1a;&#xff1a;前端根据后端的返回数据&#xff1a;画统计图&#xff1b; 1.动态获取地域数据以及数据中的平均值&#xff0c;按照平均值降序排序&#xff1b; 说明&#xff1a; X轴是动态的&#xff0c;有对应区域数据则展示&#xff1b; X轴 区域数据降序排序…

Hadoop学习:深入解析MapReduce的大数据魔力(三)

Hadoop学习&#xff1a;深入解析MapReduce的大数据魔力&#xff08;三&#xff09; 3.5 MapReduce 内核源码解析3.5.1 MapTask 工作机制3.5.2 ReduceTask 工作机制3.5.3 ReduceTask 并行度决定机制 3.6 数据清洗&#xff08;ETL&#xff09;1&#xff09;需求2&#xff09;需求…