我是靠谱客的博主 缥缈帅哥,这篇文章主要介绍keras单张预测与hdf5模型转化为.pb形式的脚本,现在分享给大家,希望可以做个参考。

单张预测:


# 单张预测
image = Image.open(r'0_predict.png')

test = cv2.resize(np.array(image),(512,512))
test = test.astype('float32')
test=np.expand_dims(test,0)
print(test.shape)

# test = np.reshape(test,(1,480,360))
# rgb = rgb/255.0
predict = model.predict(test)
print(predict.shape)
predict=np.argmax(predict,axis=3)
print(predict)
print(predict.shape)
predict=np.squeeze(predict,0)
print(predict.shape)
cv2.imwrite("predice.png",predict)

# import cv2
# import numpy as np 

# img=cv2.imread("predice.png")
# # img=img.astype(np.uint8)
# cv2.imshow("1",img*10)
# cv2.waitKey(0)

打印一下shape形状

2 修改一些hdf5名字就可以在keras环境下运行

    有几点需要注意的地方,就是有时候keras采用自定义的损失函数,在脚本load_model时候需要加入字典说明。另一点是,甲苯加载的(h5)模型是包含整个网络结构和权重的。keras中采用save_weight方法保存的是权重文件h5,这里脚本会报错。

# -*- coding:utf-8 -*-
#!/usr/bin/python
# coding:utf8
##-------keras模型保存为tensorflow的二进制模型-----------
import sys
from keras.models import load_model,load_weights
import tensorflow as tf
import os
import os.path as osp
from keras import backend as K
from tensorflow.python.framework.graph_util import convert_variables_to_constants
 
import numpy as np
from PIL import Image
import click
import os


from deblurgan.model import generator_model
from deblurgan.utils import load_image, deprocess_image, preprocess_image


# 解决方法 https://blog.csdn.net/fu6543210/article/details/90814575
#         https://blog.csdn.net/u011692048/article/details/77686208
#         https://blog.csdn.net/u011692048/article/details/77686208

# model.save是保存模型和权重
# 将整个模型保存下来,以后直接载入模型与训练数据即可开始训练,
# 不用再定义网络和编译模型.
# (这种方法已经保存了模型的结构和权重,以及损失函数和优化器)

# model.save_weight保存权重  https://www.e-learn.cn/content/wangluowenzhang/759717
# https://blog.csdn.net/leviopku/article/details/86612293

def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
    # 将会话状态冻结为已删除的计算图,创建一个新的计算图,其中变量节点由在会话中获取其当前值的常量替换.
    # session要冻结的TensorFlow会话,keep_var_names不应冻结的变量名列表,或者无冻结图中的所有变量
    # output_names相关图输出的名称,clear_devices从图中删除设备以获得更好的可移植性
    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_fld = sys.path[0] + '/tmp/'
if not os.path.isdir(output_fld):
    os.mkdir(output_fld)
weight_file_path = osp.join(sys.path[0], 'generator.h5')
K.set_learning_phase(0)
net_model = load_weights(weight_file_path)
 
print('input is :', net_model.input.name)
print ('output is:', net_model.output.name)
 
# 获得当前图
sess = K.get_session()
# 冻结图
frozen_graph = freeze_session(sess, output_names=[net_model.output.op.name])
 
from tensorflow.python.framework import graph_io
graph_io.write_graph(frozen_graph, output_fld, 'new_tensor_model.pb', as_text=False)
print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, 'new_tensor_model.pb'))
print (K.get_uid())

参考链接:https://www.e-learn.cn/content/wangluowenzhang/759717

                    https://blog.csdn.net/leviopku/article/details/86612293

 

转化fastercnn的hdf5模型用上述脚本转化失败,后来发现使用https://www.jianshu.com/p/45e575555896 提供的脚本转化成功,如下;



from RoiPoolingConv import RoiPoolingConv
from keras.models import load_model
import tensorflow as tf
import os 
import os.path as osp
from keras import backend as K
#路径参数
input_path = 'input path'
weight_file = 'epoch002-loss2.790-rpn1.490-roi1.301.hdf5'
weight_file_path = osp.join(input_path,weight_file)
output_graph_name = "fr" + '.pb'
#转换函数
def h5_to_pb(h5_model,output_dir,model_name,out_prefix = "output_",log_tensorboard = True):
    if osp.exists(output_dir) == False:
        os.mkdir(output_dir)
    out_nodes = []
    for i in range(len(h5_model.outputs)):
        out_nodes.append(out_prefix + str(i + 1))
        tf.identity(h5_model.output[i],out_prefix + str(i + 1))
    sess = K.get_session()
    from tensorflow.python.framework import graph_util,graph_io
    init_graph = sess.graph.as_graph_def()
    main_graph = graph_util.convert_variables_to_constants(sess,init_graph,out_nodes)
    graph_io.write_graph(main_graph,output_dir,name = model_name,as_text = False)
    if log_tensorboard:
        from tensorflow.python.tools import import_pb_to_tensorboard
        import_pb_to_tensorboard.import_to_tensorboard(osp.join(output_dir,model_name),output_dir)
#输出路径
output_dir = osp.join(os.getcwd(),"trans_model")
#加载模型
h5_model = load_model(weight_file,custom_objects={'RoiPoolingConv':RoiPoolingConv})
h5_to_pb(h5_model,output_dir = output_dir,model_name = output_graph_name)
print('model saved')

最后

以上就是缥缈帅哥最近收集整理的关于keras单张预测与hdf5模型转化为.pb形式的脚本的全部内容,更多相关keras单张预测与hdf5模型转化为.pb形式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(94)

评论列表共有 0 条评论

立即
投稿
返回
顶部