Tensorflow的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编译源码

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

 

3.用VS生成tensorflow工程

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

 

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

 

4给VS配置tensorflow生成库

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

 

为项目配置属性文件

 

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

 

在C中调用TensorFlow可以通过TensorFlow的C API来实现。TensorFlow的C API提供了一组函数,允许我们在C语言环境中使用TensorFlow的功能。 首先,我们需要在C程序中引入TensorFlow的头文件,例如:`#include <tensorflow/c/c_api.h>`,然后通过连接TensorFlow库,使用相关函数来操作TensorFlow。 接下来,我们需要创建一个TensorFlow会话(tf.Session),用于执行TensorFlow图(tf.Graph)。可以通过以下几个步骤来完成: 1. 创建一个图:`TF_Graph* graph = TF_NewGraph();` 2. 创建一个会话:`TF_Session* session = TF_NewSession(graph, nullptr);` 3. 创建输入Tensor:`TF_Tensor* input_tensor = create_input_tensor();`,这里的create_input_tensor()函数根据具体需求创建输入Tensor。 4. 创建TensorFlow的输入节点(tf.Operation)和输出节点(tf.Operation)。 5. 将输入Tensor绑定到输入节点:`TF_SessionRun(session, nullptr, inputs, input_values, num_inputs, ...);` 6. 运行会话:`TF_SessionRun(session, nullptr, input_ops, input_values, num_inputs, output_ops, output_values, num_outputs, ...);` 7. 获取输出Tensor的结果:`const float* output_data = (const float*)TF_TensorData(output_tensor);` 通过以上步骤,我们可以在C代码中使用TensorFlow来执行图,并获取输出结果。 需要注意的是,在C中调用TensorFlow需要注意内存管理,例如,需要手动释放创建的图、会话、Tensor等资源,以避免内存泄漏。同时,还需要根据具体需求来适配输入数据和输出结果的类型、形状等。 总结起来,通过TensorFlow的C API,我们可以在C语言环境中使用TensorFlow的功能,实现各种机器学习和深度学习的任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值