如何在 C++ 语言中使用 tensorflow.so 和 c_api.h 加载图形? [英] How to load a graph with tensorflow.so and c_api.h in c++ language?
问题描述
我找不到任何关于如何在 C++ 中使用 tensorflow.so
和 c_api.h
加载图形的示例.我阅读了 c_api.h
,但是 ReadBinaryProto
函数不在其中.如何在没有 ReadBinaryProto
函数的情况下加载图形?
I am not able to find any examples about how to load a graph with tensorflow.so
and c_api.h
in C++. I read the c_api.h
, however the ReadBinaryProto
function was not in it. How can I load a graph without the ReadBinaryProto
function?
推荐答案
如果您使用的是 C++,您可能希望改用 C++ API.标签图像示例 可能是一个很好的示例来帮助您开始.
If you're using C++, you might want to use the C++ API instead. The label image example would probably be a good sample to help you start.
如果您真的只想使用 C API,请使用 TF_GraphImportGraphDef
加载图形.请注意,C API 使用起来不是特别方便(它旨在构建其他语言的绑定,例如 Go、Java、Rust、Haskell 等)例如:
If you really want to use just the C API, use TF_GraphImportGraphDef
to load a graph. Note that the C API isn't particularly convenient to use (it is intended to build bindings in other languages such as Go, Java, Rust, Haskell etc.) For example:
#include <stdio.h>
#include <stdlib.h>
#include <tensorflow/c/c_api.h>
TF_Buffer* read_file(const char* file);
void free_buffer(void* data, size_t length) {
free(data);
}
int main() {
// Graph definition from unzipped https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
// which is used in the Go, Java and Android examples
TF_Buffer* graph_def = read_file("tensorflow_inception_graph.pb");
TF_Graph* graph = TF_NewGraph();
// Import graph_def into graph
TF_Status* status = TF_NewStatus();
TF_ImportGraphDefOptions* opts = TF_NewImportGraphDefOptions();
TF_GraphImportGraphDef(graph, graph_def, opts, status);
TF_DeleteImportGraphDefOptions(opts);
if (TF_GetCode(status) != TF_OK) {
fprintf(stderr, "ERROR: Unable to import graph %s", TF_Message(status));
return 1;
}
fprintf(stdout, "Successfully imported graph");
TF_DeleteStatus(status);
TF_DeleteBuffer(graph_def);
// Use the graph
TF_DeleteGraph(graph);
return 0;
}
TF_Buffer* read_file(const char* file) {
FILE *f = fopen(file, "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); //same as rewind(f);
void* data = malloc(fsize);
fread(data, fsize, 1, f);
fclose(f);
TF_Buffer* buf = TF_NewBuffer();
buf->data = data;
buf->length = fsize;
buf->data_deallocator = free_buffer;
return buf;
}
这篇关于如何在 C++ 语言中使用 tensorflow.so 和 c_api.h 加载图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!