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()

这样就完成了调用

上一篇:TensorBoard最全使用说明!!!


下一篇:Anaconda3下使用清华镜像源安装TensorFlow(CPU版)