Home > Mobile >  How to count number of pixels for specific color from Image Using python
How to count number of pixels for specific color from Image Using python

Time:03-14

I want to calculate the total number of pixels from a image for specific color witch will have all Sade of that specific color for example blue its will check all shade of blue and will return Total count of blue pixels

What is typed but its checking for blue not for shades of blue

from PIL import Image
im = Image.open('rin_test/Images33.png')

black = 0
red = 0

for pixel in im.getdata():
    if pixel == (30,144,255): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
        blue  = 1
print('blue='   str(blue))

Sample Image for blue color enter image description here

CodePudding user response:

You can use:

blue = sum(np.all(np.array(im.getdata()) == np.array([30,144,255]), axis=1))

Note that the blue value is more likely to be zero since there is a slight chance for the image to have an exact row that is equal to [30,144,255]

CodePudding user response:

If you want different shades of blue, you have to specify a range of rgb values(that amount to different shades of blue) to be added to your variable)

For example :-

# If you want an array of the shades

blue = []
values = [<shades of blue>]
for pixel in im.getdata():
    for value in values:
        if pixel == value: 
            blue.append(value)
print('blue='   str(blue))

# If you just want to add the number of times your shades appear

blue = 0
values = [<shades of blue>]
for pixel in im.getdata():
    for value in values:
        if pixel == value: 
            blue  = 1
print('blue='   str(blue))
  • Related