Convert TensorFlow Tensor to PIL Image using Python

Convert TensorFlow Tensor to PIL Image using Python

When working with computer vision tasks, we often need to visualize the TensorFlow tensors as images. Here the Pillow (PIL) library comes in useful. By converting TensorFlow tensor to PIL image, we can leverage the rich set of image processing capabilities provided by PIL. 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 Pillow

Code

In the following code, the image is loaded and decoded as TensorFlow tensor. Next, we convert the tensor to a PIL image. With a few lines of code, we have a PIL image that can be further processed, displayed, or saved using the extensive image manipulation functions provided by PIL.

import tensorflow as tf

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

pilImg = tf.keras.utils.array_to_img(tensorImg)

Leave a Comment

Cancel reply

Your email address will not be published.