VOOZH about

URL: https://thenewstack.io/tutorial-import-an-onnx-model-into-tensorflow-for-inference/

⇱ Tutorial: Import an ONNX Model into TensorFlow for Inference - The New Stack


TNS
SUBSCRIBE
Join our community of software engineering leaders and aspirational developers. Always stay in-the-know by getting the most important news and exclusive content delivered fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter in the past. Click the button below to open the re-subscribe form in a new tab. When you're done, simply close that tab and continue with this form to complete your subscription.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!

We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.

What’s next?

Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.

Follow TNS on your favorite social media networks.

Become a TNS follower on LinkedIn.

Check out the latest featured and trending stories while you wait for your first TNS newsletter.

PREV
1 of 2
NEXT
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
Thanks for your opinion! Subscribe below to get the final results, published exclusively in our TNS Update newsletter:
NEW! Try Stackie AI
From clobbered drafts to real-time sync
Apr 14th 2026 10:00am, by David Moore
TypeScript 6.0 RC arrives as a bridge to a faster future
Mar 14th 2026 9:00am, by Darryl K. Taft
Mastra empowers web devs to build AI agents in TypeScript
Jan 28th 2026 11:00am, by Loraine Lawson
2020-07-24 09:22:09
Tutorial: Import an ONNX Model into TensorFlow for Inference
feature,tutorial,
Software Development

Tutorial: Import an ONNX Model into TensorFlow for Inference

This post is the fourth in a series of introductory tutorials on the Open Neural Network Exchange (ONNX), an initiative from AWS, Microsoft, and Facebook to define a standard for interoperability across machine learning platforms.
Jul 24th, 2020 9:22am by Janakiram MSV
👁 Featued image for: Tutorial: Import an ONNX Model into TensorFlow for Inference
Feature image: Second-order Cauchy stress tensor, Wikipedia.
This post is the fourth in a series of introductory tutorials on the Open Neural Network Exchange (ONNX), an initiative from AWS, Microsoft, and Facebook to define a standard for interoperability across machine learning platforms. See: Part 1, Part 2, and Part 3.

In the last tutorial, we trained a CNN model in PyTorch and converted that into an ONNX model. In the current tutorial, we will import the model into TensorFlow and use it for inference.

Before proceeding, make sure that you completed the previous tutorial as this is an extension of the same.

Converting ONNX Model to TensorFlow Model

The output folder has an ONNX model which we will convert into TensorFlow format.

ONNX has a Python module that loads the model and saves it into the TensorFlow graph.

pip install onnx_tf

We are now ready for conversion. Create a Python program with the below code and run it:

import onnx
from onnx_tf.backend import prepare

onnx_model = onnx.load("output/model.onnx")
tf_rep = prepare(onnx_model)
tf_rep.export_graph("output/model.pb")

The output folder contains three models: PyTorch, ONNX, and TensorFlow.

👁 Image

We are now ready to use the model in TensorFlow. Note that it works only with TensorFlow 1.x. For this tutorial, we are using the 1.15, which is the last version.

import tensorflow as tf
import numpy as np
import cv2

import logging, os
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"

INPUT_TENSOR_NAME = 'input.1:0'
OUTPUT_TENSOR_NAME = 'add_4:0'
IMAGE_PATH="0.png"
PB_PATH="output/model.pb"

img = cv2.imread(IMAGE_PATH)
img = np.dot(img[...,:3], [0.299, 0.587, 0.114])
img = cv2.resize(img, dsize=(28, 28), interpolation=cv2.INTER_AREA)
img.resize((1, 1, 28, 28))

with tf.gfile.FastGFile(PB_PATH, 'rb') as f:
 graph_def = tf.GraphDef()
 graph_def.ParseFromString(f.read())

with tf.Graph().as_default() as graph:
 tf.import_graph_def(graph_def, name="")

input_tensor = graph.get_tensor_by_name(INPUT_TENSOR_NAME)
output_tensor = graph.get_tensor_by_name(OUTPUT_TENSOR_NAME)

with tf.Session(graph=graph) as sess:
 output_vals = sess.run(output_tensor, feed_dict={input_tensor: img}) #

prediction=int(np.argmax(np.array(output_vals).squeeze(), axis=0))
print(prediction)

We start by importing the right modules and then disable the warnings generated by TensorFlow.

The names for input and output tensor can be taken from Netron tool by opening the model.pb file.

The input node (input.1) and output node (add_4) name and shape are visible in the Netron.

👁 Image

👁 Image

The next few lines of code preprocess the image through OpenCV. We then open the TensorFlow model and create a session based on the graph.

Finally, by applying the argmax function, we classify the output into one of the ten classes defined by MNIST.

In this tutorial, we imported an ONNX model into TensorFlow and used it for inference. In the next part, we will build a computer vision application that runs at the edge powered by Intel’s Movidius Neural Compute Stick. The model uses an ONNX Runtime execution provider optimized for the OpenVINO Toolkit. Stay tuned.

Janakiram MSV’s Webinar series, “Machine Intelligence and Modern Infrastructure (MI2)” offers informative and insightful sessions covering cutting-edge technologies. Sign up for the upcoming MI2 webinar at http://mi2.live.

TRENDING STORIES
Janakiram MSV (Jani) is a practicing architect, research analyst, and advisor to Silicon Valley startups. He focuses on the convergence of modern infrastructure powered by cloud-native technology and machine intelligence driven by generative AI. Before becoming an entrepreneur, he spent...
Read more from Janakiram MSV
SHARE THIS STORY
TRENDING STORIES
SHARE THIS STORY
TRENDING STORIES
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.