这里我们使用MobileNetSSD进行目标检测,模型文件是下载的这个:https://github.com/PINTO0309/MobileNet-SSD-RealSense/tree/master/caffemodel/MobileNetSSD
具体使用的代码如下:
void main() {
cv::Mat i1=cv::imread("51.jpg");
cv::dnn::Net net;
net = cv::dnn::readNet("MobileNetSSD_deploy.caffemodel", "MobileNetSSD_deploy.prototxt");
//定义所有分类的名称
vector<String> objName;
objName.push_back("background");
objName.push_back("aeroplane");
objName.push_back("bicycle");
objName.push_back("bird");
objName.push_back("boat");
objName.push_back("bottle");
objName.push_back("bus");
objName.push_back("car");
objName.push_back("cat");
objName.push_back("chair");
objName.push_back("cow");
objName.push_back("diningtable");
objName.push_back("dog");
objName.push_back("horse");
objName.push_back("motorbike");
objName.push_back("person");
objName.push_back("pottedplant");
objName.push_back("sheep");
objName.push_back("sofa");
objName.push_back("train");
objName.push_back("tvmonitor");
int h = i1.size().height;
int w = i1.size().width;
cv::Mat blob=cv::dnn::blobFromImage(i1,
0.007843,
Size(300, 300),
Scalar(127.5, 127.5, 127.5),
false,false);
net.setInput(blob);
cv::Mat detection = net.forward("detection_out");
//因为推理出来的结果形状是1*1*100*7,先切到形状100*7
cv::Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
cout << detectionMat.size << endl;
//设置阈值
float confidenceThreshold = 0.2;
for (int i = 0; i < detectionMat.rows;i++) {
float confidence = detectionMat.at<float>(i,2);
if (confidence> confidenceThreshold) {
int idx = static_cast<int>(detectionMat.at<float>(i, 1));
//cout << "idx is " << idx << endl;
int left = static_cast<int>(detectionMat.at<float>(i, 3) * w);
int top = static_cast<int>(detectionMat.at<float>(i, 4) * h);
int right = static_cast<int>(detectionMat.at<float>(i, 5) * w);
int bottom = static_cast<int>(detectionMat.at<float>(i, 6) * h);
cv::rectangle(i1,Rect(left, top, right-left, bottom-top), Scalar(255, 0, 0), 2);
string label = objName[idx];
cv::putText(i1, label,cv::Point(int((left + right) / 2),int((top+bottom)/2)),
FONT_HERSHEY_SIMPLEX,0.5, Scalar(0, 255, 0));
}
}
cv::imshow("i1",i1);
cv:: waitKey(0);
}
运行结果如下:
版权声明:本文为CSDN博主「喝粥也会胖的唐僧」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhou_438/article/details/122927251
暂无评论