【OpenCV】基于OpenCV/C++实现yolo目标检测

这篇具有很好参考价值的文章主要介绍了【OpenCV】基于OpenCV/C++实现yolo目标检测。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1. 原理

我们都知道,yolo这些深度学习检测算法都是在python下用pytorchtf框架这些训练的,训练得到的是pt或者weight权重文件,这些是算法开发人员做的事情,如何让算法的检测精度更高、速度更快。

但在工程化的时候,一般还是要用C++实现的,OpenCV不只是能进行图像的基本处理(以前我太肤浅了),它还有很多能处理深度学习的模块,比如DNN模块就支持调用多种框架下训练的权重文件。

下面就在VS2017+OpenCV454环境下进行演示。可以选择4种yolo变体,可以检测图片或视频。
(代码参考这位博主,以下是集成和演示)

2. 图片检测程序

运行代码前,请先配置好VS和OpenCV环境,然后准备好yolo相关权重文件(cfg+weight)。

首先定义yolo.h头文件:

#include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/dnn.hpp>	//调用dnn模块
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

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

//结构体定义:网络配置参数
struct Net_config
{
	float confThreshold; // 置信度阈值
	float nmsThreshold;  // 非极大值抑制(重叠率)阈值
	int inpWidth;  
	int inpHeight; 
	string classesFile;	//类别文件名
	string modelConfiguration;	//模型配置文件
	string modelWeights;	//模型权重
	string netname;	//模型名称
};

//定义yolo类
class YOLO
{
	public:
		YOLO(Net_config config);
		void detect(Mat& frame);	//检测函数
	private:
		float confThreshold;	//类别置信度阈值
		float nmsThreshold;		//重叠率阈值
		int inpWidth;	//图片宽度
		int inpHeight;	//图片高度
		char netname[20];	//网络名称
		vector<string> classes;	//存储类别的数组
		Net net;	//深度学习模型读取
		void postprocess(Mat& frame, const vector<Mat>& outs);	//后处理函数
		void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);	//画框
};

//定义网络数组
Net_config yolo_nets[4] = {
	{0.5, 0.4, 416, 416,"coco.names", "yolov3/yolov3.cfg", "yolov3/yolov3.weights", "yolov3"},
	{0.5, 0.4, 608, 608,"coco.names", "yolov4/yolov4-tiny.cfg", "yolov4/yolov4-tiny.weights", "yolov4-tiny"},
	{0.5, 0.4, 320, 320,"coco.names", "yolo-fastest/yolo-fastest-xl.cfg", "yolo-fastest/yolo-fastest-xl.weights", "yolo-fastest"},
	{0.5, 0.4, 320, 320,"coco.names", "yolobile/csdarknet53s-panet-spp.cfg", "yolobile/yolobile.weights", "yolobile"}
};

然后进入main主程序:

#include "yolo.h"

//网络配置构造函数
YOLO::YOLO(Net_config config)
{
	cout << "Net use " << config.netname << endl;
	this->confThreshold = config.confThreshold;
	this->nmsThreshold = config.nmsThreshold;
	this->inpWidth = config.inpWidth;
	this->inpHeight = config.inpHeight;
	strcpy_s(this->netname, config.netname.c_str());

	ifstream ifs(config.classesFile.c_str());
	string line;
	while (getline(ifs, line)) this->classes.push_back(line);

	this->net = readNetFromDarknet(config.modelConfiguration, config.modelWeights);
	this->net.setPreferableBackend(DNN_BACKEND_OPENCV);
	this->net.setPreferableTarget(DNN_TARGET_CPU);
}

//后处理
void YOLO::postprocess(Mat& frame, const vector<Mat>& outs)   // Remove the bounding boxes with low confidence using non-maxima suppression
{
	vector<int> classIds;	//类别
	vector<float> confidences;	//置信度
	vector<Rect> boxes;	//框

	for (size_t i = 0; i < outs.size(); ++i)
	{
		// Scan through all the bounding boxes output from the network and keep only the
		// ones with high confidence scores. Assign the box's class label as the class
		// with the highest score for the box.
		float* data = (float*)outs[i].data;
		for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)
		{
			Mat scores = outs[i].row(j).colRange(5, outs[i].cols);
			Point classIdPoint;
			double confidence;
			// Get the value and location of the maximum score
			minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
			//当置信度大于阈值
			if (confidence > this->confThreshold)
			{
				int centerX = (int)(data[0] * frame.cols);
				int centerY = (int)(data[1] * frame.rows);
				int width = (int)(data[2] * frame.cols);
				int height = (int)(data[3] * frame.rows);
				int left = centerX - width / 2;
				int top = centerY - height / 2;

				classIds.push_back(classIdPoint.x);
				confidences.push_back((float)confidence);
				boxes.push_back(Rect(left, top, width, height));
			}
		}
	}

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

