Qt调用opencv实现yolov3对视频进行目标检测

2023-05-16

欢迎加QQ学习交流群309798848

依赖:支持CUDA的opencv4.3.0,demo.cfg,demo_final.weights,demo.names

demo.cfg,demo.names是darknet训练用的配置文件,demo_final.weights是训练后的权重文件。

使用GPU或CPU的代码:

//使用GPU检测
#ifdef Enable_GPU
	net.setPreferableTarget(DNN_TARGET_CUDA);
	net.setPreferableBackend(DNN_BACKEND_CUDA);
//使用CPU检测
#else
	net.setPreferableTarget(DNN_TARGET_CPU);
	net.setPreferableBackend(DNN_BACKEND_OPENCV);
#endif

一般opencv关闭窗口后会马上重新出现,就像有守护进程一样。这样就不能点击关闭按钮退出程序。为了点击关闭按钮就能退出程序,需要在while循环内加这段代码:

// opencv点击关闭按钮则关闭窗口
if (getWindowProperty(kWinName, WND_PROP_VISIBLE) < 1)
{
	break;
}

完整代码:

#include <QtWidgets/QApplication>

#include <iostream>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <sstream>
#include <iostream>

#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

#include <opencv2/highgui/highgui_c.h> 
#include <Windows.h>

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

string pro_dir = "./input/";

#define Enable_GPU

// Initialize the parameters
//float confThreshold = 0.5; // Confidence threshold
float confThreshold = 0.4; // Confidence threshold 
float nmsThreshold = 0.4;  // Non-maximum suppression threshold
int inpWidth = 416;  // Width of network's input image
int inpHeight = 416; // Height of network's input image
vector<string> classes;

// Remove the bounding boxes with low confidence using non-maxima suppression
void postprocess(Mat& frame, const vector<Mat>& out);
// Draw the predicted bounding box
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);
// Get the names of the output layers
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);

void dnnM()
{
	QString dir = QString("%1/%2").arg(QApplication::applicationDirPath()).arg("input");

	String modelConfiguration = QString("%1/%2").arg(dir).arg("demo.cfg").toLocal8Bit();
	String modelWeights = QString("%1/%2").arg(dir).arg("demo_final.weights").toLocal8Bit();
	String classesFile = QString("%1/%2").arg(dir).arg("demo.names").toLocal8Bit();

	String image_path = QString("%1/%2").arg(dir).arg("ammeter.png").toStdString();

	String video_path = QString("%1/%2").arg(dir).arg(QStringLiteral("demo.mp4")).toLocal8Bit();
	detect_video(video_path, modelWeights, modelConfiguration, classesFile);
}

void detect_image(string image_path, string modelWeights, string modelConfiguration, string classesFile) {
	// Load names of classes
	ifstream ifs(classesFile.c_str());
	string line;
	while (getline(ifs, line)) classes.push_back(line);

	// Load the network
	Net net = readNetFromDarknet(modelConfiguration, modelWeights);
	net.setPreferableBackend(DNN_BACKEND_OPENCV);
	net.setPreferableTarget(DNN_TARGET_OPENCL);

	// Open a video file or an image file or a camera stream.
	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);

	// Stop the program if reached end of video
	// Create a 4D blob from a frame.
	Mat blob;
	blobFromImage(frame, blob, 1 / 255.0, Size(inpWidth, inpHeight), Scalar(0, 0, 0), true, false);

	//Sets the input to the network
	net.setInput(blob);

	// Runs the forward pass to get output of the output layers
	vector<Mat> outs;
	net.forward(outs, getOutputsNames(net));

	// Remove the bounding boxes with low confidence
	postprocess(frame, outs);
	// Put efficiency information. The function getPerfProfile returns the overall time for inference(t) and the timings for each of the layers(in 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));
	// Write the frame with the detection boxes
	imshow(kWinName, frame);
	cv::waitKey();
}

