How to Convert PIL Image to NumPy Array

Muhammad Maisam Abbas Feb 02, 2024
  1. Convert PIL Image to NumPy Array With the numpy.array() Function in Python
  2. Convert PIL Image to NumPy Array With the numpy.asarray() Function in Python
How to Convert PIL Image to NumPy Array

This tutorial will discuss the methods to convert a PIL image to a 3-dimensional NumPy array in Python.

Convert PIL Image to NumPy Array With the numpy.array() Function in Python

PIL is used to perform various operations on images in Python. The Pillow library does not come pre-installed with the Python programming language. So, we have to install it first. The command to install the Pillow library is given below.

pip install Pillow

If we want to convert an image read by the PIL library to a NumPy array, we can use the numpy.array() function. The numpy.array() function creates and initializes numpy arrays. The numpy.array() function will convert the PIL image to a 3-dimensional array. See the following code example.

import numpy as np
from PIL import Image

img = Image.open("NASA.jpg")
imgArray = np.array(img)
print(imgArray.shape)

Output:

(90, 240, 3)

In the above code, we converted the PIL image img to a 3-dimensional NumPy array imgArray with the numpy.array() function. We read the image inside the variable img with the Image.open() function in Python. We then converted the img to the NumPy array imgArray with the numpy.array() function in Python. In the end, we printed the shape of the imgArray with the print() function.

Convert PIL Image to NumPy Array With the numpy.asarray() Function in Python

We can also use the numpy.asarray() function to achieve the same goal as the previous example. The numpy.asarray() function also creates and initializes an numpy array. We can convert a PIL image to a numPy array by passing the image to the numpy.asarray() function. See the following code example.

import numpy as np
from PIL import Image

img = Image.open("NASA.jpg")
imgArray = np.asarray(img)
print(imgArray.shape)

Output:

(90, 240, 3)

In the above code, we converted the PIL image img to the 3-dimensional NumPy array imgArray with the numpy.array() function in Python. We loaded the in the img variable with the Image.open() function in Python. We then converted the img image to the NumPy array imgArray with the numpy.asarray() function in Python. In the end, we printed the shape of the imgArray with the print() function.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn