Let’s extract the RGB color values for each pixel of an image in Python. We will be using Python 3.8.10. ✨✨
First, let’s install the Pillow library which is an imaging library for image processing.
pip install Pillow
Each digital image is made up of a collection of pixels. Each pixel in an image has a color, which may be represented as an RGB value/triplet/tuple. Let’s examine the following image:
Our code will extract the RGB value of each pixel in the above image. Let’s go!
from PIL import Image
im = Image.open('ex_small.png', 'r')
pix_val = list(im.getdata())
print(pix_val)
#output
#[(254, 254, 254, 254), (254, 254, 254, 253), (252, 254, 254, 244), (249, 252, 253, 246),
# (233, 247, 253, 254), (200, 236, 250, 249), (161, 217, 243, 252), (117, 203, 240, 255),
# (73, 183, 231, 255), (49, 176, 231, 255), (29, 169, 228, 255), (255, 255, 255, 255),
# ...
# (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255),
# (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255),
# (255, 255, 255, 255), (255, 255, 255, 255)]
Let’s explain what is happening here:
- We import the Image module from the pillow library. This gives us access to the open() function which will open and identify the image file ex_small.png for reading (mode=r) and return an image object as im. The image file ex_small.png must already exist in the same folder as the python script.
- The method im.getdata() will return the contents of the image as a sequence object containing pixel values. We will cast this sequence object as a python list pix_val.
When the above code executes we will get a very long list of pixel values as RGB tuples/triples/values. Each tuple is the RGB value of an individual pixel in the image.
We hope this tutorial helped. Please see another fantastic tutorial on RGB CSS3 Color Conversion and happy coding! 👌👌👌