#CMakeLists.txt

cmake_minimum_required (VERSION 2.8.)
project (tf_example) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -std=c++11 -W") #link_directories(./lib) include_directories(
/home/u/tf1./tensorflow-GPU
/home/u/tf1./tensorflow-GPU/bazel-genfiles
/home/u/tf1./tensorflow-GPU/bazel-bin/tensorflow
/home/u/tf1./tensorflow-GPU/tensorflow/contrib/makefile/downloads/nsync/public
/home/u/tf1./tensorflow-GPU/tensorflow/contrib/makefile/gen/protobuf/include
/usr/local/include/eigen3
/home/u/tf1./tensorflow-GPU/tensorflow/contrib/makefile/downloads/absl
) add_executable(tf_test tf.cpp) #link_directories(./lib)
#target_link_libraries(tf_test tensorflow_cc tensorflow_framework) target_link_libraries(tf_test /home/u/tf1./tensorflow-GPU/bazel-bin/tensorflow/libtensorflow_cc.so. /home/u/tf1./tensorflow-GPU/bazel-bin/tensorflow/libtensorflow_framework.so.)
//tf.cpp

/*
* test tensorflow_cc c++ successfully
* load mnist.pb model successfully
* conference:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/label_image
* */ //@wp conference:https://blog.csdn.net/wd1603926823/article/details/92843830
#include <fstream>
#include <utility>
#include <vector>
#include <Eigen/Core>
#include <Eigen/Dense> #include "tensorflow/cc/ops/const_op.h"
#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/lib/core/errors.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h" using namespace std;
using namespace tensorflow;
using namespace tensorflow::ops;
using tensorflow::Flag;
using tensorflow::Tensor;
using tensorflow::Status;
using tensorflow::string;
using tensorflow::int32; static Status ReadEntireFile(tensorflow::Env* env, const string& filename,
Tensor* output) {
tensorflow::uint64 file_size = ;
TF_RETURN_IF_ERROR(env->GetFileSize(filename, &file_size)); string contents;
contents.resize(file_size); std::unique_ptr<tensorflow::RandomAccessFile> file;
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(filename, &file)); tensorflow::StringPiece data;
TF_RETURN_IF_ERROR(file->Read(, file_size, &data, &(contents)[]));
if (data.size() != file_size) {
return tensorflow::errors::DataLoss("Truncated read of '", filename,
"' expected ", file_size, " got ",
data.size());
}
// output->scalar<string>()() = data.ToString();
output->scalar<string>()() = string(data);
return Status::OK();
} Status ReadTensorFromImageFile(const string& file_name, const int input_height,
const int input_width, const float input_mean,
const float input_std,
std::vector<Tensor>* out_tensors) {
auto root = tensorflow::Scope::NewRootScope();
using namespace ::tensorflow::ops; string input_name = "file_reader";
string output_name = "normalized"; // read file_name into a tensor named input
Tensor input(tensorflow::DT_STRING, tensorflow::TensorShape());
TF_RETURN_IF_ERROR(
ReadEntireFile(tensorflow::Env::Default(), file_name, &input)); // use a placeholder to read input data
auto file_reader =
Placeholder(root.WithOpName("input"), tensorflow::DataType::DT_STRING); std::vector<std::pair<string, tensorflow::Tensor>> inputs = {
{"input", input},
}; // Now try to figure out what kind of file it is and decode it.
const int wanted_channels = ;
// tensorflow::Output image_reader;
// if (tensorflow::StringPiece(file_name).ends_with(".png")) {
// image_reader = DecodePng(root.WithOpName("png_reader"), file_reader,
// DecodePng::Channels(wanted_channels));
// } else if (tensorflow::StringPiece(file_name).ends_with(".gif")) {
// // gif decoder returns 4-D tensor, remove the first dim
// image_reader =
// Squeeze(root.WithOpName("squeeze_first_dim"),
// DecodeGif(root.WithOpName("gif_reader"), file_reader));
// } else if (tensorflow::StringPiece(file_name).ends_with(".bmp")) {
// image_reader = DecodeBmp(root.WithOpName("bmp_reader"), file_reader);
// } else {
// // Assume if it's neither a PNG nor a GIF then it must be a JPEG.
// image_reader = DecodeJpeg(root.WithOpName("jpeg_reader"), file_reader,
// DecodeJpeg::Channels(wanted_channels));
// }
tensorflow::Output image_reader;
if (tensorflow::str_util::EndsWith(file_name, ".png")) {
image_reader = DecodePng(root.WithOpName("png_reader"), file_reader,
DecodePng::Channels(wanted_channels));
} else if (tensorflow::str_util::EndsWith(file_name, ".gif")) {
// gif decoder returns 4-D tensor, remove the first dim
image_reader =
Squeeze(root.WithOpName("squeeze_first_dim"),
DecodeGif(root.WithOpName("gif_reader"), file_reader));
} else if (tensorflow::str_util::EndsWith(file_name, ".bmp")) {
image_reader = DecodeBmp(root.WithOpName("bmp_reader"), file_reader);
} else {
// Assume if it's neither a PNG nor a GIF then it must be a JPEG.
image_reader = DecodeJpeg(root.WithOpName("jpeg_reader"), file_reader,
DecodeJpeg::Channels(wanted_channels));
}
// Now cast the image data to float so we can do normal math on it.
auto float_caster =
Cast(root.WithOpName("float_caster"), image_reader, tensorflow::DT_FLOAT); auto dims_expander = ExpandDims(root.WithOpName("expand"), float_caster, ); float input_max = ;
Div(root.WithOpName("div"),dims_expander,input_max); tensorflow::GraphDef graph;
TF_RETURN_IF_ERROR(root.ToGraphDef(&graph)); std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions()));
TF_RETURN_IF_ERROR(session->Create(graph));
// std::vector<Tensor> out_tensors;
// TF_RETURN_IF_ERROR(session->Run({}, {output_name + ":0", output_name + ":1"},
// {}, &out_tensors));
TF_RETURN_IF_ERROR(session->Run({inputs}, {"div"}, {}, out_tensors));
return Status::OK();
} int main()
{
Session* session;
Status status = NewSession(SessionOptions(), &session);//创建新会话Session string model_path="model.pb";
GraphDef graphdef; //Graph Definition for current model Status status_load = ReadBinaryProto(Env::Default(), model_path, &graphdef); //从pb文件中读取图模型;
if (!status_load.ok()) {
std::cout << "ERROR: Loading model failed..." << model_path << std::endl;
std::cout << status_load.ToString() << "\n";
return -;
}
Status status_create = session->Create(graphdef); //将模型导入会话Session中;
if (!status_create.ok()) {
std::cout << "ERROR: Creating graph in session failed..." << status_create.ToString() << std::endl;
return -;
}
cout << "Session successfully created."<< endl;
string image_path= "/home/u/tf1.13/tensorflow-c-mnist/digit.jpg";
int input_height =;
int input_width=;
int input_mean=;
int input_std=;
std::vector<Tensor> resized_tensors;
Status read_tensor_status =
ReadTensorFromImageFile(image_path, input_height, input_width, input_mean,
input_std, &resized_tensors);
if (!read_tensor_status.ok()) {
LOG(ERROR) << read_tensor_status;
cout<<"resing error"<<endl;
return -;
} const Tensor& resized_tensor = resized_tensors[];
std::cout << resized_tensor.DebugString()<<endl; vector<tensorflow::Tensor> outputs;
string output_node = "softmax";
Status status_run = session->Run({{"inputs", resized_tensor}}, {output_node}, {}, &outputs); if (!status_run.ok()) {
std::cout << "ERROR: RUN failed..." << std::endl;
std::cout << status_run.ToString() << "\n";
return -;
}
//Fetch output value
std::cout << "Output tensor size:" << outputs.size() << std::endl;
for (std::size_t i = ; i < outputs.size(); i++) {
std::cout << outputs[i].DebugString()<<endl;
} Tensor t = outputs[]; // Fetch the first tensor
int ndim2 = t.shape().dims(); // Get the dimension of the tensor
auto tmap = t.tensor<float, >(); // Tensor Shape: [batch_size, target_class_num]
int output_dim = t.shape().dim_size(); // Get the target_class_num from 1st dimension
std::vector<double> tout; // Argmax: Get Final Prediction Label and Probability
int output_class_id = -;
double output_prob = 0.0;
for (int j = ; j < output_dim; j++)
{
std::cout << "Class " << j << " prob:" << tmap(, j) << "," << std::endl;
if (tmap(, j) >= output_prob) {
output_class_id = j;
output_prob = tmap(, j);
}
} std::cout << "Final class id: " << output_class_id << std::endl;
std::cout << "Final class prob: " << output_prob << std::endl; return ;
}
u@u160406:~/tf1./tensorflow-c-mnist/build$ cmake ..
-- The C compiler identification is GNU 5.4.
-- The CXX compiler identification is GNU 5.4.
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/u/tf1./tensorflow-c-mnist/build u@u160406:~/tf1./tensorflow-c-mnist/build$ make
Scanning dependencies of target tf_test
[ %] Building CXX object CMakeFiles/tf_test.dir/tf.cpp.o
[%] Linking CXX executable tf_test
[%] Built target tf_test u@u160406:~/tf1./tensorflow-c-mnist/build$ ./tf_test
-- ::40.577836: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcuda.so.
-- ::40.599739: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::40.600269: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] Found device with properties:
name: GeForce RTX Ti major: minor: memoryClockRate(GHz): 1.65
pciBusID: ::00.0
-- ::40.600401: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcudart.so.10.0
-- ::40.601114: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcublas.so.10.0
-- ::40.601796: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcufft.so.10.0
-- ::40.601986: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcurand.so.10.0
-- ::40.603086: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcusolver.so.10.0
-- ::40.603734: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcusparse.so.10.0
-- ::40.605733: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcudnn.so.
-- ::40.605793: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::40.606283: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::40.606722: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] Adding visible gpu devices:
-- ::40.606738: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcudart.so.10.0
-- ::40.697274: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] Device interconnect StreamExecutor with strength edge matrix:
-- ::40.697295: I tensorflow/core/common_runtime/gpu/gpu_device.cc:]
-- ::40.697302: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] : N
-- ::40.697444: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::40.697830: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::40.698271: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::40.698632: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] Created TensorFlow device (/job:localhost/replica:/task:/device:GPU: with MB memory) -> physical GPU (device: , name: GeForce RTX Ti, pci bus id: ::00.0, compute capability: 7.5)
Session successfully created.
-- ::41.417655: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::41.419321: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] Found device with properties:
name: GeForce RTX Ti major: minor: memoryClockRate(GHz): 1.65
pciBusID: ::00.0
-- ::41.419390: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcudart.so.10.0
-- ::41.419423: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcublas.so.10.0
-- ::41.419448: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcufft.so.10.0
-- ::41.419471: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcurand.so.10.0
-- ::41.419497: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcusolver.so.10.0
-- ::41.419523: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcusparse.so.10.0
-- ::41.419549: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcudnn.so.
-- ::41.419667: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::41.421127: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::41.422501: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] Adding visible gpu devices:
-- ::41.422566: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] Device interconnect StreamExecutor with strength edge matrix:
-- ::41.422592: I tensorflow/core/common_runtime/gpu/gpu_device.cc:]
-- ::41.422613: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] : N
-- ::41.423170: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::41.424636: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:] successful NUMA node read from SysFS had negative value (-), but there must be at least one NUMA node, so returning NUMA node zero
-- ::41.426045: I tensorflow/core/common_runtime/gpu/gpu_device.cc:] Created TensorFlow device (/job:localhost/replica:/task:/device:GPU: with MB memory) -> physical GPU (device: , name: GeForce RTX Ti, pci bus id: ::00.0, compute capability: 7.5)
Tensor<type: float shape: [,,,] values: [[[0.992156923][0.0823529437][]]]...>
-- ::44.755529: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcublas.so.10.0
-- ::45.821366: I tensorflow/stream_executor/platform/default/dso_loader.cc:] Successfully opened dynamic library libcudnn.so.
Output tensor size:
Tensor<type: float shape: [,] values: [0.000222602132 0.951202273 0.00674963091...]...>
Class prob:0.000222602,
Class prob:0.951202,
Class prob:0.00674963,
Class prob:0.00721128,
Class prob:0.0029518,
Class prob:0.0100965,
Class prob:0.0119467,
Class prob:0.00218653,
Class prob:0.00189467,
Class prob:0.00553806,
Final class id:
Final class prob: 0.951202 u@u160406:~/tf1./tensorflow-c-mnist/build$

