使用 OpenCV C++ 进行 Tensorflow 2 对象检测

Анд*_*нко 7 c++ opencv resnet object-detection-api tensorflow2.0

我已经使用 Tensorflow 2 对象检测 API 训练了 SSD ResNet V1 模型。然后我想在 C++ 代码中将这个模型与 OpenCV 一起使用。

首先,训练后我有三个文件:

  • 检查站
  • ckpt-101.data-00000-of-00001
  • ckpt-101.index

请注意,我没有 .meta 文件,因为它不是生成的。

然后我使用exporter_main_v2.py对象检测 API 中的脚本从这些文件创建了 SavedModel :

python3 exporter_main_v2.py input_type=image_tensor --pipeline_config_path /path/to/pipeline.config --trained_checkpoint_dir=/path/to/checkouts --output_directory=/path/to/output/directory
Run Code Online (Sandbox Code Playgroud)

运行此脚本后,我得到了 saved_model.pb

我试图以这种方式在 OpenCV 中使用这个文件:

cv::dnn::Net net = cv::dnn::readNetFromTensorflow("/path/to/saved_model.pb");
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

OpenCV(4.2.0) /home/andrew/opencv/modules/dnn/src/tensorflow/tf_io.cpp:42: error: (-2:Unspecified error) FAILED: ReadProtoFromBinaryFile(param_file, param). Failed to parse GraphDef file: /home/andrew/Documents/tensorflow_detection/workspace/pb_model/saved_model/saved_model.pb in function 'ReadTFNetParamsFromBinaryFileOrDie'
Run Code Online (Sandbox Code Playgroud)

然后我尝试冻结saved_model.pb。但是,据我所知,在 TF2.x 中这是不可能的,因为 TF2.x 不支持会话和图形。我也没有 .pbtxt 文件。

我的问题:是否可以在 OpenCV C++ 中使用通过 TF2 Object Detection API 训练的模型?

如果您帮助我解决此问题或提供任何有用的建议,我将不胜感激。

小智 1

可以将 Tensorflow 2 模型与对象检测 API 和 Opencv 结合使用,如专用 wiki 中所述: https: //github.com/opencv/opencv/wiki/TensorFlow-Object-Detection-API

到目前为止,有更多型号与 Tensorflow 1 兼容,但对于 SSD 来说应该没问题。要冻结图表,您必须执行以下操作:

import tensorflow as tf

from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2

loaded = tf.saved_model.load('my_model')
infer = loaded.signatures['serving_default']

f = tf.function(infer).get_concrete_function(input_1=tf.TensorSpec(shape=[None, 224, 224, 3], dtype=tf.float32))
f2 = convert_variables_to_constants_v2(f)
graph_def = f2.graph.as_graph_def()

# Export frozen graph
with tf.io.gfile.GFile('frozen_graph.pb', 'wb') as f:
   f.write(graph_def.SerializeToString())
Run Code Online (Sandbox Code Playgroud)

正如 OpenCV Github 问题中的评论所述:https://github.com/opencv/opencv/issues/16582#issuecomment-603819498

然后,您可能需要使用tf_text_graph_ssd.pyOpenCV wiki 中提供的内容来生成冻结模型的文本图形表示,仅此而已!