2017-01-17 34 views
2

我無法找到任何有關如何在C++中使用tensorflow.soc_api.h加載圖的示例。我讀了c_api.h,但ReadBinaryProto函數不在其中。如何在沒有ReadBinaryProto函數的情況下加載圖表?如何在C++語言中加載tensorflow.so和c_api.h的圖形?

+0

爲什麼你想在C++中使用C API而不是本地C++ [庫](https://www.tensorflow.org/api_docs/cc/namespace/tensorflow#readbinaryproto)? –

+0

實際上,我想用tensorflow的C++ api來加載tensorflow項目之外的圖表 –

回答

6

如果您使用C++,則可能需要改用C++ API。 label image example可能是幫助您開始的一個很好的示例。

如果您確實想使用C API,請使用TF_GraphImportGraphDef加載圖形。需要注意的是C API不是特別方便使用(它旨在建立綁定在其他語言,如圍棋,爪哇,防鏽,哈斯克爾等),例如:

#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; 
} 
+1

謝謝你的回答。我想在tensorflow項目之外使用C++ API。 tensorflow項目中建立「標籤圖像示例」。我如何在張量流之外使用C++ API?我應該包括什麼頭文件? –

0

以前的答案是你的主要選項,如果你想在TensorFlow項目之外使用它(因此不能用Bazel構建)。你需要需要從c_api.h和TF_GraphImportDef加載它,我建議你在Python中訓練和測試,然後在完成時導出模型/圖形用於C++/C Api。

相關問題