Find most used colors in image using Python
Last Updated :
16 Oct, 2021
Prerequisite: PIL
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
img.convert('RGB')
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)))
Output:
(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)
Output:
(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 –
Python3
from PIL import Image
def most_common_used_color(img):
width, height = img.size
r_total = 0
g_total = 0
b_total = 0
count = 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
count + = 1
return (r_total / count, g_total / count, b_total / count)
img = Image. open (r 'C:\Users\HP\Desktop\New folder\mix_color.png' )
img = img.convert( 'RGB' )
common_color = most_common_used_color(img)
print (common_color)
|
Output:
# Most Used color is Blue
(179.6483313253012, 196.74100602409638, 200.54631927710844)
Share your thoughts in the comments
Please Login to comment...