opencv进阶-SSD模型实时对象检测(摄像头)
Posted 殇堼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了opencv进阶-SSD模型实时对象检测(摄像头)相关的知识,希望对你有一定的参考价值。
图像分类+位置信息=对象检测
支持的对象检测网络:
全部代码
#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 labelFile = "D:/opencv-4.1.0/models/ssd/labelmap_det.txt";
String model_text_file = "D:/opencv-4.1.0/models/ssd/MobileNetSSD_deploy.prototxt";
String modelFile = "D:/opencv-4.1.0/models/ssd/MobileNetSSD_deploy.caffemodel";
int main(int argc, char** argv) {
VideoCapture capture;
capture.open(0);
namedWindow("input", 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);
net.setPreferableBackend(DNN_BACKEND_OPENCV);
net.setPreferableTarget(DNN_TARGET_CPU);
Mat frame;
while (capture.read(frame)) {
flip(frame, frame, 1);
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.25;
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);
}
}
vector < double>layerstimings;
double freq = getTickFrequency() / 1000;
double time = net.getPerfProfile(layerstimings) / freq;
ostringstream ss;
ss << "FPS" << 1000 / time << ";time:" << time << "ms";
putText(frame, ss.str(), Point(20, 20), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255), 2, 8);
imshow("ssd-video-demo", frame);
char c = waitKey(5);
if (c == 27) { // ESC退出
break;
}
}
capture.release();//释放资源
waitKey(0);
return 0;
}
效果展示
以上是关于opencv进阶-SSD模型实时对象检测(摄像头)的主要内容,如果未能解决你的问题,请参考以下文章