Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

  1. 将Keras训练的.hdf5模型固化为.pb模型

    from tensorflow.python.framework import graph_io
    from keras.models import load_model
    from keras import backend as K
    import tensorflow as tf


    def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
        from tensorflow.python.framework.graph_util import convert_variables_to_constants
        graph = session.graph
        with graph.as_default():
            freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
            output_names = output_names or []
            output_names += [v.op.name for v in tf.global_variables()]
            input_graph_def = graph.as_graph_def()
            if clear_devices:
                for node in input_graph_def.node:
                    node.device = ""
            frozen_graph = convert_variables_to_constants(session, input_graph_def,
                                                          output_names, freeze_var_names)
            return frozen_graph


    """----------------------------------配置路径-----------------------------------"""
    output_path = "D:/sift"
    pb_model_name = "resunet_membrane2.pb"

    """----------------------------------导入keras模型------------------------------"""
    K.set_learning_phase(0)
    net_model = load_model('D:/sift/resunet_membrane120.hdf500-4')

    print('input is :', net_model.input.name)
    print('output is:', net_model.output.name)

    """----------------------------------保存为.pb格式------------------------------"""
    sess = K.get_session()
    frozen_graph = freeze_session(K.get_session(), output_names=[net_model.output.op.name])
    graph_io.write_graph(frozen_graph, output_path, "resunet_membrane2.pb", as_text=False)

  2. 测试.pb模型在tensorflow下的效果

from keras.models import load_model
import matplotlib.pyplot as plt
import numpy as np
import cv2

# data
img_path = "./0.png"
img = cv2.imread(img_path, 0)

# model
keras_model_path = "./resunet_membrane120.hdf500-4"
ResUNnet = load_model(keras_model_path)

# prepare_and_predict
img = img / 255
img = cv2.resize(img, (512, 512))
X = np.reshape(img, (1, 512, 512, 1))
y = ResUNnet.predict(X)
out = np.reshape(y, (512, 512)) * 255
out = np.array(out, dtype="u1")
print("img.shape: %s, out.shape: %s" % (img.shape, out.shape))

# show
plt.subplot(1, 2, 1); plt.imshow(img, cmap="gray")
plt.subplot(1, 2, 2); plt.imshow(out, cmap="gray")
plt.suptitle("keras-hdf5"); plt.show()


"""------------------------tensorflow-pb------------------------"""
import tensorflow as tf

# model

tf_model_path = "./new_tensor_model.pb"

# graph_and_predict
with tf.Graph().as_default():
    output_graph_def = tf.GraphDef()

    # open the *.pb model
    with open(tf_model_path, "rb") as fr:
        output_graph_def.ParseFromString(fr.read())
        tf.import_graph_def(output_graph_def, name="")

    # run the forward in the session
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())  # init
        inp_tensor = sess.graph.get_tensor_by_name("input_1:0")#这是对应模型输入张量的名字,每个人的定义不一样,如果你不知道,可以去网上找代码输出所有结点的名字,一般第一个就是
        out_tensor = sess.graph.get_tensor_by_name("conv2d_30/Sigmoid:0")#这是输出张量的名字,一般是输出的所有结点的最后一个名字
        npy_tensor = sess.run(out_tensor, feed_dict={inp_tensor: X})  # X in line 18.
        # postprocessing
        npy = np.reshape(npy_tensor, (512, 512)) * 255
        npy = np.array(npy, dtype="u1")

# show
plt.subplot(1, 3, 1); plt.imshow(img, cmap="gray"), plt.title("IMG")
plt.subplot(1, 3, 2); plt.imshow(out, cmap="gray"), plt.title("keras")
plt.subplot(1, 3, 3); plt.imshow(npy, cmap="gray"), plt.title("TF")
plt.show()

搭建VS的tensorflow平台

CMake 3.14.1

Swigwin3.0.12

VS2015

 

  1. 用git下载tensorflow的源码

git clone -b v1.82 https://github.com/tensorflow/tensorflow.git

  1. 用CMake编译源码

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

之后会报一个 swig 的错误,搜索:SWIG_EXECUTABLEValue 设置成自己的 swig.exe 的目录。

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

 

3.用VS生成tensorflow工程

用 vs 打开 E:\ResUNetTools\build 中的 tensorflow.sln,分别将前面这几个以下划线开头的项目的属性修改一下,方法:右击项目→属性→配置属性→链接器→常规→附加库目录,添加$(SolutionDir)$(Configuration); 

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

 

然后点击生成解决方案,就会在build文件夹下生成release文件夹,其中有tensorflow.lib和tensorflow.dll文件就是我们需要的生成库

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

 

4给VS配置tensorflow生成库

将转化好的.pb模型文件,tensorflow.lib和tensorflow.dll文件放在工程的源代码路径下

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

 

为项目配置属性文件

 

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用

打开预处理器选项,添加一条PLATFORM_WINDOWS记录

 

Keras Tensorflow下训练出来的模型在Visual Studio C++环境中的应用