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

By | June 16, 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]]

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

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