c++ opencv 调用python tensorflow
2021/9/18 14:04:48
本文主要是介绍c++ opencv 调用python tensorflow,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.vs2019配置opencv3.4.X版本(我是3.4.15),此处配置过程略
2.上C++代码
#include <opencv2/dnn.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <Windows.h> #include <fstream> #include <iostream> #include "highgui.h" using namespace cv; using namespace cv::dnn; using namespace std; int main(int argc, char** argv) { String tf_pb_file = "D:\\Files\\Pycharm_files\\NEWCNN\\frozen_models\\MODEL.pb"; Net net = readNetFromTensorflow(tf_pb_file); float inputdata[1][8] = { {0.089277327 ,0.107121679 ,0.097890143, 1.339686044, 1.150469794, 3.420068931 ,3.934685998, 4.338265198} }; Mat data(1, 8, CV_32FC1, inputdata); //将输入模型中得到结果放在tmp中,tmp的尺寸等于你的输出层 net.setInput(data); Mat tmp = net.forward(); cout << "tmp" << tmp << endl; float result = tmp.at<float>(0, 1); cout << result << endl; return 0; }
此处只需要更换一个tf_pb_file 的pb文件,和一个inputdata[1][8]输入数据就行了。
那pb文件怎么的来呢?
我这里采用python tensorflow先训练完成保存MODEL.h5文件,后将MODEL.h5文件冻结成pb文件,下面是冻结代码
import tensorflow as tf from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 def convert_h5to_pb(): model = tf.keras.models.load_model("./MODEL.h5", compile=False) model.summary() full_model = tf.function(lambda Input: model(Input)) full_model = full_model.get_concrete_function(tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype)) # Get frozen ConcreteFunction frozen_func = convert_variables_to_constants_v2(full_model) frozen_func.graph.as_graph_def() layers = [op.name for op in frozen_func.graph.get_operations()] print("-" * 50) print("Frozen model layers: ") for layer in layers: print(layer) print("-" * 50) print("Frozen model inputs: ") print(frozen_func.inputs) print("Frozen model outputs: ") print(frozen_func.outputs) # Save frozen graph from frozen ConcreteFunction to hard drive tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir="./frozen_models", name="MODEL.pb", as_text=False) convert_h5to_pb()
这样就完成了调用
这篇关于c++ opencv 调用python tensorflow的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-30tensorflow是什么-icode9专业技术文章分享
- 2024-10-15成功地使用本地的 NVIDIA GPU 运行 PyTorch 或 TensorFlow
- 2024-01-23供应链投毒预警 | 恶意Py包仿冒tensorflow AI框架实施后门投毒攻击
- 2024-01-19attributeerror: module 'tensorflow' has no attribute 'placeholder'
- 2024-01-19module 'tensorflow.compat.v2' has no attribute 'internal'
- 2023-07-17【2023年】第33天 Neural Networks and Deep Learning with TensorFlow
- 2023-07-10【2023年】第32天 Boosted Trees with TensorFlow 2.0(随机森林)
- 2023-07-09【2023年】第31天 Logistic Regression with TensorFlow 2.0(用TensorFlow进行逻辑回归)
- 2023-07-01【2023年】第30天 Supervised Learning with TensorFlow 2(用TensorFlow进行监督学习 2)
- 2023-06-18【2023年】第29天 Supervised Learning with TensorFlow 1(用TensorFlow进行监督学习 1)