VS+QT+Opencv使用YOLOv4对视频流进行目标检测

news/2024/7/11 0:48:23 标签: qt, opencv, YOLO

对单张图像的检测,请参考:https://blog.csdn.net/qq_45445740/article/details/109659938

#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;

// 初始化参数
float confThreshold = 0.5; // 置信度
float nmsThreshold = 0.4;  // NMS
int inpWidth = 416;  // 网络输入图像的宽度
int inpHeight = 416; // 网络输入图像的高度
vector<string> classes;

// 使用非最大值抑制去除低置信度的边界框
void postprocess(Mat& frame, const vector<Mat>& out);

// 绘制预测的边界框
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);

// 获取输出层的名称
vector<String> getOutputsNames(const Net& net);
void detect_image(string image_path, string modelWeights, string modelConfiguration, string classesFile);
void detect_video(string video_path, string modelWeights, string modelConfiguration, string classesFile);

int main(int argc, char** argv)
{
	// 给出模型的配置和权重文件
	String modelConfiguration = "E:/00000000E/QT/pracitce/PcbDetectv2/01图像识别/model/yolo-obj.cfg";
	String modelWeights = "E:/00000000E/QT/pracitce/PcbDetectv2/01图像识别/model/yolo-obj_4000.weights";
	string image_path = "E:/00000000E/QT/pracitce/PcbDetectv2/01图像识别/image/01.jpg";
	string classesFile = "E:/00000000E/QT/pracitce/PcbDetectv2/01图像识别/model/classes.names";// "coco.names";

	// detect_image(image_path, modelWeights, modelConfiguration, classesFile);
	string video_path = "E:/00000000E/QT/pracitce/PcbDetectv2/02视频检测/video/test.mp4";
	detect_video(video_path, modelWeights, modelConfiguration, classesFile);
	cv::waitKey(0);
	return 0;
}



void detect_image(string image_path, string modelWeights, string modelConfiguration, string classesFile) 
{
	// 加载分类类别
	ifstream ifs(classesFile.c_str());
	string line;
	while (getline(ifs, line)) classes.push_back(line);

	// 加载网络
	Net net = readNetFromDarknet(modelConfiguration, modelWeights);
	net.setPreferableBackend(DNN_BACKEND_OPENCV);
	net.setPreferableTarget(DNN_TARGET_OPENCL);

	// 打开视频文件或图像文件或摄像机流
	string str, outputFile;
	cv::Mat frame = cv::imread(image_path);

	// Create a window
	static const string kWinName = "Deep learning object detection in OpenCV";
	namedWindow(kWinName, WINDOW_NORMAL);

	Mat blob;
	blobFromImage(frame, blob, 1 / 255.0, Size(inpWidth, inpHeight), Scalar(0, 0, 0), true, false);

	// 设置网络输入
	net.setInput(blob);

	// 运行前向传递以获得输出层的输出
	vector<Mat> outs;
	net.forward(outs, getOutputsNames(net));

	// 移除低置信度的边界框
	postprocess(frame, outs);

	// 返回推断的总时间(t)和每个层的计时(以layersTimes表示)

	vector<double> layersTimes;
	double freq = getTickFrequency() / 1000;
	double t = net.getPerfProfile(layersTimes) / freq;
	string label = format("Inference time for a frame : %.2f ms", t);
	putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255));

	// 写入带有检测框的帧
	imshow(kWinName, frame);
	cv::waitKey(30);
}


void detect_video(string video_path, string modelWeights, string modelConfiguration, string classesFile) 
{
	string outputFile = "./yolo_out_cpp.avi";;

	ifstream ifs(classesFile.c_str());
	string line;
	while (getline(ifs, line)) classes.push_back(line);

	Net net = readNetFromDarknet(modelConfiguration, modelWeights);
	net.setPreferableBackend(DNN_BACKEND_OPENCV);
	net.setPreferableTarget(DNN_TARGET_CPU);

	VideoCapture cap;

	Mat frame, blob;

	try 
	{
		// 打开视频文件
		ifstream ifile(video_path);
		if (!ifile) throw("error");
		cap.open(video_path);
	}

	catch (...) 
	{
		cout << "Could not open the input image/video stream" << endl;
		return;
	}

	// Get the video writer initialized to save the output video
	//  video.open(outputFile, 
	//	VideoWriter::fourcc('M', 'J', 'P', 'G'), 28, Size(cap.get(CAP_PROP_FRAME_WIDTH), cap.get(CAP_PROP_FRAME_HEIGHT)));


	static const string kWinName = "Deep learning object detection in OpenCV";
	namedWindow(kWinName, WINDOW_NORMAL);

	while (waitKey(1) < 0)
	{
		cap >> frame;
		if (frame.empty()) 
		{
			cout << "Done processing !!!" << endl;
			cout << "Output file is stored as " << outputFile << endl;
			waitKey(3000);
			break;
		}

		blobFromImage(frame, blob, 1 / 255.0, Size(inpWidth, inpHeight), Scalar(0, 0, 0), true, false);

		net.setInput(blob);

		vector<Mat> outs;
		net.forward(outs, getOutputsNames(net));

		postprocess(frame, outs);

		vector<double> layersTimes;
		double freq = getTickFrequency() / 1000;
		double t = net.getPerfProfile(layersTimes) / freq;
		string label = format("Inference time for a frame : %.2f ms", t);
		putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255));

		Mat detectedFrame;
		frame.convertTo(detectedFrame, CV_8U);

		imshow(kWinName, frame);
	}

	cap.release();
}

