Convert PIL Image to PyTorch Tensor using Python

Convert PIL Image to PyTorch Tensor using Python

PyTorch uses tensors as its fundamental data structure. However, when working with images in Python, we often process them using Pillow (PIL) library. Therefore, we need to convert PIL image to PyTorch tensor before using image with PyTorch models. Thankfully, 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 torch torchvision
pip install Pillow

Code

In the following code, we load the image using the PIL image module. Next, we convert the PIL image to a PyTorch tensor. With just a few lines of code, we got a PyTorch tensor that can be utilized for additional processing tasks.

from PIL import Image
import torchvision.transforms as transforms

pilImg = Image.open('test.jpg')

tensorImg = transforms.PILToTensor()(pilImg)

Leave a Comment

Cancel reply

Your email address will not be published.