@https://github.com/zhangcliff/tensorflow-c-mnist 会报错:

参照@https://blog.csdn.net/wd1603926823/article/details/92843830解决问题。

”“”“找了很久原因没解决。因为我去看string_view的源码,真的没有报错的这几个成员函数。所以可能是我用错了版本还是这几个函数已经被废弃。

今天终于解决了。原来上面这个例程是按照 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/label_image/main.cc  仿照这个来写的,而外国人进行了更新,国内很多人以前的博客都是老版本,所以我使用会出问题。 ”“”“

开源框架---tensorflow c++ API 运行第一个“手写字的例子”的更多相关文章

  1. 开源框架---tensorflow c++ API 一个卡了很久的问题

    <开源框架---tensorflow c++ API 运行第一个“手写字的例子”> 中可以说明tensorflow c++ API是好用的,.......

  2. 开源框架---tensorflow c++ API中./configure步骤细节

    u@u160406:~/tf1.13/tensorflow$ git checkout r1.13 分支 r1.13 设置为跟踪来自 origin 的远程分支 r1.13.切换到一个新分支 'r1.1 ...

  3. 【实践】如何利用tensorflow的object_detection api开源框架训练基于自己数据集的模型(Windows10系统)

    如何利用tensorflow的object_detection api开源框架训练基于自己数据集的模型(Windows10系统) 一.环境配置 1. Python3.7.x(注:我用的是3.7.3.安 ...

  4. 开源框架---通过Bazel编译使用tensorflow c++ API 记录

    开源框架---通过Bazel编译使用tensorflow c++ API 记录 tensorflow python API,在python中借用pip安装tensorflow,真的很方便,几句指令就完 ...

  5. 谷歌开源的TensorFlow Object Detection API视频物体识别系统实现教程

    视频中的物体识别 摘要 物体识别(Object Recognition)在计算机视觉领域里指的是在一张图像或一组视频序列中找到给定的物体.本文主要是利用谷歌开源TensorFlow Object De ...

  6. 对于谷歌开源的TensorFlow Object Detection API视频物体识别系统实现教程

    本教程针对Windows10实现谷歌近期公布的TensorFlow Object Detection API视频物体识别系统,其他平台也可借鉴. 本教程将网络上相关资料筛选整合(文末附上参考资料链接) ...

  7. Android开源框架Afinal第一篇——揭开圣女的面纱

    Android开源框架Afinal第一篇——揭开圣女的面纱 分类: Android开源框架哪点事2013-09-02 14:25 260人阅读 评论(0) 收藏 举报 Afinal 这是Afinal在 ...

  8. Pyhton开源框架(加强版)

    info:Djangourl:https://www.oschina.net/p/djangodetail: Django 是 Python 编程语言驱动的一个开源模型-视图-控制器(MVC)风格的 ...

  9. Python开源框架

    info:更多Django信息url:https://www.oschina.net/p/djangodetail: Django 是 Python 编程语言驱动的一个开源模型-视图-控制器(MVC) ...

随机推荐

  1. iOS-Xib获取view尺寸的问题

    用xib创建的视图,我们一般要在控制器中获取对应的view尺寸,但经常我们没法获取到,或者获取的不准 如果通过xib加载出来的view尺寸是不正确的, 在xib中这个view不管你怎么设置都是治标不治 ...

  2. 按键板的原理与实现----ADC

    在嵌入式系统产品开发中,按键板的设计是最基本的,也是项目评估阶段必须要考虑的问题.其实现方式又很多种,具体使用那一种就需要结合特定IC的可用IO数量,并综合考虑成本,做出最终选择.本系列文章将介绍多种 ...

  3. qbittorrent搜索在线插件

    https://raw.githubusercontent.com/khensolomon/leyts/master/yts.py https://raw.githubusercontent.com/ ...

  4. Python数据挖掘之随机森林

    主要是使用随机森林将four列缺失的数据补齐. # fit到RandomForestRegressor之中,n_estimators代表随机森林中的决策树数量 #n_jobs这个参数告诉引擎有多少处理 ...

  5. 【转】那些年用过的Redis集群架构(含面试解析)

    引言 今天是2019年2月12号,也就是大年初八,我接到了高中同学刘有码面试失利的消息. 他面试的时候,身份是某知名公司的小码农一枚,却因为不懂自己生产上Redis是如何部署的,导致面试失败! 人间惨 ...

  6. [WebAPI] - 使用 Ajax 提交 HTML Form Data 到 WebAPI 的方法

    背景 根据HTTP标准,HTTP请求可以使用多种请求方法. HTTP 1.0 定义了三种请求方法:GET.POST 和 HEAD 方法.HTTP 1.1 新增了五种请求方法:OPTIONS.PUT.D ...

  7. Bean配置

    1.xml配置(摘抄自:https://www.cnblogs.com/zyx1301691180/p/7665971.html) 一.setter方法配置Bean: 1.创建一个 Spring Be ...

  8. 转:数据库实例自动crash并报ORA-27157、ORA-27300等错误

    rhel7.2上安装12C RAC数据库后,其中一个数据库实例经常会自动crash.查看alert日志发现以下错误信息: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Errors ...

  9. Model 的使用

    1.   设计数据结构 问题表Question:作用存放问题 id 主键 自增 question_text 题目 varchar120 created 创建时间 datetime 选项表Choice: ...

  10. 机器学习-EM算法-GMM模型笔记

    GMM即高斯混合模型,下面根据EM模型从理论公式推导GMM: 随机变量X是有K个高斯分布混合而成,取各个高斯分布的概率为φ1,φ2,... ,φK,第i个高斯分布的均值为μi,方差为Σi.若观测到随机 ...