基于opencv dnn模块 的caffe模型的调用

来源:互联网 发布:python读取json文件 编辑:程序博客网 时间:2024/05/17 21:42

      2017年7月5日:更正 自己在博客后面写到最终调用ssd caffe模型时一直不能出结果,今天下午笔者新建了一个工程再次跑程序,发现等了1分钟就出结果了,所以说啊,调bug真的是一件很无语的事情。有时候你都不知道为什么这样就好了,我的运行结果如下:

                 



      话不多说,自己最近在做一个小任务,任务主要目的在windows 下利用 opencv调用训练好的caffe模型做多目标检测。至于为啥这样搞,因为笔者是图像处理相关专业,以后难免会在工程中用到。当然要研究深度学习理论,还是在ubuntu下去搞。

      opencv真的是一个非常强大并且好用的图像处理库。自从进入3.X时代以后,OpenCV将代码库分成了两部分,分别是稳定的核心功能库和试验性质的contrib库。并且从3.1以后,编译好的版本中就没有现成的x86平台的库了,想用就必须自己从源码编译。之前都是直接下载编译好的版本。而contrib库中的dnn模块(笔者是opencv3.2.0加最新的contrib库)更是支持caffe、TensorFlow、torch三种深度学习框架。可以自己写网络层,读取网络结构和已经训练好的模型。因此,首先要自己编译opencv及contrib库.

   1 运行环境及前期准备

      Windows 7 64位

      VisualStudio 2013

      CMake 3.9

      OpenCV 3.2.0 

      OpenCV contrib库(最新版)

   2 编译OpenCV及contrib库

     编译部分自己主要参考了两篇博客:

     http://blog.csdn.net/weixinhum/article/details/70982048

     http://blog.csdn.net/guyubit/article/details/51994171

     说来奇怪,自己在编译的时候基本上没遇到bug,如果有遇到bug的同学请参考上两篇博客,自己编译过程大概如下(多提一句,下载好的opencv3.2.0和contrib库放在同一根目录下):

      打开CMake3.9,选择你的opencv源码路径和新建输出路径,然后点击configure,选择编译器,我选择的是visual studio 12 2013 win64编译器。点击finish。笔者路径如下图所示:

             

     configure第一次完成后,因为要编译contrib库,因此需要将额外的opencv_contrib加入到工程中第二次编译,在配置表中找到“OPENCV_EXTRA_MODUALS_PATH”,设置其参数值为opencv_contrib源码包中的modules目录,设置完成后,点击configure进行第二次编译。第二次编译后,点击generate,生成了OPENCV_sln工程文件。此时,我们打开buildopencv文件夹就多了一个OPENCV_sln。接下来需要生成相应的lib以及dll文件等,用vs2013打开OPENCV_sln文件,选择debug x64环境,并选择重新生成整个解决方案,生成之后,找到CMakeTargets中的INSTALL,点击右键-仅用于项目-仅生成INSTALL,完成后多了一个install文件夹。release版本同样进行相同的操作。至此,所有的编译以及生成工作完成。完成后build文件夹里多了一个install文件夹,里面和我们从OpenCV官网下载的差不多,配置起来也基本一样。

     至于vs2013配置opencv笔者就不多提了,这基本是搞图像处理人人要掌握的基本功,具体的配置可以参考一下博客:http://blog.csdn.net/ailunlee/article/details/70254835

   3 运行官方示例demo

     opencv_contrib-master\modules\dnn\samples路径下有一个官方示例程序caffe_googlenet.cpp,该程序主要是调用训练好的caffemodel做分类进行目标检测。程序的主要说明请参考:

       http://docs.opencv.org/master/d5/de7/tutorial_dnn_googlenet.html

      该介绍详细说明了程序的功能及每一步的作用。

       具体做法:新建一个工程,将源码拷进工程目录下,下载对应的caffemodel及prototx文件和输入图像至工程目录下,笔者用的是bvlc_googlenet.caffemodel和bvlc_googlenet.prototxt。运行demo,此时,不出意外(笔者是真的遇到了这个bug),程序是会报错的。这真的是无奈啊,明明是官方给的,但依旧会有错误,于是笔者开始了漫长的调bug阶段。最终是终于解决了。

            

     大家可以参考下面的评论:http://www.answers.opencv.org/question/129140/goturn-tracker-error/ 

     具体做法是:找到opencv_contrib-master\modules\tracking\src目录下的gtrTracker.cpp,打开后将源码修改如下:

                            

           然后将caffe_googlenet.cpp的代码修改如下:

              

      最后,完美运行,输入图像

              

     输出结果:

              

   4 运行基于ssd caffe模型的目标检测程序

     话不多说,直接上代码。

