前面我們介紹了將tensorflow的ckpt模型檔案轉換為pb檔案,接下來,我們使用tensorflow的c++介面呼叫pb檔案做前向推理。
這裡假設已經編譯好了tensorflow的動態庫載入模型的過程和python介面時一致,先建立乙個session會話,定義乙個graph,讀取pb檔案後使用session為定義的graph分配資源。
前向推理時,需要指定起止結點,根據指定的起止結點去執行要執行哪部分graph,還要給起止結點的tensor,為輸入影象和輸出結果開闢記憶體,以上篇轉換pb時定義的tensor name為例。using tensorflow::flag;
using tensorflow::tensor;
using tensorflow::status;
using tensorflow::string;
using tensorflow::int32;
using tensorflow::uint8;
using namespace tensorflow;
using namespace std;
using namespace cv;
status load_graph(const string& graph_file_name, std::unique_ptr* session)
session->reset(tensorflow::newsession(tensorflow::sessionoptions()));
status session_create_status = (*session)->create(graph_def);
if (!session_create_status.ok())
return status::ok();
}
將載入模型和前向推理封裝,偽**如下:int predict(std::unique_ptr&session, string image_path) ;
auto ori_img = cv::imread(image_path);
cv::mat img;
cv::resize(ori_img, img, cv::size(input_width,input_height));
int width = img.size().width;
int height = img.size().height;
uchar* data = img.data;
tensor data_tensor(tensorflow::dt_float, tensorflow::tensorshape());
for (int y = 0; y < height * width * 3; y += 3)
std::vectoroutputs;
outputs.clear();
status run_status = session->run(}, output_layer, {}, &outputs);
if (!run_status.ok())
return 0;
}
這樣,就可以使用c++**進行tensorflow的前向推理了。int inference(string graph_path, string img_path)
predict(session, img_path);
return 0;
}
如何在TF2中使用TF1 x的 pb模型
在tf1.x中,使用凍結的.pb模型方法比較簡單,可以參看 隨著tf2的推進,以後,用tf2的也會越來越多。但是,有時候還是會需要在tf2中使用到tf1.x的模型。對於.pb模型的使用,該如何做呢?直接上code def wrap frozen graph graph def,inputs,outp...
TF庫的使用
1 tf不是座標變換那麼簡單。很多小夥伴認為tf的作用是便捷的進行座標變換。這個沒錯,但沒這麼簡單。在很多api中,存在著 target frame,source frame,parent frame,child frame 這些名字的引數。看起來很讓人糊塗,也很讓讓人煩,但裡面隱藏著很多資訊。so...
使用tf 時gpu的設定
使用gpu跑tensorflow程式,預設載入所有的gpu,但計算過程中只會用其中一塊。也就是你看著所有gpu都被占用了,以為是在gpu平行計算,但實際上只有其中一塊在執行 另外的所有顯示卡都閒著,但其視訊記憶體都被占用了,所以別人也用不了。不過這種情況通過在程式之前加三行 就可以解決 import...