Python provides several powerful libraries for image processing, such as Pillow (PIL). While PIL offers many functions to work with images, TensorFlow provides a comprehensive ecosystem for building and training deep learning models. Often, it becomes necessary to convert PIL image to TensorFlow tensor to seamlessly integrate image data into TensorFlow pipelines. Thankfully, this conversion process is straightforward. 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 using the PIL image module. We convert the PIL image 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. Using just a small portion of code, we got a TensorFlow tensor that can be used for further processing and analysis.
from PIL import Image
import tensorflow as tf
pilImg = Image.open('test.jpg')
tensorImg = tf.convert_to_tensor(pilImg, dtype=tf.float32)
Leave a Comment
Cancel reply