void detect_video(string video_path, string modelWeights, string modelConfiguration, string classesFile) {
	string outputFile = "./out.avi";;
	// Load names of classes
	ifstream ifs(classesFile.c_str());
	string line;
	while (getline(ifs, line)) classes.push_back(line);

	// Load the network
	Net net = readNetFromDarknet(modelConfiguration, modelWeights);

//使用GPU检测
#ifdef Enable_GPU
	net.setPreferableTarget(DNN_TARGET_CUDA);
	net.setPreferableBackend(DNN_BACKEND_CUDA);
//使用CPU检测
#else
	net.setPreferableTarget(DNN_TARGET_CPU);
	net.setPreferableBackend(DNN_BACKEND_OPENCV);
#endif

	// Open a video file or an image file or a camera stream.
	VideoCapture cap;
	VideoWriter video;
	Mat frame, blob;

	try {
		// Open the video file
		ifstream ifile(video_path);
		if (!ifile) throw("error");
		cap.open(video_path);

		//video.open(outputFile, VideoWriter::fourcc('M', 'J', 'P', 'G'), 25, Size(cap.get(CAP_PROP_FRAME_WIDTH), cap.get(CAP_PROP_FRAME_HEIGHT)));
		bool b = video.open(outputFile, VideoWriter::fourcc('M', 'P', '4', '2'), 25, Size(cap.get(CAP_PROP_FRAME_WIDTH), cap.get(CAP_PROP_FRAME_HEIGHT)));
	}
	catch (...) {
		cout << "Could not open the input image/video stream" << endl;
		return;
	}

	static const string kWinName = "demo";
	namedWindow(kWinName, WINDOW_NORMAL);

	while (waitKey(1) < 0)
	{
		// opencv点击关闭按钮则关闭窗口
		if (getWindowProperty(kWinName, WND_PROP_VISIBLE) < 1)
		{
			break;
		}

		// get frame from the video
		cap >> frame;

		// Stop the program if reached end of video
		if (frame.empty()) {
			cout << "Done processing !!!" << endl;
			cout << "Output file is stored as " << outputFile << endl;
			waitKey(3000);
			break;
		}
		// Create a 4D blob from a frame.
		blobFromImage(frame, blob, 1 / 255.0, Size(inpWidth, inpHeight), Scalar(0, 0, 0), true, false);

		//Sets the input to the network
		net.setInput(blob);

		// Runs the forward pass to get output of the output layers
		vector<Mat> outs;
		net.forward(outs, getOutputsNames(net));

		// Remove the bounding boxes with low confidence
		postprocess(frame, outs);

		// Put efficiency information. The function getPerfProfile returns the overall time for inference(t) and the timings for each of the layers(in layersTimes)
		vector<double> layersTimes;
		double freq = getTickFrequency() / 1000;
		double t = net.getPerfProfile(layersTimes) / freq;
		double FPS = 1 / (t / 1000);
		string label = format("FPS: %.2f", FPS);
		//rectangle(frame, Size(0, 0), Size(100, 20), Scalar(0, 0, 0), 0);
		//cv::line(frame, Size(0, 0), Size(100, 0), Scalar(0, 0, 0), 0);
		putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 255), 1);

		// Write the frame with the detection boxes
		Mat detectedFrame;
		frame.convertTo(detectedFrame, CV_8U);
		video.write(detectedFrame);
		//imshow(kWinName, frame);
		imshow(kWinName, detectedFrame);
	}
	cap.release();
	video.release();
	cv::destroyWindow(kWinName);
}

// Remove the bounding boxes with low confidence using non-maxima suppression
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)
	{
		// 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 > 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, 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);
	}
}

// Draw the predicted bounding box
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
	string type;

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

	Scalar scalar;
	switch (classId)
	{
	case 0:
		scalar = Scalar(255, 104, 0);
		break;
	case 1:
		scalar = Scalar(255, 39, 255);
		break;
	case 2:
		scalar = Scalar(255, 31, 107);
		break;
	case 3:
		scalar = Scalar(255, 239, 0);
		break;
	case 4:
		scalar = Scalar(0, 122, 254);
		break;
	case 5:
		scalar = Scalar(131, 216, 0);
		break;
	case 6:
		scalar = Scalar(0, 226, 189);
		break;
	case 7:
		scalar = Scalar(250, 25, 19);
		break;
	case 8:
		scalar = Scalar(111, 111, 22);
		break;
	default:
		scalar = Scalar(255, 104, 22);
		break;
	}

	//Draw a rectangle displaying the bounding box
	rectangle(frame, Point(left, top), Point(right, bottom), scalar, 2);

	//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);

	baseLine -= 1;
	rectangle(frame, Point(left, top - 2 * labelSize.height - baseLine), Point(left + round(labelSize.width), top - baseLine + 2), scalar, FILLED);
	putText(frame, label, Point(left, top - 0.5 * labelSize.height - baseLine - 1), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0), 1);
}

// Get the names of the output layers
vector<String> getOutputsNames(const Net& net)
{
	static vector<String> names;
	if (names.empty())
	{
		//Get the indices of the output layers, i.e. the layers with unconnected outputs
		vector<int> outLayers = net.getUnconnectedOutLayers();

		//get the names of all the layers in the network
		vector<String> layersNames = net.getLayerNames();

		// Get the names of the output layers in names
		names.resize(outLayers.size());
		for (size_t i = 0; i < outLayers.size(); ++i)
			names[i] = layersNames[outLayers[i] - 1];
	}
	return names;
}

int main(int argc, char* argv[])
{
	//QApplication a(argc, argv);

	dnnM();

	//return a.exec();
	return 1;
}

实测:

1650s显卡下跑这个程序,FPS在33左右,比CPU 5帧好多了。但是很奇怪的是我用darknet检测的时候FPS只有7,实在是不知道哪里有问题。

2070s:FPS 65 。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Qt调用opencv实现yolov3对视频进行目标检测 的相关文章

  • Keil编译警告:function "assert_param" declared implicitly的解决方法

    1 问题描述 新建STM32的keil工程 xff0c 在编译时出现警告 FWLIB src stm32f10x rcc c 273 warning 223 D function assert param declared implicit
  • 寻路A*算法 (下)

    这样还剩下 5 个相邻的方格 当前方格下面的 2 个方格还没有加入 open list xff0c 所以把它们加入 xff0c 同时把当前方格设为他们的父亲 在剩下的 3 个方格中 xff0c 有 2 个已经在 close list 中 一
  • ROS学习笔记之七:ROSSerial初试

    总体来说 xff0c ROS更偏重软件 xff0c 其涉及的控制 算法都是偏策略或复杂的 xff0c 但机器人是要和现实世界打交道的 xff0c 必须有相应的执行机构 xff0c 使ROS所能做的那些 高 大 上 的工作落地 真正能够和执行
  • 单片机的堆和栈(Heap & Stack)详解

    一 程序内存分配 由c C 43 43 编译的程序占用的内存分为以下几个部分 1 栈区 xff08 stack xff09 由编译器自动分配释放 xff0c 存放函数的参数值 xff0c 局部变量的值等 其操作方式类似于数据结构中的栈 2
  • 汽车CAN通信基础知识-CAN数据结构

    目录 1 CAN总线概述 2 基于CAN总线的汽车电气网络结构 3 CAN总线的特点 4 CAN协议分层结构和功能 5 CAN数据帧类型 1 CAN总线概述 a CAN Controller Area Network 即控制器局域网络 由于
  • lubuntu18.04工控屏QT开发

    lubuntu18 04工控屏QT开发 备忘 系统更新中文语言包及输入法QT安装QWT安装QT程序的打包和运行Lubuntu开机自启动脚本程序方法Lubuntu开机跳过输入密码自动登录 13 3寸触摸工控屏 xff0c lubuntu18
  • 数据FIFO的读写和信息FIFO的基本使用方法

    数据FIFO 一 写使能 wr en xff0c 写数据 wdata din 8bit assign wr en 61 din vld din vld 为数据有效指示信号 assign wdata 61 din sop din eop di
  • 获取系统当前时间和特定格式的时间

    java中获取系统当前时间 SimpleDateFormat formatter 61 new SimpleDateFormat 34 yyyy年MM月dd日 HH mm ss 34 Date curDate 61 new Date Sys
  • HTTP认证模式:Basic & Digest

    引言 经常在工作中使用到了各种认证方式 xff0c 但从未考虑过这些认证方式所属的知识范畴 xff0c 同时也解释不清楚它们 曾用到的认证方式 xff08 看看是否您也用过 xff0c 但很难解释清楚他们 xff09 xff1a Basic
  • Could not retrieve

    输入where nvm 找到nvm安装文件夹 在nvm文件夹下找到settings txt 添加以下代码 xff1a xff08 若没有则新建settings txt文件 xff09 node mirror npm taobao org m
  • Jetson Xavier gpio编程 (8)

    GPIO lines are attached to gpiochips Look in sys class gpio and you should see gpiochip240 248 and 288 I haven t yet det
  • curl 函数

    1 curl close 关闭一个cURL会话 语法 xff1a curl close span class hljs variable ch span span class hljs variable ch span 由 curl ini
  • CMake Error at /opt/ros/kinetic/share/catkin/cmake/catkinConfig.cmake:83 (find_package):

    出现了这样的情况的话如 xff1a CMake Error at opt ros kinetic share catkin cmake catkinConfig cmake 83 find package Could not find a
  • Rails Digest认证实现和原理

    优势 Http Digest是一种Http 不仅限于Web页面 认证框架 xff0c 相比通常使用的基本认证 xff0c Digest认证的优点是相对安全 基于网络标准和简单 xff0c 它不需要编写登录表单页面 xff0c 对登录信息进行
  • 【目标检测】修改YOLO标注索引,批量修改txt文件指定内容

    假设需要将原索引 0 xff0c 1 xff0c 2 xff0c 3 都修改为 0 xff1a import os path 61 39 train 39 total txt 61 os listdir path deleteList 61
  • 《C语言中分配了动态内存后一定要释放吗?》

    问 xff1a 比如main函数里有一句 malloc 后面没有free 1 那么当main结束后 xff0c 动态分配的内存不会随之释放吗 xff1f 2 如果程序结束能自动释放 xff0c 那么还加上free xff08 xff09 x
  • 串口通讯的延时问题

    串口编程涉及很多问题 xff0c 对于实时采集系统 xff0c 串口编程必须服从系统定时器采集节拍 xff0c 这样通过事件方式接收串口然后延时就会带来很多问题 串口数据通常不是一次到来 xff0c 对于一个较为长的数据 xff0c 可能分
  • linux下从源代码编译安装软件的一般步骤

    1 下载并解压文件 如果下的压缩文件的后缀是 tar gz 解压用 tar xzvf xxx tar gz tar b2 解压用 tar xjvf xxx tar b2 tar 解压用 tar xvf xxx tar 2 配置安装路径 在
  • 单精度浮点数(float)与双精度浮点数(double)的区别

    单精度浮点数 xff08 float xff09 与双精度浮点数 xff08 double xff09 的区别如下 xff1a xff08 1 xff09 在内存中占有的字节数不同 单精度浮点数在机内占4个字节 双精度浮点数在机内占8个字节
  • /dev/ttyUSB0 permission denied 解决办法:永久有可操作权限

    一般使用USB口 无论USB转什么口 xff0c 串口之类的 xff0c 启动时容易出现 dev ttyUSB0 permission denied 因为一般情况下不是root用户 xff0c 对端口没有权限 xff0e 遇到这种情况 xf

