win10在darknet训练完成后用C++调用实现目标检测

1.目的

最终让图片目标检测功能封装到动态库文件中,供其它函数直接调用

2.准备工作

软件
1.visual studio 2015
2.opencv3.4.7(版本尽量新,3.4.0貌似不行)

文件
1.darknet训练完成后的weights格式文件yolov3.weights
2.test时的cfg文件yolov3.cfg
3.样本names文件coco.names
4.测试需求的jpg图片cat.jpg

3.建立工程

3.1 opencv3.4.7配置在vs2015的release x64环境里面(网上教程很多)

win10在darknet训练完成后用C++调用实现目标检测_第1张图片
win10在darknet训练完成后用C++调用实现目标检测_第2张图片

3.2 新建opencvdarknet动态库工程文件(DLL

3.2.1新建OpencvDaeknet.cpp文件,代码如下:

// It is based on the OpenCV project.
#include "OpencvDarknet.h"
#include 
#include 


#include 
#include 
#include 


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

// Initialize the parameters
float confThreshold = 0.5; // 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 nms
vector<messages> 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);

vector<messages> detect(string names,string cfg,string weights,string img)
{
	vector<messages> vctRes;


	// Load names of classes
	string classesFile = names;
	ifstream ifs(classesFile.c_str());
	string line;
	while (getline(ifs, line)) classes.push_back(line);

	// Give the configuration, weight and image files for the model
	String modelConfiguration = cfg;
	String modelWeights = weights;
	string image = img;

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

	// Open a video file or an image file or a camera stream.
	string outputFile;

	Mat frame, blob;

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

	try {
		ifstream ifile(image);
		if (!ifile) throw("error");
		frame = imread(image);
		image.replace(image.end() - 4, image.end(), "_yolo_out_cpp.jpg");
		outputFile = image;

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

	}


	// Create a 4D blob from a frame.
	blob = blobFromImage(frame, 1 / 255.0, cvSize(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
	vctRes = 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
	Mat detectedFrame;
	frame.convertTo(detectedFrame, CV_8U);
	imwrite(outputFile, detectedFrame);

	imshow(kWinName, frame);

	//show the output
	for (int i = 0; i < vctRes.size(); i++)
	{
		messages mess = vctRes[i];
		cout << mess.index << " " << mess.x << " " << mess.y << " " << mess.rotate << endl;
	}
	waitKey(0);
	return vctRes;
}


// Remove the bounding boxes with low confidence using nms
vector<messages> postprocess(Mat& frame, const vector<Mat>& outs)
{
	vector<int> classIds;
	vector<float> confidences;
	vector<Rect> boxes;
	messages mess;
	vector<messages> vctRes;

	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 nms 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];
		//cout << box.x << " " << box.y <<" "<
		drawPred(classIds[idx], confidences[idx], box.x, box.y, box.x + box.width, box.y + box.height, frame);
		mess.index = to_string(idx);
		mess.x = box.x + box.width / 2;
		mess.y = box.y + box.height / 2;
		mess.rotate = box.width / box.height >= 1;

		vctRes.push_back(mess);
	}
	return vctRes;
}

// Draw the predicted bounding box
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
	//Draw a rectangle displaying the bounding box
	rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 178, 50), 3);

	//Get the label for the class name and its confidence
	string label = format("%.2f", conf);
	if (!classes.empty())
	{
		CV_Assert(classId < (int)classes.size());
		label = 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 - 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);
}

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

3.2.2新建OpencvDaeknet.h文件,代码如下:

#pragma once
#include 
#include 

using namespace std;

typedef struct messages {
	string index;
	float x;
	float y;
	bool rotate;
}messages;

__declspec(dllexport) vector<messages> detect(string names, string cfg, string weights, string image);

3.2.3 点击 生成–>重新生成解决方案 后生成dll文件
win10在darknet训练完成后用C++调用实现目标检测_第3张图片

3.3 新建opencvdarknet_test工程(控制台应用程序

3.3.1 将上面opencvdarknet产生的OpencvDarknet.dll,OpencvDarknet.lib,OpencvDarknet.h复制到Opencvdarknet_test文件里面,详情如下:
win10在darknet训练完成后用C++调用实现目标检测_第4张图片
OpencvDarknet.dll,OpencvDarknet.lib文件
win10在darknet训练完成后用C++调用实现目标检测_第5张图片
OpencvDarknet.h 文件
win10在darknet训练完成后用C++调用实现目标检测_第6张图片
复制完以后的现状

3.3.2 将OpencvDarknet.h 文件添加到头文件中,OpencvDarknet.lib文件添加到资源文件中,最后新建源文件OpencvDarknet_test.cpp 文件,OpencvDarknet_test.cpp如下:

#include 
#include "OpencvDarknet.h"
#include 

using namespace std;

void main()
{
	string names = "coco.names";
	string cfg = "yolov3.cfg";
	string weights = "yolov3.weights";
	string img = "cat.jpg";
	detect( names,  cfg,  weights,  img);

}

3.3.3 将文章开头需要的文件复制到Opencvdarknet_test文件夹里面,如下:

win10在darknet训练完成后用C++调用实现目标检测_第7张图片
cat.jpg待检测图片文件,coco.names文件,yolov3.cfg文件,yolov3.weights文件

3.3.4 按Ctrl+F5得到检测结果
win10在darknet训练完成后用C++调用实现目标检测_第8张图片

参考链接:
https://www.aiuai.cn/aifarm822.html
https://blog.csdn.net/m0_37170593/article/details/76445972

你可能感兴趣的:(win10在darknet训练完成后用C++调用实现目标检测)