本人原本使用tensorflow2.4 使用如下代码保存graph:
def export_frozen_graph(model, frozen_out_path, input_size) :
f = tf.function(lambda x: model(x))
f = f.get_concrete_function(x=tf.TensorSpec(shape=[None, input_size[0], input_size[1], input_size[2]], dtype=tf.float32))
f2 = convert_variables_to_constants_v2(f)
graph_def = f2.graph.as_graph_def()
layers = [op.name for op in f.graph.get_operations()]
print("-" * 60)
print("Frozen model layers: ")
for layer in layers:
print(layer)
print("-" * 60)
print("Frozen model inputs: ")
print(f.inputs) # 模型输入
print("Frozen model outputs: ")
print(f.outputs) # 模型输出
with tf.io.gfile.GFile(frozen_out_path, 'wb') as f:
f.write(graph_def.SerializeToString())
最后使用opencv.dnn模块加载graph计算,在tensorflow2.4下运行程序一切正常,但是当本人将tensorflow版本升级为2.5之后在原来的程序运行,opencv会报如下错误:
Traceback (most recent call last):
File "D:/资料/python/YoloV3_Project/prd.py", line 9, in <module>
cv2.dnn.readNetFromTensorflow("frozen_graph.pb")
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\tensorflow\tf_importer.cpp:2822: error: (-2:Unspecified error) More than one input is Const op in function 'cv::dnn::dnn4_v20211220::`anonymous-namespace'::TFImporter::getConstBlob'