Convert PIL Image to NumPy Array

Convert PIL Image to NumPy Array With the
numpy.array()
Function in Python 
Convert PIL Image to NumPy Array With the
numpy.asarray()
Function in Python
This tutorial will discuss the methods to convert a PIL image to a 3dimensional 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 preinstalled 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 3dimensional 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 3dimensional 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 3dimensional 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.