tensorflow c++ API加载.pb模型文件并预测图片
tensorflow python创建模型,训练模型,得到.pb模型文件后,用c++ api进行预测
#include <iostream>
#include <map> #include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h" using namespace std ;
using namespace tensorflow;
using tensorflow::Tensor;
using tensorflow::Status;
using tensorflow::string;
using tensorflow::int32; //从文件名中读取数据
Status ReadTensorFromImageFile(string file_name, const int input_height,
const int input_width,
vector<Tensor>* out_tensors) {
auto root = Scope::NewRootScope();
using namespace ops; auto file_reader = ops::ReadFile(root.WithOpName("file_reader"),file_name);
const int wanted_channels = ;
Output image_reader;
std::size_t found = file_name.find(".png");
//判断文件格式
if (found!=std::string::npos) {
image_reader = DecodePng(root.WithOpName("png_reader"), file_reader,DecodePng::Channels(wanted_channels));
}
else {
image_reader = DecodeJpeg(root.WithOpName("jpeg_reader"), file_reader,DecodeJpeg::Channels(wanted_channels));
}
// 下面几步是读取图片并处理
auto float_caster =Cast(root.WithOpName("float_caster"), image_reader, DT_FLOAT);
auto dims_expander = ExpandDims(root, float_caster, );
auto resized = ResizeBilinear(root, dims_expander,Const(root.WithOpName("resize"), {input_height, input_width}));
// Div(root.WithOpName(output_name), Sub(root, resized, {input_mean}),{input_std});
Transpose(root.WithOpName("transpose"),resized,{,,,}); GraphDef graph;
root.ToGraphDef(&graph); unique_ptr<Session> session(NewSession(SessionOptions()));
session->Create(graph);
session->Run({}, {"transpose"}, {}, out_tensors);//Run,获取图片数据保存到Tensor中 return Status::OK();
} int main(int argc, char* argv[]) { string graph_path = "aov_crnn.pb";
GraphDef graph_def;
//读取模型文件
if (!ReadBinaryProto(Env::Default(), graph_path, &graph_def).ok()) {
cout << "Read model .pb failed"<<endl;
return -;
} //新建session
unique_ptr<Session> session;
SessionOptions sess_opt;
sess_opt.config.mutable_gpu_options()->set_allow_growth(true);
(&session)->reset(NewSession(sess_opt));
if (!session->Create(graph_def).ok()) {
cout<<"Create graph failed"<<endl;
return -;
} //读取图像到inputs中
int input_height = ;
int input_width = ;
vector<Tensor> inputs;
// string image_path(argv[1]);
string image_path("test.jpg");
if (!ReadTensorFromImageFile(image_path, input_height, input_width,&inputs).ok()) {
cout<<"Read image file failed"<<endl;
return -;
} vector<Tensor> outputs;
string input = "inputs_sq";
string output = "results_sq";//graph中的输入节点和输出节点,需要预先知道 pair<string,Tensor>img(input,inputs[]);
Status status = session->Run({img},{output}, {}, &outputs);//Run,得到运行结果,存到outputs中
if (!status.ok()) {
cout<<"Running model failed"<<endl;
cout<<status.ToString()<<endl;
return -;
} //得到模型运行结果
Tensor t = outputs[];
auto tmap = t.tensor<int64, >();
int output_dim = t.shape().dim_size(); return ;
}
g++ -g tf_predict.cpp -o tf_predict -I /usr/include/eigen3 -I /usr/local/include/tf -L/usr/local/lib/ `pkg-config --cflags --libs protobuf` -ltensorflow_cc -ltensorflow_framework
也可以用opencv c++库读取图片Mat复制到Tensor中
tensorflow::Tensor readTensor(string filename){
tensorflow::Tensor input_tensor(DT_FLOAT,TensorShape({,,,}));
Mat src=imread(filename,);
Mat dst;
resize(src,dst,Size(,));//resize
Mat dst_transpose=dst.t();//transpose auto tmap=input_tensor.tensor<float,>(); for(int i=;i<;i++){//Mat复制到Tensor
for(int j=;j<;j++){
tmap(,i,j,)=dst_transpose.at<uchar>(i,j);
}
} return input_tensor;
}
也可用指针引用的方式转换
tensorflow::Tensor input_tensor(DT_FLOAT,TensorShape({,height,width,}));
float *tensor_data_ptr = input_tensor.flat<float>().data();
cv::Mat fake_mat(dst.rows, dst.cols, CV_32FC(src.channels()), tensor_data_ptr);
dst.convertTo(fake_mat, CV_32FC3);
tensorflow c++ API加载.pb模型文件并预测图片的更多相关文章
- xBIM 实战01 在浏览器中加载IFC模型文件
系列目录 [已更新最新开发文章,点击查看详细] 一.创建Web项目 打开VS,新建Web项目,选择 .NET Framework 4.5 选择一个空的项目 新建完成后,项目结构如下: 二.添 ...
- xBIM 实战02 在浏览器中加载IFC模型文件并设置特效
系列目录 [已更新最新开发文章,点击查看详细] 在模型浏览器中加载模型后,可以对模型做一些特殊操作.下图是常用的设置. 都是通过 xbim-viewer.js 中的 API 来设置以达到一定的 ...
- iOS 加载本地 HTML 文件 CSS 样式图片无效果
在开发的过程中,有时候需要加载一些 HTML 页面,对于不太复杂的界面,基本上都可以放到本地用 UIWebview 来加载,但是在开发过程中会碰到 UIWebview 加载出来的 HTML 页面没有图 ...
- tensorflow数据加载、模型训练及预测
数据集 DNN 依赖于大量的数据.可以收集或生成数据,也可以使用可用的标准数据集.TensorFlow 支持三种主要的读取数据的方法,可以在不同的数据集中使用:本教程中用来训练建立模型的一些数据集介绍 ...
- 机器学习之保存与加载.pickle模型文件
import pickle from sklearn.externals import joblib from sklearn.svm import SVC from sklearn import d ...
- Qt3D使用assimp加载常规模型文件
Qt3D使用assimp加载三维模型文件,assimp支持很多常规格式的三维模型格式: 其中支持导入的格式有: 3D 3DS 3MF AC AC3D ACC AMJ ASE ASK B3D BLEND ...
- 开园第一篇---有关tensorflow加载不同模型的问题
写在前面 今天刚刚开通博客,主要想法跟之前某位博主说的一样,希望通过博客园把每天努力的点滴记录下来,也算一种坚持的动力.我是小白一枚,有啥问题欢迎各位大神指教,鞠躬~~ 换了新工作,目前手头是OCR项 ...
- iOS边练边学--plist文件,懒加载,模型初使用--补充instancetype
一.什么是plist文件 1>将数据直接写在代码里面,不是一种合理的做法.如果数据经常修改,就要经常翻开对应的代码进行修改,造成代码扩展性低 2>因此,可以考虑将经常变得数据放在文件中进行 ...
- 查看tensorflow pb模型文件的节点信息
查看tensorflow pb模型文件的节点信息: import tensorflow as tf with tf.Session() as sess: with open('./quantized_ ...
随机推荐
- WebDriver自动化测试工具(1)---环境搭建
Webdriver是一个前端自动化测试工具,可以模拟用户点击链接,填写表单,点击按钮等操作,下面介绍其使用 一.下载WebdriverC#类库以及对应浏览器驱动 http://www.selenium ...
- 获取或设置config节点值
ExeConfigurationFileMap 这个类提供了修改.获取指定 config 的功能:新建一个 ExeConfigurationFileMap 的实例 ecf :并设置 ExeConfig ...
- Flask实战第59天:首页帖子布局完成
编辑front_index.html <div id="carousel-example-generic" class="carousel slide index- ...
- ALL运算符
ALL在英文中的意思是“所有”,ALL运算符要求比较的值需要匹配子查询中的所有值.ALL运算符同样不能单独使用,必须和比较运算符共同使用. 下面的SQL语句用来检索在所有会员入会之前出版的图书: SE ...
- [BZOJ2159]Crash的文明世界(斯特林数+树形DP)
题意:给定一棵树,求$S(i)=\sum_{j=1}^{n}dist(i,j)^k$.题解:根据斯特林数反演得到:$n^m=\sum_{i=0}^{n}C(n,i)\times i!\times S( ...
- 洛谷 P3943 星空
题目背景 命运偷走如果只留下结果, 时间偷走初衷只留下了苦衷. 你来过,然后你走后,只留下星空. 题目描述 逃不掉的那一天还是来了,小 F 看着夜空发呆. 天上空荡荡的,没有一颗星星——大概是因为天上 ...
- 【拓扑排序】【bitset】Gym - 101128A - Promotions
给你一张DAG,若选择u点,则必须先选择所有能到达其的点.问你在选择A个点的情况下,哪些点必选:选择B个点的情况下,哪些点必选:选择B个点的情况下,哪些点一定不选. 选择A个点的情况,必选的点是那些其 ...
- 【最小生成树】【kruscal】hdu4786 Fibonacci Tree
假设这张图能够形成具有k条白边的生成树, 则易证k一定形成一个连续的区间[a,b],中间一定不会断开.要是断开……tm怎么可能. 所以求出a,b就好啦,人家都给你把白边赋成1了,直接跑一下最小生成树, ...
- [CodeForces-759D]Bacterial Melee
题目大意: 有一串n个字母,每个位置的字母可以同化边上的一个字母, 比如:ab可以变成aa或者bb. 相对的两个同化不能同时发生,比如ab不能变成ba. 现在给你一个字符串,问你经过任意次数的同化过程 ...
- 微软笔试Highway问题解析
High way 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 In the city, there is a one-way straight highway ...