opencv使用MobileNetSSD进行目标检测

这里我们使用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);
}

运行结果如下:

 

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值