Python Pillow Read Image to NumPy Array: A Step Guide – Python Pillow Tutorial

By | August 30, 2020

When we are using python pillow or opencv to process images, we have to read image to numpy array. In this tutorial, we will introduce you how to convert image to numpy array.

Convert image to numpy array using pillow

First, we should read an image file using python pillow.

image = 'lake-1.jpg'

from PIL import Image

im = Image.open(image)

Then we can convert the image to numpy array using np.asarray() function.

im = Image.open(image)
im_data = np.asarray(im)
print(type(im_data))
print(im_data)

Run this code, we will find the im_data is numpy.ndarray.

<class 'numpy.ndarray'>
[[[ 42 105 185]
  [ 42 105 185]
  [ 41 104 184]
  ...
  [107 177 226]
  [106 178 226]
  [107 179 227]]

However, we should notice: the numpy ndarray created from image is determined by image mode.

To know what modes are supported by python pillow, you can refer to:

Understand Python Pillow Image Mode: A Completed Guide – Python Pillow Tutorial

As example above, the mode of lake-1.jpg is RGB, each image pixel will contain 3 value, such as: [ 42 105 185]

However, if the mode of lake-1.jpg is RGBA, each image pixel will contain 4 value, such as: [ 42 105 185 255]

To know how to get and convert image mode in python pillow, here is an tutorial:

Python Pillow Get and Convert Image Mode: A Beginner Guide – Python Pillow Tutorial

For example:

imx = im.convert('RGBA')

im_data = np.asarray(imx)
print(type(im_data))
print(im_data)

Run this code, you will get:

<class 'numpy.ndarray'>
[[[ 42 105 185 255]
  [ 42 105 185 255]
  [ 41 104 184 255]
  ...
  [107 177 226 255]
  [106 178 226 255]
  [107 179 227 255]]

Convert numpy ndarray to image

Here is an example:

imx = Image.fromarray(im_data)
print(type(imx))

Run this code, we can find the type of imx is:<class ‘PIL.Image.Image’>

Leave a Reply