1

Convert a NumPy Array to an image in Python

 1 year ago
source link: https://thispointer.com/convert-a-numpy-array-to-an-image-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

Advertisements

vid5e668cf2d9a0d613471368.jpg?cbuster=1600267117
liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2ZW50PTUjJaNypaZypyRcoWU9MTY1MTp0MwU5MlZ2nWRspGkurWVlVzVlPTMhMS4jJaM9MTAkMwx3JaN0YT0jJat9NDUmJax9MmI1JaZcZF9jYXNmRG9gYWyhPXRbnXNjo2yhqGVlLzNioSZmqWJJZD10nGympG9coaRypv5wo20zZGVvqWqJozZipz1uqGyiow0znXNBpHA9MCZlnT02QmY5NmY2NTUmNmQ2MTp0NmM3QmpmNxImMTqCNTQmMDqEN0I2NDMlMmAmMwMlMxQmMDM1MxQmMDM1NUYmMTMlN0Q3QwpmMmEmMwMmMmQmOTM2MmQmOTqEN0I0MmMkMmpmMwqEN0I1MmY0NDp2ODpjNwMmMmQlNmY2MTU3MmUmMDVBNTt0OTp1NTxmMwM5NmQ3RDqCNwI2MmY4NmI2RwZENwU3RDqCNmE2NDY1NmM2Qwp0NxY3MDqEN0I2RwZDNwx2RTp1Nmt3RDqCNTtmNDM1MmM3RDqCNTxmMmMlMmU3RDqCNwYmMTqEN0I0QmMkMmImNTMlMmE3REZFRxUzZGyunWQ9JaVmZXJJpEFxZHI9MTQkLwE2NC42Ml4kNwQ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lnSUlRwUmNl4mNvZwp3V1nWQ9NwI3Mmx3N2VzMmxkMSZwo250ZW50RzyfZUyxPTAzoWVxnWFQoGF5TGymqEyxPTAzoWVxnWFMnXN0SWQ9MCZxqXI9ODAjJzqxpHI9MCZaZHBlQ29hp2VhqD0znXNXZVBup3NHZHBlPTEzY2NjYT0jJzNwpGFDo25mZW50PSZwYaVmqGVlPTE2NTE3NDI2MDUlODYzqWyxPVNyn2yhZG9TUGkurWVlNwI3Mmx3ODEjODRyNvZjqWJVpzj9nHR0pHMyM0EyMxYyMxZ0nGympG9coaRypv5wo20yMxZwo252ZXJ0LWEgoaVgpHxgYXJlYXxgqG8gYW4gnW1uZ2UgnW4gpHy0nG9hJTJGJzZfo2F0U3RuqHVmPWZuoHNyJzVcZHNjPXBlZWJcZA==

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)
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)
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)
Image.save(fp)
  • Parameters:
    • fp = Name or path of the image file to be saved.
  • Returns:

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")
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
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 2D NumPy Array

If you get an error like this,

ModuleNotFoundError: No module named 'PIL'
ModuleNotFoundError: No module named 'PIL'

Then use the following command to install the pillow module,

pip3 install Pillow
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)
matplotlib.pyplot.imsave(fp, Array)
  • Parameters:
    • Array = Array which needs to be converted into image.
    • fp = Name or path to save the image.
  • Returns:

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 ")
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
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 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'
ModuleNotFoundError: No module named 'matplotlib'

Then use the following command to install the matplotlib module,

pip3 install matplotlib
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)
imageio.imwrite(fp, Array)
  • Parameters:
    • Array = Array which needs to be converted into image.
    • fp = Name or path to save the image.
  • Returns:

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 ")
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
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 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'
ModuleNotFoundError: No module named 'imageio'

Then use the following command to install the imageio module,

pip3 install imageio
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)
cv2.imwrite(fp, Array)
  • Parameters:
    • Array = Array which needs to be converted into image.
    • fp = Name or path to save the image.
  • Returns:

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 ")
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
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 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'
ModuleNotFoundError: No module named 'cv2'

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

pip3 install opencv-python
 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.

Pandas Tutorials -Learn Data Analysis with Python

 

 

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK