4

I use the Python 3.7.4 with TensorFlow 2.0 and Keras 2.2.4-tf to train my own CNN model. Everything goes fine. I can use e.g. model.save(my_model), and then use it in other Python scripts. Problem appears when I want to use trained model in OpenCV with its DNN module in C++. cv::dnn:readNetFromTensorflow(model.pb, model.pbtxt), takes as you can see two arguments, and I can't get the second .pbtxt file. So I decide to use .onnx format, because of its flexibility. The problem is that existing libraries keras2onnx takes only model from TensorFlow 1.*, and I want to avoid working with it. Example of code to convert it is presented below:

import tensorflow as tf
import onnx
import keras2onnx
model = tf.keras.models.load_model(my_model_folder_path)
onnx_model = keras2onnx.convert_keras(model, model.name)
onnx.save_model(onnx_model, model_name_onnx)

Is there some other ways to convert such model to onnx format?

Mimi
  • 95
  • 1
  • 10

2 Answers2

6

The latest version of keras2onnx (in github master) supports TensorFlow 2.

You can install it like this:

pip install git+https://github.com/microsoft/onnxconverter-common
pip install git+https://github.com/onnx/keras-onnx
2

You need to create a file which can hold ONNX object. Visit https://github.com/onnx/tutorials/blob/master/tutorials/OnnxTensorflowExport.ipynb

import tensorflow as tf
import onnx
import keras2onnx
model = tf.keras.models.load_model('Model.h5')
onnx_model = keras2onnx.convert_keras(model, model.name)

file = open("Sample_model.onnx", "wb")
file.write(onnx_model.SerializeToString())
file.close()