Find most used colors in image using Python
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy-to-use library developed by Alex Clark and other contributors. We’ll be working with Pillow.
Let’s understand with step-by-step implementation:
1. Read an image
For reading the image in PIL, we use Image method.
# Read an Image img = Image.open('File Name')
2. Convert into RGB image
3. Get Width and Height of Image
width, height = img.size
4. Iterate through all pixels of Image and get R, G, B value from that pixel
for x in range(0, width): for y in range(0, height): r, g, b = img.getpixel((x,y)) print(img.getpixel((x,y)))
(155, 173, 151), (155, 173, 151), (155, 173, 151), (155, 173, 151), (155, 173, 151) …
5. Initialize three variable
- r_total = 0
- g_total = 0
- b_total = 0
Iterate through all pixel and add each color to different Initialized variable.
r_total = 0 g_total = 0 b_total = 0 for x in range(0, width): for y in range(0, height): r, g, b = img.getpixel((x,y)) r_total += r g_total += g b_total += b print(r_total, g_total, b_total)
(29821623, 32659007, 33290689)
As we can R, G & B value is very large, here we will use count variable
Initialize One More variable
count = 0
Divide total color value by count
Below is the Implementation:
Image Used –
# Most Used color is Blue (179.6483313253012, 196.74100602409638, 200.54631927710844)
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course