//画预测框
void YOLO::drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)   // Draw the predicted bounding box
{
	//Draw a rectangle displaying the bounding box 画框
	rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255), 3);

	//Get the label for the class name and its confidence	打标签
	string label = format("%.2f", conf);
	if (!this->classes.empty())
	{
		CV_Assert(classId < (int)this->classes.size());
		label = this->classes[classId] + ":" + label;
	}

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

//detect检测
void YOLO::detect(Mat& frame)
{
	Mat blob;	//blob预处理
	blobFromImage(frame, blob, 1 / 255.0, Size(this->inpWidth, this->inpHeight), Scalar(0, 0, 0), true, false);
	this->net.setInput(blob);
	vector<Mat> outs;
	this->net.forward(outs, this->net.getUnconnectedOutLayersNames());	//前向处理
	this->postprocess(frame, outs);	//后处理

	vector<double> layersTimes;
	double freq = getTickFrequency() / 1000;
	double t = net.getPerfProfile(layersTimes) / freq;
	string label = format("%s Inference time : %.2f ms", this->netname, t);
	putText(frame, label, Point(0, 30), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 0, 255), 2);
	//imwrite(format("%s_out.jpg", this->netname), frame);
}

//main入口
int main()
{
	YOLO yolo_model(yolo_nets[2]);	//选择网络

	//1.图片检测
	string imgpath = "dog.jpg";
	Mat srcimg = imread(imgpath);	//读取照片
	yolo_model.detect(srcimg);	//调用检测程序

	//图片检测界面
	static const string kWinName = "Deep learning object detection in OpenCV C++";
	namedWindow(kWinName, WINDOW_NORMAL);
	imshow(kWinName, srcimg);
	waitKey(0);
	destroyAllWindows();


}

运行结果如下:

c++ opencv yolov5,c++CV计算机视觉,opencv,c++,目标检测

3. 视频检测程序

要调用视频,只需在main函数中加入:

	//2.视频检测/实时摄像头
	VideoCapture capture("test.avi");	//0
	Mat frame;
	while (true) {
		int ret = capture.read(frame);
		if (!ret) {
			break;
		}
		//imshow("input", frame);	//显示原视频
		yolo_model.detect(frame);	//调用process
		static const string kWinName = "Deep learning object detection in OpenCV C++";
		namedWindow(kWinName, WINDOW_NORMAL);
		imshow(kWinName, frame);

		char c = waitKey(5);
		if (c == 27) {
			break;
		}
	}

运行结果如下:

c++ opencv yolov5,c++CV计算机视觉,opencv,c++,目标检测

其他

还有一个用SSD MobileNet检测的示例:

项目Github地址:https://github.com/ChiekoN/OpenCV_SSD_MobileNet

#编译
mkdir build && cd build
cmake ..
make
./ssd_obj_detect

基于ROS的人脸检测的示例:

项目Github地址:https://github.com/1417265678/robot_vision

# 先起相机节点
roslaunch robot_vision usb_cam.launch
# 检测节点
roslaunch robot_vision face_detector.launch

c++ opencv yolov5,c++CV计算机视觉,opencv,c++,目标检测

以上。文章来源地址https://www.toymoban.com/news/detail-614946.html

