Convert a NumPy Array to an image in Python

In this article, we will learn how to convert a NumPy Array to an image in Python.

Table Of Contents

Given a NumPy array we need to convert it into an image in Python.

How the images are stored in a computer?

The usual black and white images are represented using a matrix. Where each cell in the matrix represent a pixel and the pixel color is either black or white. The value in the cell represent the intensity of the color, like 0 is for black and 255 is for white. The color intensity changes with the numbers in cell. So we will create a numpy array with size as (144 x 144) and fill it with random values between 0 and 255. Later we will convert this 2D NumPy Array into an image.

There are multiple ways to convert a NumPy Array to an image in Python. Lets discuss all the methods one by one with proper approach and a working code example

Convert NumPy Array to Image using fromarray() from pillow library

The pillow library has an image module. This image module provide a fromarray() method, to convert the array into any image format. We will create a 2D NumPy Aarray and will pass that array to the fromarray() method.

Let’s have a quick look at the functions that we are going to use in this example,

Syntax of randint()

random.randint(low, high=None, size=None, dtype=int)
  • Parameters:
    • low = least value of the random number to be generated.
    • high = highest value of the random number to be generated.
    • size = This specifies the shape of the numpy array to be created
    • dtype = datatype of array, by default it is int.
  • Returns:
    • Returns a numpy array filled with random numbers

Syntax of fromarray()

PIL.Image.fromarray(Array)
  • Parameters:
    • Array = Array which needs to be converted into image.
  • Returns:
    • Returns a Image object.

Syntax of save()

Image.save(fp)
  • Parameters:
    • fp = Name or path of the image file to be saved.
  • Returns:
    • None

The Approach to convert NumPy Array to an Image:

  1. Import numpy library and create 2D NumPy array using randint() method.
  2. Pass this array to the fromarray() method. This will return an image object.
  3. Save the image to the filesystem using the save() method.

Source Code

from PIL import Image
import numpy as np

# Creating the 144 X 144 NumPy Array with random values
arr = np.random.randint(255, size=(144, 144), dtype=np.uint8)

# Converting the numpy array into image
img  = Image.fromarray(arr)

# Saving the image
img.save("Image_from_array.png")

print(" The Image is saved successfully")

Output:

The Image is saved successfully

It will create an image file with name “Image_from_array.png” in the same folder. Image file will be like this,

Image created from a NumPy Array
Image created from a 2D NumPy Array

If you get an error like this,

ModuleNotFoundError: No module named 'PIL'

Then use the following command to install the pillow module,

pip3 install Pillow

Convert NumPy Array to Image using imsave() from matplotlib.pyplot

The matplotlib.pyplot module provide an imsave() method to convert the array into any image format. Create a numpy array and pass that array to the imsave() method.

Let’s have a quick look at the functions that we are going to use in this example,

Syntax of imsave()

matplotlib.pyplot.imsave(fp, Array)
  • Parameters:
    • Array = Array which needs to be converted into image.
    • fp = Name or path to save the image.
  • Returns:
    • None

The Approach to convert NumPy Array to an Image:

  1. Import numpy library and create 2D NumPy array using randint() method.
  2. Pass this array to the imsave() method.
  3. The image will be saved to the path mentioned in the method arguments.

Source Code:

import matplotlib.pyplot as mp
import numpy as np

# Creating the 144 X 144 NumPy Array with random values
arr = np.random.randint(255, size=(144, 144),dtype=np.uint8)

# Converting the NumPy Array into an image
mp.imsave("Image_from_array.png", arr)

print(" The Image is saved successfully ")

Output:

The Image is saved successfully 

It will create an image file with name “Image_from_array.png” in the same folder. Image file will be like this,

Image created from a NumPy Array
Image created from a 2D NumPy Array

It might be possible that you can get an error, if matplotlib module is not installed. Like,

ModuleNotFoundError: No module named 'matplotlib'

Then use the following command to install the matplotlib module,

pip3 install matplotlib

Convert NumPy Array to Image using imwrite() from imageio module

The imageio module provide imwrite() method to convert the array into any image format. We will create a numpy array and pass the array to imwrite() method.

Syntax of imwrite()

imageio.imwrite(fp, Array)
  • Parameters:
    • Array = Array which needs to be converted into image.
    • fp = Name or path to save the image.
  • Returns:
    • None

The Approach to convert NumPy Array to an Image:

  1. Import numpy library and create numpy array using randint() method.
  2. Pass this array to the imwrite() method.
  3. The image will be saved to the path mentioned in the method.

Source Code:

import imageio
import numpy as np

# Creating the 144 X 144 NumPy Array with random values
arr = np.random.randint(255, size=(144, 144), dtype=np.uint8)

# Converting the numpy array into image
imageio.imwrite('Image_from_array.png', arr)

print(" The Image is saved successfully ")

Output:

The Image is saved successfully 

It will create an image file with name “Image_from_array.png” in the same folder. Image file will be like this,

Image created from a NumPy Array
Image created from a 2D NumPy Array

It might be possible that you can get an error, if imageio module is not installed. Like,

ModuleNotFoundError: No module named 'imageio'

Then use the following command to install the imageio module,

pip3 install imageio

Convert NumPy Array to Image using imwrite() from opencv module

The opencv module provide imwrite() method to convert the array into any image format. We will create a numpy array and pass the array to imwrite() method

Syntax of imwrite()

cv2.imwrite(fp, Array)
  • Parameters:
    • Array = Array which needs to be converted into image.
    • fp = Name or path to save the image.
  • Returns:
    • None

The Approach to convert NumPy Array to an Image:

  1. Import numpy library and create numpy array using randint() method.
  2. Pass this array to the imwrite() method.
  3. The image will be saved to the path mentioned in the method.

Source Code

import cv2   
import numpy as np

# Creating the 144 X 144 NumPy Array with random values
arr = np.random.randint(255, size=(144, 144),dtype=np.uint8)

# Converting the numpy array into image
cv2.imwrite('Image_from_array.png', arr)

print(" The Image is saved successfully ")

Output:

The Image is saved successfully 

It will create an image file with name “Image_from_array.png” in the same folder. Image file will be like this,

Image created from a NumPy Array
Image created from a 2D NumPy Array

It might be possible that you can get an error, if opencv-python module is not installed. Like,

ModuleNotFoundError: No module named 'cv2'

Then use the following command to install the opencv-python module,

 pip3 install opencv-python

Summary

Great! you made it, We have discussed All possible methods to convert a NumPy Array to an image in Python. Happy learning.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top