随机推荐

  • 三种继承的方法:public 继承/private继承/protected继承详解及区别

    公有继承 public 私有继承 private 保护继承 protected 是常用的三种继承方式 1 公有继承 public 公有继承的特点是基类的公有成员和保护成员作为派生类的成员时 xff0c 它们都保持原有的状态 xff0c 而基
  • [C/C++] const 详解(修饰变量、输入参数、返回值、成员函数)

    看到const关键字 xff0c 程序员首先想到的可能是const 常量 const 更大的魅力是它可以修饰函数的参数 返回值 xff0c 甚至函数的定义体 const 是constant 的缩写 xff0c 恒定不变 的意思 被const
  • 怎么理解矩阵的秩

    首先来想一个问题 xff0c 最初的那个人为什么为什么要叫他为 秩 xff0c 为什么不叫 猪 牛 马 xff1f 举个例子就很容易理解 xff0c 大家排队买票 如果大家互相不认识 xff0c 那就会一个排一个 xff0c 非常有秩序 然
  • javascript中的sort()方法

    现在在学习javascript中 xff0c 发现sort 函数是有点奇怪的东西 xff08 可能是本人水平的问题 xff01 xff09 xff0c 于是就在这里记录一下自己找到的东西吧 sort 这个方法的参数很奇怪 xff0c 必须是
  • 【ROS读书笔记】--- 7.参数(parameters)

    时间见证一切 xff01 一 简述二 通过命令行操作参数 查看参数列表 查询参数 设置参数 删除参数 创建和加载参数文件 三 在C 43 43 代码中操作参数 设置参数 读取参数 四 在启动文件中操作参数 设置参数 设置私有参数 从yaml
  • 高位字节与低位字节简单介绍

    一般一个16位 xff08 双字节 xff09 的数据 xff0c 比如 FF1A xff08 16进制 xff09 那么高位字节就是FF xff0c 低位是1A 如果是32位的数据 xff0c 比如 3F68415B 高位字 xff08
  • STL常用容器详细解析

    STL容器的实现原理 STL共有六大组件 1 容器 2 算法 3 迭代器 4 仿函数 6 适配器 STL容器的实现原理 STL来管理数据十分方便 省去了我们自己构建数据结构的时间 其实 STL的实现也是基于我们常见的数据结构 序列式容器 x
  • 相机内参的标定

    最近刚刚开始学习相机的标定 xff0c 也是在师兄的帮助下完成的 过程还是值得记录的 xff0c 于是决定写在自己的第一篇CSDN上 xff0c 便于之后的复习 xff0c 同时也希望能够和大家进行交流 xff0c 相互学习 xff0c 相
  • 利用IMU数据来计算位移

    目标 xff1a 利用IMU测得的加速度信息来计算位移 xff0c 很简单假设是匀加速运动或是匀速运动都可以 xff0c 主要是看问题的背景来具体去确定运动模型 xff0c 这里我就取个简单的匀加速运动模型 学习过程 xff1a 1 了解I
  • 惯导(IMU)的使用

    提示 xff1a 和上一篇关于利用imu计算位移的文章相比 xff0c 这篇我对imu的理解应该是更加深刻了 目录 前言 一 imu调试 二 利用IMU计算旋转 1 引入库 2 读入数据 总结 前言 这次使用的imu和上一篇文章中所提到的i
  • 利用 imu_utils 标定 imu

    目录 前言 一 安装 imu utils 二 编译出现的错误 三 操作步骤 四 结果 前言 记录利用 imu utils 标定 imu xff0c 最近在使用imu做导航 xff0c 要对imu进行标定 xff0c 使用标定得到的加速度的噪
  • 卡尔曼滤波(利用C++编写,ROS下实现)

    提示 xff1a 利用C 43 43 来编写卡尔曼滤波 xff0c 更能比较简单 xff0c 主要是提供一个思路 xff0c 大家可以在这个上面进行修改 附上一个小例题 xff0c 这个卡尔曼滤波适合这个小例题 目录 前言 二 编程部分 1
  • window10安装双系统ubuntu18.04

    win10安装ubuntu18 04 xff0c 有几点需要注意 xff0c 先罗列一下 BIOS模式 硬盘数 我觉得这两个是最烦的所以先重点标记一下 xff01 xff01 xff01 xff08 此教程只适合BIOS为UEFI xff0
  • PX4 OffBoard Control

    终于还是走上了这一步 xff0c 对飞控下手 xff0c 可以说是一张白纸了 记录一下学习的过程方便以后的查阅 目录 一 ubuntu18 04配置px4编译环境及mavros环境 二 PX4的OffBoard控制 1 搭建功能包 2 编写
  • 2021年电子竞赛四天三夜征程—-信号失真度测量装置(A题)

    2021大学生电子设计大赛 1 前言2 正文3 精彩片段分享4 信号失真度测量装置 xff08 A题 xff09 试题 1 前言 个人博客主页 ID Eterlove 一笔一画 xff0c 记录我的学习生活 xff01 站在巨人的肩上Sta
  • 【ROS】在回调函数中发布消息

    在ROS中 xff0c 想在回调函数中发布消息 xff0c 有两个思路 xff1a xff08 1 xff09 把函数写成类的形式 xff0c 把需要的一些变量在类中声明为全局变量 推荐 xff0c 模块化好 xff08 2 xff09 在
  • C语言-结构体对齐

    详细说明参考博客 1条消息 C语言结构体对齐 xff0c 超详细 xff0c 超易懂 haozigegie的博客 CSDN博客 1条消息 pragma pack详解 OuJiang2021的博客 CSDN博客 pragma pack 以下个
  • PowerShell 远程执行任务的方法和步骤

    PowerShell 远程执行任务的方法步骤 1 查看WinRM服务 Get Service WinRM 如果为关闭状态 xff0c 以管理员权限启动PowerShell窗口 xff0c 执行命令 Enable PSRemoting For
  • 电影网站推荐

    http www amobbs com thread 5599359 1 1 html 作者 solisgood 几年前当我还是一个小白的时候 xff0c 在网上常常会看到一些教人找电影的攻略 xff0c 他们推荐的无非是电影天堂 电影FM
  • Qt调用opencv实现yolov3对视频进行目标检测

    欢迎加QQ学习交流群309798848 依赖 xff1a 支持CUDA的opencv4 3 0 xff0c demo cfg xff0c demo final weights xff0c demo names demo cfg xff0c