How to convert an RGB image to a NumPy array

Hello programmers, in this tutorial we will learn to convert RGB image to a NumPy array in Python.

In image processing, all colored images use the RGB model. RGB(Red, Green, Blue) model is additive of all three colors to produce an extensive spectrum of colors. The value of each color component ranges from 0-255 pixels (a total of 256 shades of colors).

We will be using NumPy and Pillow library in Python for this tutorial. NumPy is a library for Python language used to work with 2D and 3D arrays and matrices. Python Image Library (PIL / PILLOW) is an image processing library in Python that adds support for opening editing and saving images in different file formats.

We need to install these libraries on our local machine.

To install NumPy, open your Command Prompt / Terminal and write:

pip install numpy

To install Pillow library, open your Command Prompt / Terminal and write:

pip install Pillow

 

Lets Code

We have used RGB_image.jpg to convert it into a NumPy array. Below is given the image that we are going to use for this conversion:

Importing libraries

from PIL import Image
import numpy

Image is a submodule of PIL library

img= Image.open("RGB_image.jpg")
np_array_img = numpy.array(img)

print(np_array_img)

Image.open() will take up file (image) name. numpy.array() function is used to convert RGB image into numpy array format.

Combining all code

from PIL import Image
import numpy


img= Image.open("RGB_image.jpg")
np_array_img = numpy.array(img)

print(np_array_img)
Output:
[[[ 93 28 58] [ 94 29 59] [ 91 26 56] ... [220 90 77] [220 90 77] [220 90 77]] [[ 93 28 58] [ 93 28 58] [ 94 29 59] ... [220 90 77] [220 90 77] [220 90 77]] [[ 94 29 59] [ 91 26 56] [ 94 29 59] ... [220 90 77] [220 90 77] [220 90 77]] ... [[ 95 30 60] [ 95 30 60] [ 95 30 60] ... [181 71 74] [181 71 74] [180 70 73]] [[ 95 30 60] [ 95 30 60] [ 95 30 60] ... [181 71 74] [181 71 74] [180 70 73]] [[ 95 30 60] [ 95 30 60] [ 95 30 60] ... [181 71 74] [181 71 74] [180 70 73]]]

Leave a Reply

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