void postprocess(Mat& frame, const vector<Mat>& outs)
{
	vector<int> classIds;
	vector<float> confidences;
	vector<Rect> boxes;
	for (size_t i = 0; i < outs.size(); ++i)
	{
		// 扫描网络输出的所有边界框,只保留置信度高的边界框。将盒子的类标签指定为盒子得分最高的类
		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;
			// 获取最高分的值和位置
			minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
			if (confidence > 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));
			}

		}

	}

	// 执行非最大抑制以消除置信度较低的冗余重叠框
	vector<int> indices;
	NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
	for (size_t i = 0; i < indices.size(); ++i)
	{
		int idx = indices[i];
		Rect box = boxes[idx];
		drawPred(classIds[idx], confidences[idx], box.x, box.y,
			box.x + box.width, box.y + box.height, frame);
	}

}


// 绘制预测框
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
	// 绘制显示边界框的矩形
	rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 178, 50), 3);

	// 获取类名及其置信度的标签
	string label = format("%.2f", conf);
	if (!classes.empty())
	{
		CV_Assert(classId < (int)classes.size());
		label = classes[classId] + ":" + label;
	}

	// 在边界框的顶部显示标签
	int baseLine;
	Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
	top = max(top, labelSize.height);
	rectangle(frame, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED);

	putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 0), 1);
}

vector<String> getOutputsNames(const Net& net)
{
	static vector<String> names;
	if (names.empty())
	{
		// 获取输出层的索引,即输出不相连的层
		vector<int> outLayers = net.getUnconnectedOutLayers();

		vector<String> layersNames = net.getLayerNames();

		names.resize(outLayers.size());
		for (size_t i = 0; i < outLayers.size(); ++i)
			names[i] = layersNames[outLayers[i] - 1];
	}
	return names;
}

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

相关文章

数据结构(一):顺序表详解

在正式介绍顺序表之前&#xff0c;我们有必要先了解一个名词&#xff1a;线性表。 线性表&#xff1a; 线性表是&#xff0c;具有n个相同特性的数据元素的有限序列。常见的线性表&#xff1a;顺序表、链表、栈、队列、数组、字符串... 线性表在逻辑上是线性结构&#xff0c;但…

mac harbor的安装

harbor的安装 为什么要整这个呢&#xff0c;因为我在学习k8s&#xff0c;但是需要一个自己的镜像仓库。于是&#xff0c;最开始想到的就是在本地直接部署一个&#xff0c;还比较安全、快速。 直接下载了官方的项目&#xff0c;运行脚本发现出了异常&#xff0c;这种异常我已经…

LNMP环境搭建wordpress以及跳转后台报404解决

基于上文配置好的LNMP环境继续搭建wordpress 目录 一.到官网下载tar.gz包&#xff0c;并上传到Linux上&#xff0c;也可以通过复制链接地址进行下载 二. 将wordpress中的所有文件移动到你nginx.conf中指定目录中 三.为wordpress配置数据库 四.到浏览器进行注册 1.刚开始…

bat语言的学习

1、删除文件的实例&#xff0c;这个是工程内的bat脚本实例 del *.bak /s del *.ddk /s del *.edk /s del *.lst /s del *.lnp /s del *.mpf /s del *.mpj /s del *.obj /s del *.omf /s ::del *.opt /s ::不允许删除JLINK的设置 del *.plg /s del *.rpt /s del *.tmp /s del …

基于Googlenet深度学习网络的人员行为动作识别matlab仿真

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 1. 原理 1.1 深度学习与卷积神经网络&#xff08;CNN&#xff09; 1.2 GoogLeNet 2. 实现过程 2.1 数据预处理 2.2 构建网络模型 2.3 数据输入与训练 2.4 模型评估与调优 3. 应用领域…

2023-08-12 LeetCode每日一题(合并 K 个升序链表)

2023-08-12每日一题 一、题目编号 23. 合并 K 个升序链表二、题目链接 点击跳转到题目位置 三、题目描述 给你一个链表数组&#xff0c;每个链表都已经按升序排列。 请你将所有链表合并到一个升序链表中&#xff0c;返回合并后的链表。 示例 1&#xff1a; 示例 2&…

Golang 基本常量声明及 iota 使用

文章目录 一、局部常量声明二、全局常量声明三、多行常量定义&#xff0c;值表达式为空时自动继承前一个四、常量声明 - iota 一、局部常量声明 package mainimport "fmt"func main() {//局部常量声明//方式一&#xff1a;主动声明类型const lengthA int 10//方式二…

【数据结构】“栈”的模拟实现

&#x1f490; &#x1f338; &#x1f337; &#x1f340; &#x1f339; &#x1f33b; &#x1f33a; &#x1f341; &#x1f343; &#x1f342; &#x1f33f; &#x1f344;&#x1f35d; &#x1f35b; &#x1f364; &#x1f4c3;个人主页 &#xff1a;阿然成长日记 …