Convert OpenCV Image to TensorFlow Tensor using Python

Convert OpenCV Image to TensorFlow Tensor using Python

OpenCV is widely used for image processing and computer vision tasks, while TensorFlow provides a powerful framework for building and training deep learning models. Most of the time, it is necessary to convert an OpenCV image to a TensorFlow tensor to take advantages of both libraries. Luckily, this conversion process is pretty simple. This tutorial shows 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 the image using OpenCV. The image is returned as a NumPy array in the BGR color format. Since TensorFlow typically expects images in RGB format, we convert the color space from BGR to RGB. Finally, the NumPy array is converted to a TensorFlow tensor. We specify that the tensor should have a data type of float32, which is a common choice for image data in TensorFlow. That's all, now tensor can be used in TensorFlow for further processing tasks.

import cv2
import tensorflow as tf

cvImg = cv2.imread('test.jpg')
cvImg = cv2.cvtColor(cvImg, cv2.COLOR_BGR2RGB)

tensorImg = tf.convert_to_tensor(cvImg, dtype=tf.float32)

Leave a Comment

Cancel reply

Your email address will not be published.