c++使用opencv讀取影象進tensorflow做預測
阿新 • • 發佈:2018-12-12
接上一篇文章,上一篇文章簡單了訓練一個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