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;
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";
String objNames[] = { "background",
"aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair",
"cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor" };//只检测20种对象
int main() {
Mat src = imread("D:/images/objects.jpg");
if (src.empty()) {
printf("could not load image...\\n");
return -1;
}
imshow("input image", src);
Net net = readNetFromCaffe(model_text_file, modelFile);
//构建输入
Mat blobImage = blobFromImage(src, 0.007843,Size(300, 300),Scalar(127.5, 127.5, 127.5), true, false);
printf("blobImage width : %d, height: %d\\n", blobImage.cols, blobImage.rows);
net.setInput(blobImage, "data");
//执行推理
Mat detection = net.forward("detection_out");
Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
float confidence_threshold = 0.2;
//解析输出数据
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) * src.cols;
float tl_y = detectionMat.at<float>(i, 4) * src.rows;
float br_x = detectionMat.at<float>(i, 5) * src.cols;
float br_y = detectionMat.at<float>(i, 6) *src.rows;
Rect object_box((int)tl_x, (int)tl_y, (int)(br_x - tl_x), (int)(br_y - tl_y));
rectangle(src, object_box, Scalar(0, 0, 255), 2, 8, 0);
putText(src, format("%.2f,%s", confidence, objNames[objIndex].c_str()), Point(tl_x, tl_y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 0, 0), 2);
}
}
imshow("ssd-demo",src);
waitKey(0);
return 0;
}
效果展示
以上是关于opencv进阶-SSD模块物体检测(非实时)的主要内容,如果未能解决你的问题,请参考以下文章