How To Convert PIL Images to Numpy Array

This article will discuss the PIL module and various ways to convert an image to a Numpy array. Before that, let’s see what the Python PIL and Numpy module offers.

PIL (Python Image Library) is an image processing package created for Python. It provides various classes and methods that aid in the creation, editing, and exportation of image documents. Unfortunately, support for the PIL module was discontinued in 2011. However, the Pillow project, which had similar objectives, forked the PIL module. Eventually, the Pillow module replaced PIL and became the default image processing tool for Python developers.

Now that we have a brief idea about PIL let’s see what the Numpy module is about.

Numpy is the go-to module for scientific computations in Python. Numpy introduces an array object called “ndarray”. They are faster and more potent than traditional Python lists. Data Scientists make use of this module due to its efficiency and proper resource management.

Installing the Modules

PIL / Pillow

PIL is not part of the Python Standard Library. Use the following command to install PIL via PIP manually.

PIP Command for PIL/Pillow (MacOs/Linux & Windows)
$ pip install Pillow 

NumPy

Numpy is not part of the Python Standard Library. Install using the following PIP command.

PIP Command for Numpy (MacOs/Linux & Windows)
$ pip install numpy

How are PIL Images Stored? What are its Formats?

The save() function allows us to store images into multiple supported image formats.

Let’s look at the fully supported formats by the Pillow module.

  • BLP
  • BMP
  • DDS
  • DIB
  • EPS
  • GIF
  • ICNS
  • ICO
  • IM
  • JPEG
  • JPEG 2000
  • MSP
  • PCX
  • PNG
  • PPM
  • SGI
  • SPIDER
  • TGA
  • TIFF
  • WebP
  • XBM

Different Ways to a Convert PIL Image to a Numpy Array

Now that we have a brief idea about the Pillow module and the Numpy module let’s see various ways to convert a PIL image to a Numpy array.

Convert PIL Image to Numpy Array Using numpy.asarray() function

To convert a PIL image object to a numpy array, we can use numpy.asarray().

Using numpy.asarray(), we can initialize array types. Therefore, passing a PIL image object to .asarray() will convert it into a ndarray.

import numpy as np
from PIL import Image
myImage = Image.open("/content/companylogo.jpg")
myImageArr = np.asarray(myImage)
print(myImageArr.shape)

Output

(298, 33, 1500)

Convert PIL Image to Numpy array Using numpy.array() Function

Similarly, we can use the numpy.asarray() to convert a PIL image to a numpy array object.

numpy.array() function allows us to create and initialize numpy array objects. Using the function, we are converting the PIL image to a 3D ndarray. Let’s look at the following program.

import numpy as np
from PIL import Image
myImage = Image.open("/content/companylogo.jpg")
myImageArr = np.array(myImage)
print(myImageArr.shape)

Output

(298, 33, 1500)

In the above programs, we have transformed the image companylogo.png to a 3D Numpy ndarray myImageArr. Finally, we have displayed the array shapes. Note that both functions .array() and .asarray() produce similar outputs.

How To Convert a 2D Matrix to an Image in Python

Using the Numpy ndarray and the Pillow module, we can transform a 2D matrix from Numpy to an Image file. Let’s look at the following implementation.

from PIL import Image
import numpy as np

# Creating an matrix of size 50x50 with integer values
myArray = np.random.randint(300, size=(50,50), dtype=np.uint8)

resImage = Image.fromarray(arr)

# Exporting the image in png format
resImage.save("image2Darray.png")

Output

image2Darray.png
convert numpy array to pil image
Resultant image created from the 2D numpy array.

How to Convert an RGB Image to a Numpy Array

Python modules like matplotlib and openCV natively use Numpy arrays. Therefore, with the help of OpenCV, we can load an RGB Image as a Numpy array.

import cv2
imageArray = cv2.imread("RGBImage.tiff",mode='RGB')
print(type(imageArray))

Output

<type 'numpy.ndarray'>

How to Convert a 2D Numpy Array with Grayscale Values to PIL Object

Using the .linspace function, we can create a gradient between 0 and 1. The fromarray() function allows us to convert it into PIL image format.

Let’s look at the following implementation.

import numpy as np
from PIL import Image

myArray = np.linspace(0,1,256*256)


array2D = np.reshape(myArray,(256,256))

# Creates PIL image
imgGray = Image.fromarray( array2D , 'L')
imgGray.save("grayscale.png")

Output

grayscale image
grayscale.png

How To Convert a Base64 Image to Numpy Array

For example, let’s say you’re receiving a base64 encoded image from HTTP. How do we convert to a Numpy Array?

Let’s look at the following example:

import torch
import numpy as np
from PIL import Image
import base64


base64_decoded = base64.b64decode(test_image_base64_encoded)

with open("sample.jpg", "wb") as sample:
    sample.write(base64_decoded)

image = Image.open("sample.jpg")
imageArray = np.array(image)

Explanation

First off, we are decoding the base64 image. Then, we create a JPG file and write the decoded image into the file. Finally, we open the image and convert it into a NumPy array.

FAQs

How do you convert an image loaded using PIL into a Numpy array?

Numpy provides a function that aids the creation of a numpy array object. Use numpy.array() or numpy.asarray()

How do I convert Numpy Arrays to images?

The PIL modules provide a function .fromarray() that takes an array as a parameter. This allows us to convert an array object to a PIL image object.

Conclusion

In this article, we have reviewed a powerful image processing tool in Python called PIL/Pillow. Various techniques to convert image objects to a Numpy array and vice versa have been taught. We have learned the multiple image formats the PIL module allows us to work with.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments