基于OpenCV C++的TensorFlow 2目标检测 [英] Tensorflow 2 Object Detection with OpenCV C++

查看:51
本文介绍了基于OpenCV C++的TensorFlow 2目标检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

首先,经过培训,我有三个文件:

  • 检查点
  • CKPT-101.数据-00000/00001
  • 检查点-101.index

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

然后我使用对象检测API中的exporter_main_v2.py脚本从这些文件创建了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

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

我尝试在OpenCV中使用此文件的方式如下:

cv::dnn::Net net = cv::dnn::readNetFromTensorflow("/path/to/saved_model.pb");

但我收到以下错误:

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'

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

我的问题:在OpenCV C++中可以使用TF2对象检测API训练的模型吗?

如果您能帮助我解决这些问题或给我任何有用的建议,我将不胜感激。

推荐答案

可以将TensorFlow 2模型与对象检测API和OpenCV一起使用,如专用维基中所述: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())

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

然后您可能需要使用OpenCV wiki中提供的tf_text_graph_ssd.py来生成冻结模型的文本图形表示,就是这样!

这篇关于基于OpenCV C++的TensorFlow 2目标检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