到了这里,关于【OpenCV】基于OpenCV/C++实现yolo目标检测的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • YOLOV5-LITE实时目标检测(onnxruntime部署+opencv获取摄像头+NCNN部署)python版本和C++版本

    使用yolov5-lite自带的export.py导出onnx格式,图像大小设置320,batch 1 之后可以使用 onnxsim对模型进一步简化 onnxsim参考链接:onnxsim-让导出的onnx模型更精简_alex1801的博客-CSDN博客 这个版本的推理FPS能有11+FPS 这两处换成自己的模型和训练的类别即可:     parser.add_argument(\\\'--modelpa

    2024年02月04日
    浏览(38)
  • OpenCV之YOLOv5目标检测

    💂 个人主页: 风间琉璃 🤟 版权:  本文由【风间琉璃】原创、在CSDN首发、需要转载请联系博主 💬 如果文章对你有帮助、 欢迎关注、 点赞、 收藏(一键三连) 和 订阅专栏 哦 目录 前言 一、YOLOv5简介 二、预处理 1.获取分类名 2.获取输出层名称 3.图像尺度变换 三、模型加载

    2024年01月20日
    浏览(38)
  • 【OpenCV】车辆识别 目标检测 级联分类器 C++ 案例实现

    前言 一、目标检测技术 二、样本采集工作原理 三、创建自己的级联分类器 Step1:准备好样本图像 Step2:环境配置(OpenCV win10) Step3:设置路径 Step4:实现样本数据采集  Step5:实现样本数据训练 Step6:生成级联分类器文件  四、案例实现 Step1:灰度处理 Step2:二次压缩 Ste

    2024年02月05日
    浏览(32)
  • 目标检测YOLO实战应用案例100讲-基于深度学习的航拍图像YOLOv5目标检测(论文篇)(续)

    目录 基础理论及相关技术  2.1 深度学习基础理论 

    2024年04月16日
    浏览(33)
  • 【解惑笔记】树莓派+OpenCV+YOLOv5目标检测(Pytorch框架)

     -【学习资料】 子豪兄的零基础树莓派教程 https://github.com/TommyZihao/ZihaoTutorialOfRaspberryPi/blob/master/%E7%AC%AC2%E8%AE%B2%EF%BC%9A%E6%A0%91%E8%8E%93%E6%B4%BE%E6%96%B0%E6%89%8B%E6%97%A0%E7%97%9B%E5%BC%80%E6%9C%BA%E6%8C%87%E5%8D%97.md#%E7%83%A7%E5%BD%95%E9%95%9C%E5%83%8F 第2讲:树莓派新手无痛开机指南【子豪兄的树莓派

    2024年02月14日
    浏览(28)
  • 【问题记录】树莓派+OpenCV+YOLOv5目标检测(Pytorch框架)

     -【学习资料】 子豪兄的零基础树莓派教程 https://github.com/TommyZihao/ZihaoTutorialOfRaspberryPi/blob/master/%E7%AC%AC2%E8%AE%B2%EF%BC%9A%E6%A0%91%E8%8E%93%E6%B4%BE%E6%96%B0%E6%89%8B%E6%97%A0%E7%97%9B%E5%BC%80%E6%9C%BA%E6%8C%87%E5%8D%97.md#%E7%83%A7%E5%BD%95%E9%95%9C%E5%83%8F 第2讲:树莓派新手无痛开机指南【子豪兄的树莓派

    2024年02月02日
    浏览(42)
  • opencv案例06-基于opencv图像匹配的消防通道障碍物检测与深度yolo检测的对比

    技术背景 消防通道是指在各种险情发生时,用于消防人员实施营救和被困人员疏散的通道。消防法规定任何单位和个人不得占用、堵塞、封闭消防通道。事实上,由于消防通道通常缺乏管理,导致各种垃圾,物品以及车辆等障碍物常常出现在消防通道中,堵塞消防通道,当险

    2024年02月03日
    浏览(34)
  • 用opencv的DNN模块做Yolov5目标检测(纯干货,源码已上传Github)

    最近在微信公众号里看到多篇讲解yolov5在openvino部署做目标检测文章,但是没看到过用opencv的dnn模块做yolov5目标检测的。于是,我就想着编写一套用opencv的dnn模块做yolov5目标检测的程序。在编写这套程序时,遇到的bug和解决办法,在这篇文章里讲述一下。 在yolov5之前的yolov3和

    2024年02月02日
    浏览(37)
  • 裂缝检测,只依赖OPENCV,基于YOLO8S

    裂缝检测,只依赖OPENCV,YOLOV8S 现在YOLOV8S训练目标非常方便,可以直接转换成ONNX让OPENCV调用,支持C++/PYTHON,原理很简单,自己找博客,有兴趣相互交流

    2024年02月11日
    浏览(28)
  • OpenCV与AI深度学习 | 实战 | 基于YOLOv9+SAM实现动态目标检测和分割(步骤 + 代码)

    本文来源公众号 “OpenCV与AI深度学习” ,仅用于学术分享,侵权删,干货满满。 原文链接:实战 | 基于YOLOv9+SAM实现动态目标检测和分割(步骤 + 代码)     本文主要介绍基于YOLOv9+SAM实现动态目标检测和分割,并给出详细步骤和代码。     在本文中,我们使用YOLOv9+SAM在

    2024年04月22日
    浏览(61)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包