win10+VS2015+opencv3.4.3调用darknet模型

opencv必须大于等于3.4.2

opencv在线文档:

https://docs.opencv.org/trunk/db/d30/classcv_1_1dnn_1_1Net.html#a98ed94cb6ef7063d3697259566da310b

参考文章:

https://blog.51cto.com/gloomyfish/2095418

https://blog.csdn.net/windfly_al/article/details/84873767

https://blog.csdn.net/shanglianlm/article/details/80030569

blobFromImage函数

  • 第一个参数,InputArray image,表示输入的图像,可以是opencv的mat数据类型。
  • 第二个参数,scalefactor,这个参数很重要的,如果训练时,是归一化到0-1之间,那么这个参数就应该为0.00390625f (1/256),否则为1.0
  • 第三个参数,size,应该与训练时的输入图像尺寸保持一致。
  • 第四个参数,mean,这个主要在caffe中用到,caffe中经常会用到训练数据的均值。tf中貌似没有用到均值文件。
  • 第五个参数,swapRB,是否交换图像第1个通道和最后一个通道的顺序。
  • 第六个参数,crop,如果为true,就是裁剪图像,如果为false,就是等比例放缩图像。
// Opencv_ObjectDetection.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include


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

vector classes;
vector getOutputsNames(Net&net)
{
	static vector names;
	if (names.empty())
	{
		//返回加载模型中所有层的输入和输出形状(shape)
		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;
}

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("%.5f", 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);
}

void postprocess(Mat& frame, const vector& outs, float confThreshold, float nmsThreshold)
{
	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);
	}
}

int main()
{
	//加载网络模
	String modelConfiguration = "E:/_darknet/x64/data/METAL/darknet19_448.cfg";
	String modelBinary = "E:/_darknet/x64/backup/_darknet19_448_final.weights";
	dnn::Net net = readNetFromDarknet(modelConfiguration, modelBinary);
	if (net.empty())
	{
		printf("Could not load net...\n");
		return 0;
	}

	/*要求网络在支持的地方使用特定的计算后端
	*如果opencv是用intel的推理引擎库编译的,那么dnn_backend_default意味着dnn_backend_interrusion_引擎
	*否则等于dnn_backend_opencv。
	*/
	net.setPreferableBackend(DNN_BACKEND_OPENCV);
	//要求网络对特定目标设备进行计算
	net.setPreferableTarget(DNN_TARGET_CPU);


	//2.加载分类信息
	//vector classNamesVec;
	ifstream classNamesFile("E:/_darknet/x64/data/METAL/labels.txt");
	if (classNamesFile.is_open())
	{
		string className = "";
		while (std::getline(classNamesFile, className))
			classes.push_back(className);
	}

	//3.加载图像
	Mat frame = imread("E:/_darknet/x64/data/METAL/abnor/190324141318_00002/s001_abnor.jpg");
//	Mat inputBlob = blobFromImage(frame, 1 / 255.F, Size(500, 860), Scalar(), true, false);

	std::vector frames;
	frames.push_back(frame);

	Mat inputBlob = blobFromImages(frames, 1 / 255.F, Size(500, 860), Scalar(), true, false);


	net.setInput(inputBlob, "data");

	//4.检测和显示
	//获得“dectection_out"的输出
	vector outs;
	net.forward(outs, getOutputsNames(net));
	
	//如果是目标检测任务绘制矩形框
	double thresh = 0.5;
	double nms_thresh = 0.25;
	//postprocess(frame, outs, thresh, nms_thresh);

	//reshape the blob to 1x1000 matrix // 1000个分类
	Mat probMat = outs[0].reshape(1, 1); 
	Point classNumber;
	double classProb;
	// 可能性最大的一个
	minMaxLoc(probMat, NULL, &classProb, NULL, &classNumber);
	// 分类索引号
	int classIdx = classNumber.x; 
	printf("current image classification : %s, possible : %.8f \n", classes.at(classIdx).c_str(), classProb);
	//putText(frame, classes.at(classIdx), Point(20, 20), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 255), 2, 8);

	vector layersTimings;
	double freq = getTickFrequency() / 1000;
	double time = net.getPerfProfile(layersTimings) / freq;
	/*ostringstream ss;
	ss << "detection time: " << time << " ms";
	putText(frame, ss.str(), Point(20, 60), 0, 0.5, Scalar(0, 0, 255));*/
	string label = format("class: ")+classes.at(classIdx)+ format(" ,time: %.2f ms",time);
	putText(frame, label, Point(20,20), 0, 0.5, Scalar(0, 0, 255));
	
	namedWindow("OCT");
	imshow("OCT", frame);
	waitKey();
    return 0;
}

 

你可能感兴趣的:(深度学习,深度学习)