接上一篇文章,上一篇文章简单了训练一个101层的残差网络并保持为pb格式,下面在c++中读取图片进行预测,用Mat转化为tensor的形式,opencv接口安装、tensorflow编译在前面的文章都有说到在这里不再累赘,进模型之前图片预处理较简单,只是做了个去均值操作,灰度什么的没做处理,下面看下代码:
#include <iostream> #include <opencv2/opencv.hpp> #include
"tensorflow/cc/saved_model/loader.h" #include
"tensorflow/core/framework/graph.pb.h" #include
"tensorflow/core/protobuf/meta_graph.pb.h" #include
"tensorflow/cc/saved_model/tag_constants.h" using namespace std; using
namespace cv; using namespace tensorflow; //参考
https://stackoverflow.com/questions/39379747/import-opencv-mat-into-c-tensorflow-without-copying
void cvmat_to_tensor(cv::Mat img,Tensor* tensor,int rows,int cols){
cv::resize(img,img,cv::Size(rows,cols)); img=img-128.0; float
*p=tensor->flat<float>().data(); cv::Mat imagePixels(rows,cols,CV_32FC1,p);
img.convertTo(imagePixels,CV_32FC1); } int main(int argc, char *argv[]) { int
rows=224; int cols=224; int chanel=3; string
modelpath="/Users/zhoumeixu/Documents/python/credit-transform/model/2"; string
picturepath="/Users/zhoumeixu/Desktop/图像测试/美女.jpg"; string inputname="input";
string outputname="output"; cv::Mat img = cv::imread(picturepath);
tensorflow::SessionOptions sess_options; tensorflow::RunOptions run_options;
tensorflow::SavedModelBundle bundle; Status status; status
=tensorflow::LoadSavedModel(sess_options, run_options, modelpath,
{tensorflow::kSavedModelTagServe}, &bundle); if(!status.ok()){
cout<<status.ToString()<<endl; } tensorflow::MetaGraphDef graph_def =
bundle.meta_graph_def; std::unique_ptr<tensorflow::Session>& session =
bundle.session; Tensor x(tensorflow::DT_FLOAT, tensorflow::TensorShape({rows,
cols,chanel})); cvmat_to_tensor(img,&x,rows,cols);
std::vector<std::pair<string, tensorflow::Tensor>> inputs;
inputs.push_back(std::pair<std::string, tensorflow::Tensor>(inputname, x));
Tensor tensor_out(tensorflow::DT_FLOAT, TensorShape({1,20}));
std::vector<tensorflow::Tensor> outputs={{ tensor_out }}; status=
session->Run(inputs, {outputname}, {}, &outputs); if (!status.ok()) {
cout<<"failure"<<endl; std::cout << status.ToString() << "\n"; return 1; }
cout<<"ok...."<<endl; cout << "Output tensor size:" << outputs.size() <<
std::endl; cout << outputs[0].DebugString()<<endl; Tensor t = outputs[0]; int
output_dim = t.shape().dim_size(0); cout<<output_dim<<endl; auto tmap =
t.tensor<float, 1>(); for(int i=0;i<output_dim;++i){ cout<<i<<"-->"<<tmap(i)<<"
"; } cout<<endl; return 0; }
结果:

ok....
Output tensor size:1
Tensor<type: float shape: [20] values: 0.0127011631 0.0497760847
0.00124033471...>
20
0-->0.0127012 1-->0.0497761 2-->0.00124033 3-->0.0369612 4-->0.0458243
5-->0.0124642 6-->0.00162883 7-->0.00522397 8-->0.0574596 9-->0.130111
10-->0.0435387 11-->0.015093 12-->0.00260962 13-->0.024438 14-->0.00970128
15-->0.0859285 16-->0.168278 17-->0.0681312 18-->0.0497715 19-->0.17912 
 

友情链接
ioDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信