w3resource

NumPy: Convert a PIL Image into a NumPy array


Convert PIL Image to NumPy Array

Write a NumPy program to convert a PIL image into a NumPy array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Importing the PIL library for handling image data
import PIL

# Opening an image file 'w3resource-logo.png' using PIL's Image module and storing the image data in 'img_data'
img_data = PIL.Image.open('w3resource-logo.png')

# Converting the image data into a NumPy array and storing it in 'img_arr'
img_arr = np.array(img_data)

# Printing the NumPy array representation of the image
print(img_arr) 

Sample Output:

[[[255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]
  ...
  [255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]]

 [[255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]
  ...
  [255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]]

 [[255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]
  ...
  [255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]]

 ...

 [[255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]
  ...
  [255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]]

 [[255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]
  ...
  [255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]]

 [[255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]
  ...
  [255 255 255   0]
  [255 255 255   0]
  [255 255 255   0]]]

Explanation:

In the above code -

img_data = PIL.Image.open('w3resource-logo.png'): Read the image file 'w3resource-logo.png' using PIL's Image.open() function and store the image data in the variable 'img_data'.

img_arr = np.array(img_data): Convert the image data stored in 'img_data' to a NumPy array named 'img_arr'. The NumPy array will have a shape corresponding to the image's height, width, and the number of color channels (typically 3 for RGB images or 4 for RGBA images).

Finally print() function prints the NumPy array 'img_arr' to the console.

Python-Numpy Code Editor: