darknet框架调用yolov3模型流程

1.载入模型与网络文件,网络预处理

string CfgPath="...\\name.cfg";
string WeightsPath="...\\name.weights";
network net = load_network((char*)CfgPath.c_str(), (char*)WeightsPath.c_str(), 0);///加载网络,加载成功,终端会打印出网络各层
set_batch_network(net, 1);///设置网络batch, 预测时batch必须设置为1

2. 输入数据预处理

Mat frame=imread("testpath");
Mat resizeImg;
resize(frame, resizeImg, Size(net->w, net->h));///opencv API
size_t resizeSize = net->w*net->h * 3 * sizeof(float);
float* inputSizeImg = (float*)malloc(resizeSize);
imgConvert(resizeImg, inputSizeImg);
void imgConvert(const cv::Mat& img, float* dst) 
{
	uchar *data = img.data;
	int h = img.rows;
	int w = img.cols;
	int c = img.channels();
	for (int k = 0; k < c; ++k) {
		for (int i = 0; i < h; ++i) {
			for (int j = 0; j < w; ++j) {
				dst[k*w*h + i * w + j] = data[(i*w + j)*c + k] / 255.;
			}
		}
	}
}

3.网络推理

float nms = 0.35;///置信度阈值
int classes = 2;///类型数目
network_predict(net, resizeImg);///网络推理
int nboxes = 0;///预测框个数
detection *dets = get_network_boxes(net, frame.cols, frame.rows, confidenceThreshold, 0.5, 0, 1, &nboxes);
if (nms)
{
	do_nms_sort(dets, nboxes, classes, nms);///非极大值抑制
}

4.计算输出检测框

vectorboxes;
boxes.clear();
for (int i = 0; i < nboxes; i++)
{
	bool flag = 0;
	int className;
	for (int j = 0; j < classes; j++)
	{
            if (dets[i].prob[j] > confidenceThreshold)
            {
                 if (!flag)
                 {
                     flag = 1;
                     className = j;
                 }
            }	   
	}
	if (flag)
	{
		int left = (dets[i].bbox.x - dets[i].bbox.w / 2.)*frame.cols;
		int right = (dets[i].bbox.x + dets[i].bbox.w / 2.)*frame.cols;
		int top = (dets[i].bbox.y - dets[i].bbox.h / 2.)*frame.rows;
		int bot = (dets[i].bbox.y + dets[i].bbox.h / 2.)*frame.rows;
		if (left < 0)
			left = 0;
		if (right > frame.cols - 1)
			right = frame.cols - 1;
		if (top < 0)
			top = 0;
		if (bot > frame.rows - 1)
			bot = frame.rows - 1;
		Rect box(left, top, fabs(left - right), fabs(top - bot));///opencv Rect类
		boxes.push_back(box);
	}
}
free_detections(dets, nboxes);
free(resizeImg);
if (boxes.size() < 1)
{
	return -1;
}

 

你可能感兴趣的:(Darknet,darknet,模型调用,c++,API)