tensorflow2.x保存pb模型,用于opencv3.4.16 dnn模块调用

-------------------

from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2

def save_model_to_cv_dnn(netmodel, frozen_out_path, frozen_graph_filename):

    full_model = tf.function(lambda x: netmodel(x)).get_concrete_function(tf.TensorSpec(netmodel.inputs[0].shape, netmodel.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("-" * 60)
    print("Frozen model layers: ")
    for layer in layers:
        print(layer)
    print("-" * 60)
    print("Frozen model inputs: ")
    print(frozen_func.inputs)  # 模型输入
    print("Frozen model outputs: ")
    print(frozen_func.outputs)  # 模型输出

    # 存储PB模型
    # Save frozen graph to disk
    tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
                      logdir=frozen_out_path,
                      name=f"{frozen_graph_filename}.pb",
                      as_text=False)
    # Save its text representation
    tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
                      logdir=frozen_out_path,
                      name=f"{frozen_graph_filename}.pbtxt",
                      as_text=True)

path of the directory where you want to save your model
model.save('./data/tf_model_savedmodel', save_format="tf") print('export saved model.') model_loaded = tf.keras.models.load_model('./data/tf_model_savedmodel') yout = model_loaded.predict(x_test) ylab = yout[:, 0] > 0.5 print(ylab.shape) print(y_test.shape) model_loaded.evaluate(x = x_test,y = y_test)
frozen_out_path = './'  # 存储模型的路径
name of the .pb file
frozen_graph_filename = "frozen_graph1"  # 模型名称
save_model_to_cv_dnn(model,frozen_out_path,frozen_graph_filename)

Original: https://blog.csdn.net/u010795146/article/details/122561465
Author: 这个不开车的老司机
Title: tensorflow2.x保存pb模型,用于opencv3.4.16 dnn模块调用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/511280/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球