Convert TensorFlow Tensor to OpenCV Image using Python

Convert TensorFlow Tensor to OpenCV Image using Python

When working with computer vision and deep learning tasks, TensorFlow and OpenCV are two powerful libraries that often go hand in hand. In certain scenarios, you may need to convert TensorFlow tensor to OpenCV image to bridge the gap between these libraries. Fortunately, the conversion process is straightforward. This tutorial explains how to do that using Python.

Prepare environment

  • Install the following packages using pip:
pip install tensorflow
pip install opencv-python

Code

In the following code, we read and decode the image file as a TensorFlow tensor. Next, we convert the tensor to a NumPy array and do color space from RGB to BGR conversion because OpenCV expects images in the BGR color format. That's it, now the image can be further processed, displayed, or used with OpenCV functions for various computer vision tasks.

import cv2
import tensorflow as tf

tensorImg = tf.io.decode_image(tf.io.read_file('test.jpg'))

cvImg = cv2.cvtColor(tensorImg.numpy(), cv2.COLOR_RGB2BGR)

Leave a Comment

Cancel reply

Your email address will not be published.