简体   繁体   English

无法将 tensorflow 冻结图转换为 pbtxt 文件

[英]Failed to convert tensorflow frozen graph to pbtxt file

I want to extract pbtxt file given an input of tensorflow frozen inference graph.我想提取 tensorflow 冻结推理图输入的 pbtxt 文件。 In order to do this I am using the below script :为了做到这一点,我使用以下脚本:

import tensorflow as tf

#from google.protobuf import text_format
from tensorflow.python.platform import gfile

def converter(filename): 
  with gfile.FastGFile(filename,'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    tf.import_graph_def(graph_def, name='')
    tf.train.write_graph(graph_def, 'pbtxt/', 'protobuf.pbtxt', as_text=True)
    print(graph_def)
  return


#converter('ssd_mobilenet_v1_coco_2017_11_17/frozen_inference_graph.pb')  # here you can write the name of the file to be converted
# and then a new file will be made in pbtxt directory.

converter('ssd_mobilenet_v1_coco_2017_11_17/frozen_inference_graph.pb')

As an example, I am using ssd mobilenet architecture.例如,我使用的是 ssd mobilenet 架构。 Using the above code I get the output as pbtxt but I cannot use it.使用上面的代码我得到输出为 pbtxt 但我不能使用它。 For reference see the image below参考下图

在此处输入图片说明

RIGHT: Image of original pbtxt file of mobile-net architecture右:移动网络架构的原始 pbtxt 文件图像

LEFT: Image of pbtxt file obtained by using above script.左:使用上述脚本获得的 pbtxt 文件的图像。

When I use The official pbtxt on the RIGHT I get correct results.当我使用右侧的官方 pbtxt 时,我得到了正确的结果。 But, I do not get any prediction when I use LEFT pbtxt which I generated using above script但是,当我使用我使用上述脚本生成的 LEFT pbtxt 时,我没有得到任何预测

I am using these predictions on open cv DNN module我在 open cv DNN 模块上使用这些预测

tensorflowNet = cv2.dnn.readNetFromTensorflow('ssd_mobilenet_v1_coco_2017_11_17/frozen_inference_graph.pb', 'pbtxt/protobuf.pbtxt')

How do I convert mobilenet frozen inference graph into proper pbtxt format so that I can get inference ?如何将 mobilenet 冻结推理图转换为正确的 pbtxt 格式,以便进行推理?

References: https://gist.github.com/Arafatk/c063bddb9b8d17a037695d748db4f592参考资料: https : //gist.github.com/Arafatk/c063bddb9b8d17a037695d748db4f592

Heres what worked for me这对我有用

  • git clone https://github.com/opencv/opencv.git git 克隆https://github.com/opencv/opencv.git
  • Navigate to opencv/samples/dnn/导航到 opencv/samples/dnn/
  • Copy frozen_inference_graph.pb, and *.config file corresponding to your pb file复制frozen_inference_graph.pb,和你的pb文件对应的*.config文件
  • Paste the copied files in opencv/samples/dnn directory将复制的文件粘贴到 opencv/samples/dnn 目录中
  • Make a new folder in the den directory and name it "exported_pbtxt"在 den 目录中创建一个新文件夹并将其命名为“exported_pbtxt”

And run this script:并运行这个脚本:

python3 tf_text_graph_ssd.py --input frozen_inference_graph.pb --output exported_pbtxt/output.pbtxt --config pipeline.config

在此处输入图片说明

That's all you need, now copy the frozen inference graph and newely generated pbtxt file.这就是你所需要的,现在复制冻结的推理图和新生成的 pbtxt 文件。 And, use the following script to run your model using OpenCV:并且,使用以下脚本使用 OpenCV 运行您的模型:

import cv2

# Load a model imported from Tensorflow
tensorflowNet = cv2.dnn.readNetFromTensorflow('card_graph/frozen_inference_graph.pb', 'exported_pbtxt/output.pbtxt')

# Input image
img = cv2.imread('image.jpg')
rows, cols, channels = img.shape

# Use the given image as input, which needs to be blob(s).
tensorflowNet.setInput(cv2.dnn.blobFromImage(img, size=(300, 300), swapRB=True, crop=False))

# Runs a forward pass to compute the net output
networkOutput = tensorflowNet.forward()

# Loop on the outputs
for detection in networkOutput[0,0]:

    score = float(detection[2])
    if score > 0.9:

        left = detection[3] * cols
        top = detection[4] * rows
        right = detection[5] * cols
        bottom = detection[6] * rows

        #draw a red rectangle around detected objects
        cv2.rectangle(img, (int(left), int(top)), (int(right), int(bottom)), (0, 0, 255), thickness=2)

# Show the image with a rectagle surrounding the detected objects 
cv2.imshow('Image', img)
cv2.waitKey()
cv2.destroyAllWindows()

Please follow this guide: https://github.com/opencv/opencv/wiki/TensorFlow-Object-Detection-API .请遵循本指南: https : //github.com/opencv/opencv/wiki/TensorFlow-Object-Detection-API There is no sense to create a .pbtxt without modifying it.创建 .pbtxt 而不修改它是没有意义的。 The script from guide creates an extra text graph which is used for import to OpenCV.指南中的脚本创建了一个额外的文本图,用于导入到 OpenCV。

Might help someone.可能会帮助某人。 Met the same problem with mars-small128.pb for OpenCV 4.3.0 pulled from master从 master 中提取的 OpenCV 4.3.0 的 mars-small128.pb 遇到了同样的问题

import argparse
import tensorflow as tf
from tensorflow.python.saved_model import signature_constants

def save(graph_pb, export_dir):
builder = tf.saved_model.builder.SavedModelBuilder(export_dir)

with tf.gfile.GFile(graph_pb, "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

sigs = {}

with tf.Session(graph=tf.Graph()) as sess:
    # INFO: name="" is important to ensure we don't get spurious prefixing
    tf.import_graph_def(graph_def, name='')
    g = tf.get_default_graph()

    # INFO: if name is added the input/output should be prefixed like:
    #       name=net => net/images:0 & net/features:0
    inp = tf.get_default_graph().get_tensor_by_name("images:0")
    out = tf.get_default_graph().get_tensor_by_name("features:0")

    sigs[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \
        tf.saved_model.signature_def_utils.predict_signature_def(
            {"in": inp}, {"out": out})

    builder.add_meta_graph_and_variables(sess,
                                         [tag_constants.SERVING],
                                         signature_def_map=sigs)

builder.save(as_text=True)


if __name__ == '__main__':
    # export_dir = './saved'
    # graph_pb = '../models/deep_sort/mars-small128.pb'

    parser = argparse.ArgumentParser()
    parser.add_argument('--input', help="path to frozen pb file")
    parser.add_argument('--output', help="Folder to save")
    args = parser.parse_args()
    if args.input is not None and args.output:
        save(args.input, args.output)
    else:
        print(f"Usage adapt_opencv.py.py --input 'path_to_bp' --output './saved'")

Convert pb to pbtxt for TF 2.xxx:将 TF 2.xxx 的 pb 转换为 pbtxt:

import tensorflow as tf
from google.protobuf import text_format
from tensorflow.python.platform import gfile

def graphdef_to_pbtxt(filename): 
    with open(filename,'rb') as f:
        graph_def = tf.compat.v1.GraphDef()
        graph_def.ParseFromString(f.read())
    with open('protobuf.txt', 'w') as fp:
        fp.write(str(graph_def))
    
graphdef_to_pbtxt('saved_model.pb')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将冻结图转换为 TensorFlow lite - How to convert frozen graph to TensorFlow lite TensorFlow:有没有办法将冻结图转换为检查点模型? - TensorFlow: Is there a way to convert a frozen graph into a checkpoint model? 如何将在 tensorflow 2 中训练的模型转换为 tensorflow 1 冻结图 - How can I convert a model trained in tensorflow 2 to a tensorflow 1 frozen graph 如何使用 tensorflow 2 生成frozen_inference_graphe.pb 和.pbtxt 文件 - How to generate frozen_inference_graphe.pb and .pbtxt files with tensorflow 2 张量流-object-detection.pbtxt; 无此文件或目录 - tensorflow - object-detection.pbtxt; No such file or directory Tensorflow:加载 .pb 文件,然后将其保存为冻结图问题 - Tensorflow: Load a .pb file and then save it as a frozen graph issues 从 Tensorboard 上保存的 .pbtxt 文件查看图表 - Viewing Graph from saved .pbtxt file on Tensorboard 使用现有的 freeze_interface_graph.pb 和 label_map.pbtxt 部署 TFX - deploy TFX with existing frozen_interface_graph.pb and label_map.pbtxt 如何将Tensorflow Simple Audio Recognition冷冻图(.pb)转换为Core ML模型? - How to convert Tensorflow Simple Audio Recognition frozen graph(.pb) to Core ML model? 如何将预训练的 tensorflow pb 冻结图转换为可修改的 h5 keras 模型? - How to convert a pretrained tensorflow pb frozen graph into a modifiable h5 keras model?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM