Search code examples
pythonpython-imaging-librarypixel

Pixel Loading and Evaluating with PIL


I want to create a program that loads the RGB values of each pixel in a image and saves them in some kind of list/dictionary/tuple and then when I type in a value it tells me how much pixels in the image have that value. So far I have read through the whole PIL documentation trying to find a method that could fit my needs and I have tried several other approaches with for example the .getpixel() or the .load() function, but it is very difficult to save and evaluate that information for each pixel.


Solution

  • First, you will want to convert the image to the "RGB" mode, so that you always get (R, G, B) tuples for pixels, even for grayscale/monochrome images.

    image = image.convert("RGB")
    

    Then, iterate over getdata() to build your histogram.

    colors = {}
    
    for color in image.getdata():
        colors[color] = colors.get(color, 0) + 1
    

    Then, you can use get() to retreive the number of pixels of a given color

    print colors.get((255, 255, 255), 0)  # No. of white pixels