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

依赖:支持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 

#include 
#include 
#include 
#include 
#include 

#include 
#include 
#include 

#include  
#include 

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

// Remove the bounding boxes with low confidence using non-maxima suppression
void postprocess(Mat& frame, const vector& 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 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 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 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 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 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& outs)
{
	vector classIds;
	vector confidences;
	vector 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 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 getOutputsNames(const Net& net)
{
	static vector names;
	if (names.empty())
	{
		//Get the indices of the output layers, i.e. the layers with unconnected outputs
		vector outLayers = net.getUnconnectedOutLayers();

		//get the names of all the layers in the network
		vector 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 。

你可能感兴趣的:(opencv)