#include <opencv2/dnn.hpp>#include <opencv2/imgproc.hpp>#include <opencv2/highgui.hpp>using namespace cv;using namespace cv::dnn;#include <fstream>#include <iostream>#include <cstdlib>using namespace std;const size_t width = 300;const size_t height = 300;Mat getMean(const size_t& imageHeight, const size_t& imageWidth){Mat mean;const int meanValues[3] = { 104, 117, 123 };vector<Mat> meanChannels;for (size_t i = 0; i < 3; i++){Mat channel(imageHeight, imageWidth, CV_32F, Scalar(meanValues[i]));meanChannels.push_back(channel);}cv::merge(meanChannels, mean);return mean;}Mat preprocess(const Mat& frame){Mat preprocessed;frame.convertTo(preprocessed, CV_32FC3);resize(preprocessed, preprocessed, Size(width, height)); //SSD accepts 300x300 RGB-imagesMat mean = getMean(width, height);cv::subtract(preprocessed, mean, preprocessed);return preprocessed;}const char* about = "This sample uses Single-Shot Detector ""(https://arxiv.org/abs/1512.02325)""to detect objects on image\n"; // TODO: linkconst char* params= "{ help         | false | print usage         }""{ proto          |deploy.prototxt    | model configuration }""{ model          |VGG_VOC0712_SSD_300x300_iter_120000.caffemodel     | model weights       }""{ image          |rgb.jpg        | image for detection }""{ min_confidence | 0.5   | min confidence      }";int main(int argc, char** argv){cv::CommandLineParser parser(argc, argv, params);if (parser.get<bool>("help")){std::cout << about << std::endl;parser.printMessage();return 0;}cv::dnn::initModule();          //Required if OpenCV is built as static libsString modelConfiguration = parser.get<string>("proto");String modelBinary = parser.get<string>("model");//! [Create the importer of Caffe model]Ptr<dnn::Importer> importer;// Import Caffe SSD modeltry{importer = dnn::createCaffeImporter(modelConfiguration, modelBinary);}catch (const cv::Exception &err) //Importer can throw errors, we will catch them{cerr << err.msg << endl;}//! [Create the importer of Caffe model]if (!importer){cerr << "Can't load network by using the following files: " << endl;cerr << "prototxt:   " << modelConfiguration << endl;cerr << "caffemodel: " << modelBinary << endl;cerr << "Models can be downloaded here:" << endl;cerr << "https://github.com/weiliu89/caffe/tree/ssd#models" << endl;exit(-1);}//! [Initialize network]dnn::Net net;importer->populateNet(net);importer.release();          //We don't need importer anymore//! [Initialize network]cv::Mat frame = cv::imread(parser.get<string>("image"), -1);//! [Prepare blob]Mat preprocessedFrame = preprocess(frame);dnn::Blob inputBlob = dnn::Blob::fromImages(preprocessedFrame); //Convert Mat to dnn::Blob image//! [Prepare blob]//! [Set input blob]net.setBlob(".data", inputBlob);                //set the network input//! [Set input blob]//! [Make forward pass]net.forward();                                  //compute output//! [Make forward pass]//! [Gather output]dnn::Blob detection = net.getBlob("detection_out");Mat detectionMat(detection.rows(), detection.cols(), CV_32F, detection.ptrf());float confidenceThreshold = parser.get<float>("min_confidence");for (int i = 0; i < detectionMat.rows; i++){float confidence = detectionMat.at<float>(i, 2);if (confidence > confidenceThreshold){size_t objectClass = detectionMat.at<float>(i, 1);float xLeftBottom = detectionMat.at<float>(i, 3) * frame.cols;float yLeftBottom = detectionMat.at<float>(i, 4) * frame.rows;float xRightTop = detectionMat.at<float>(i, 5) * frame.cols;float yRightTop = detectionMat.at<float>(i, 6) * frame.rows;std::cout << "Class: " << objectClass << std::endl;std::cout << "Confidence: " << confidence << std::endl;std::cout << " " << xLeftBottom<< " " << yLeftBottom<< " " << xRightTop<< " " << yRightTop << std::endl;Rect object(xLeftBottom, yLeftBottom,xRightTop - xLeftBottom,yRightTop - yLeftBottom);rectangle(frame, object, Scalar(0, 255, 0));}}imshow("detections", frame);waitKey(0);return 0;} 

     笔者使用的是VGG_VOC0712_SSD_300x300_iter_120000.caffemodel的模型及网络文件deploy.prototxt

在这里,需要对deploy.prototxt进行修改,否则程序会报错,这里参考了如下博客,不过按照修改后依旧会报一些奇怪的错误 http://blog.csdn.net/dzkd1768/article/details/63785665#comments 

      于是自己最后修改主要如下:

     (1)Normalize->NormalizeBBox
     (
2)norm_para->normalize_bbox_para

     (3)step行->直接删除   

     (4)offset行->直接删除

     (5)nms_param变量->直接删除,仅留下nms_threshold: 0.45  top_k: 400

     最后运行程序,笔者的程序是终于可以跑通了,但是,结果如下:笔者等了10多分钟,都没有出最后的结果。

             

     而实际这个程序的结果,应该是这样的:

             

     至于为什么不出结果,笔者可以比较肯定的是在修改网络层的时候出现了问题,但程序却并没有报错。至于问题到底在哪,受限于笔者现目前的水平,对ssd模型的网络层不是很熟悉,等以后深入了解深度学习后再回来解决,当然,也希望有大神能出来给我解惑,现目前我确实没找到一个能跑出结果的对应的deploy.prototxt。

     

     

            

       

       

     

       

       

      

    

    

       



    

     

原创粉丝点击