1. 程式人生 > >Opencv3.4.3呼叫SSD caffe模型進行物體檢測

Opencv3.4.3呼叫SSD caffe模型進行物體檢測

原始碼

#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>

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

const size_t width = 300;
const size_t height = 300;
const float meanVal = 127.5;
const float scaleFactor = 0.007843f;
const char* classNames[] = { "background",
"aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair",
"cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor" };

String modelFile = "C:/Users/18301/Desktop/models_VGGNet_VOC0712Plus_SSD_300x300/models/VGGNet/VOC0712Plus/SSD_300x300/VGG_VOC0712Plus_SSD_300x300_iter_240000.caffemodel";
String model_text_file = "C:/Users/18301/Desktop/models_VGGNet_VOC0712Plus_SSD_300x300/models/VGGNet/VOC0712Plus/SSD_300x300/deploy.prototxt";

int main() 
{
	VideoCapture capture;
	capture.open(0);
	namedWindow("input", CV_WINDOW_AUTOSIZE);
	int w = capture.get(CAP_PROP_FRAME_WIDTH);
	int h = capture.get(CAP_PROP_FRAME_HEIGHT);
	printf("frame width : %d, frame height : %d", w, h);

	// set up net
	Net net = readNetFromCaffe(model_text_file, modelFile);

	Mat frame;
	//while (capture.read(frame)) //注意:這裡提供了兩種模式,呼叫攝像頭的時候把該句取消註釋即可
	while (1)
	{
		frame = imread("C:/Users/18301/Desktop/car.jpg");
		imshow("input", frame);

		//預測
		Mat inputblob = blobFromImage(frame, scaleFactor, Size(width, height), meanVal, false);
		net.setInput(inputblob, "data");
		Mat detection = net.forward("detection_out");

		//檢測
		Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
		float confidence_threshold = 0.3;
		for (int i = 0; i < detectionMat.rows; i++) {
			float confidence = detectionMat.at<float>(i, 2);
			if (confidence > confidence_threshold) {
				size_t objIndex = (size_t)(detectionMat.at<float>(i, 1));
				float tl_x = detectionMat.at<float>(i, 3) * frame.cols;
				float tl_y = detectionMat.at<float>(i, 4) * frame.rows;
				float br_x = detectionMat.at<float>(i, 5) * frame.cols;
				float br_y = detectionMat.at<float>(i, 6) * frame.rows;

				Rect object_box((int)tl_x, (int)tl_y, (int)(br_x - tl_x), (int)(br_y - tl_y));
				rectangle(frame, object_box, Scalar(0, 0, 255), 2, 8, 0);
				putText(frame, format("%s", classNames[objIndex]), Point(tl_x, tl_y), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255, 0, 0), 2);
			}
		}
		imshow("ssd-video-demo", frame);
		char c = waitKey(5);
		if (c == 27) 
		{ // ESC退出
			break;
		}
	}
	capture.release();
	waitKey(0);
	return 0;
}

實驗結果

在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

不過說實話效果不是太好,因為這個SSD模型是基於VGG16的,可能特徵表徵能力不是太強吧~視訊檢測就更差了,就不展示了