opencv调用tf训练好的模型

        tensorflow训练好的模型,如何使用?在tensorflow上使用,当然很好实现啊。但是在实际生产部署时,主机要求不安装tf,也没有显卡,何解?本博文对此做一个记录。

一、opencv dnn模块

1、OpenCV 3.3版本发布,对深度学习(dnn模块)提供了更好的支持,dnn模块目前支持Caffe、TensorFlow、Torch、PyTorch等深度学习框架。

2、OpenCV的dnn模块调用TesorFlow训练的MoblieNet模型

3、关于opencv的版本,最好是3.4.0及以上吧。

4、opencv调用tf模型文档


二、使用步骤

1、tf训练模型,并保存成.pb文件

2、使用opencv的readNetFromTensorflow函数加载.pb文件

3、帖几行关键性代码

String weights = "nn.pb";
dnn::Net net = cv::dnn::readNetFromTensorflow(weights);
Mat img = imread(files[i], 1);
Mat inputBlob = dnn::blobFromImage(img, 0.00390625f, Size(256, 256), Scalar(), false,false); 
net.setInput(inputBlob, "data");//set the network input, "data" is the name of the input layer     
Mat pred = net.forward("fc2/prob");

4、dnn::blobFromImage函数解读(这个很重要,参数不对,直接影响预测结果)

opencv中的函数声明

  CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(),
                                   const Scalar& mean = Scalar(), bool swapRB=true, bool crop=true);
对于各参数的文档解释
 /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center,
     *  subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels.
     *  @param image input image (with 1-, 3- or 4-channels).
     *  @param size spatial size for output image
     *  @param mean scalar with mean values which are subtracted from channels. Values are intended
     *  to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
     *  @param scalefactor multiplier for @p image values.
     *  @param swapRB flag which indicates that swap first and last channels
     *  in 3-channel image is necessary.
     *  @param crop flag which indicates whether image will be cropped after resize or not
     *  @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
     *  dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
     *  If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
     *  @returns 4-dimansional Mat with NCHW dimensions order.
     */

第一个参数,InputArray image,表示输入的图像,可以是opencv的mat数据类型。

第二个参数,scalefactor,这个参数很重要的,如果训练时,是归一化到0-1之间,那么这个参数就应该为0.00390625f (1/256),否则为1.0

第三个参数,size,应该与训练时的输入图像尺寸保持一致。

第四个参数,mean,这个主要在caffe中用到,caffe中经常会用到训练数据的均值。tf中貌似没有用到均值文件。

第五个参数,swapRB,是否交换图像第1个通道和最后一个通道的顺序。

第六个参数,crop,如果为true,就是裁剪图像,如果为false,就是等比例放缩图像。


三、其他注意事项

1、注意输入和输出name的对应。下面是c++的代码,tf中的输入就应该name为data,输出就应该name为fc2/prob

net.setInput(inputBlob, "data");   
pred = net.forward("fc2/prob");
2、如果pb文件大于200m,小心出现莫名其妙的报错。 sources\modules\core\src\matrix.cpp:362: error: (-215) u != 0 in function cv::Mat::create




猜你喜欢

转载自blog.csdn.net/hust_bochu_xuchao/article/details/79428759