How to convert an image to a matrix in Python

Published on Aug. 22, 2023, 12:16 p.m.

To convert an image to a matrix in Python, you can use the Pillow library and NumPy. Here’s an example code:

from PIL import Image
import numpy as np

# open the image
img = Image.open('input_image.jpg')

# convert the image to a NumPy array
img_arr = np.asarray(img)

# print the shape of the array (height x width x RGB channels)
print(img_arr.shape)

In this code, the Image module from the Pillow library is used to open the input image. The asarray() function from NumPy is then used to convert the image to a NumPy array. Finally, the shape of the array is printed to the console using the shape attribute of the NumPy array.

Note that the resulting matrix will have dimensions of height x width x RGB channels, where the RGB channels represent the color values of each pixel. The values in the matrix range from 0 to 255, representing the intensity of each color channel.

Tags: