Display and save Numpy array as Image

In this article, we have explained the process of how to display and save a Numpy array as an Image. This requires Numpy and PIL library.

Table of contents:

  1. Display Numpy array as Image
  2. Complete Python Code

Display Numpy array as Image

Import the relevant library to display and save Numpy array as Image. We import numpy library to create Numpy array and PIL library to add support for display and saving.

from PIL import Image
import numpy as np

Create a sample Numpy array and convert the array to PIL format using fromarray() function of PIL.

height = 500
weight = 500
channel = 3
img_numpy = np.zeros((height, weight, channel), dtype=np.uint8)
img = Image.fromarray(img_numpy, "RGB")

To view the image from the terminal use the show() function:

# Display the Numpy array as Image
img.show()

This will open a new terminal window where the image will be displayed.

To save the Numpy array as a local image, use the save() function and pass the image filename with the directory where to save it.

# Save the Numpy array as Image
image_filename = "opengenus_image.jpeg"
img.save(image_filename)

This will save the Numpy array as a jpeg image.

Complete Python Code

Following is the complete Python code to display and save Numpy array as Image:

from PIL import Image
import numpy as np

height = 500
weight = 500
channel = 3
img_numpy = np.zeros((height, weight, channel), dtype=np.uint8)
img = Image.fromarray(img_numpy, "RGB")
# Display the Numpy array as Image
img.show()

# Save the Numpy array as Image
image_filename = "opengenus_image.jpeg"
img.save(image_filename)

With this article at OpenGenus, you must have the complete idea of how to display and save Numpy array as image.