How to Convert a NumPy Array to PIL Image in Python

Suraj Joshi Feb 02, 2024
  1. Convert a NumPy Array to PIL Image in Python
  2. Convert a NumPy Array to PIL Image Python With the Matplotlib Colormap
How to Convert a NumPy Array to PIL Image in Python

This tutorial explains how we can convert the NumPy array to a PIL image using the Image.fromarray() from the PIL package. The Python Imaging Library (PIL) is a library in Python with various image processing functions.

The Image.fromarray() function takes the array object as the input and returns the image object made from the array object.

Convert a NumPy Array to PIL Image in Python

import numpy as np
from PIL import Image

image = Image.open("lena.png")
np_array = np.array(image)

pil_image = Image.fromarray(np_array)
pil_image.show()

Output:

Convert a NumPy Array to PIL Image Python

It will read the image lena.png in the current working directory using the open() method from the Image and return an image object.

We then convert this image object to a NumPy array using the numpy.array() method.

We use the Image.fromarray() function to convert the array back to the PIL image object and finally display the image object using the show() method.

import numpy as np
from PIL import Image

array = np.random.randint(255, size=(400, 400), dtype=np.uint8)
image = Image.fromarray(array)
image.show()

Output:

Convert a self-created NumPy Array to PIL Image Python

Here, we create a NumPy array of size 400x400 with random numbers ranging from 0 to 255 and then convert the array to an Image object using the Image.fromarray() function and display the image using show() method.

Convert a NumPy Array to PIL Image Python With the Matplotlib Colormap

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib import cm

image_array = plt.imread("lena.jpg")
image_array = image_array / 255
image = Image.fromarray(np.uint8(cm.plasma(image_array) * 255))
image.show()

Output:

Convert a NumPy Array to PIL Image Python applying Matplotlib Colormap

It applies the plasma colormap from the Matplotlib package. To apply a colormap to an image, we first normalize the array with a max value of 1. The maximum value of the element in image_array is 255 in the above example. So, we divide the image_array by 255 for normalization.

We then apply the colormap to the image_array and multiply it by 255 again. Then, we convert the elements to the int format using the np.uint8() method. Finally, we convert the array into the image using the Image.fromarray() function.

Author: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn

Related Article - Matplotlib Images