How to count the number of pixels of a certain color in python?

milkysheep picture milkysheep · Feb 18, 2015 · Viewed 19.5k times · Source

I have a picture of two colours, black and red, and I need to be able to count how many pixels in the picture are red and how many are black.

Answer

Matthijs picture Matthijs · Apr 15, 2015

I corrected code from 0xd3 to actually work:

from PIL import Image
im = Image.open('black.jpg')

black = 0
red = 0

for pixel in im.getdata():
    if pixel == (0, 0, 0): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
        black += 1
    else:
        red += 1
print('black=' + str(black)+', red='+str(red))