Search code examples
pythonpython-3.ximagecolorspng

How to check if a PNG has a certain RGB color using Python?


I have a .png file and I want to scan through the image to check if there is a certain RGB value in it. For example, let's say I have an image and want to check if the RGB value (255, 0, 0) is somewhere in the image. How would I do this in Python? Thanks!


Solution

  • I recommend you to use PIL-Getpixel or PIL-Getdata

    from PIL import Image
    
    im = Image.open('whatever.png').convert("RGB")
    
    # get pixels
    pixels = [im.getpixel((i, j)) for j in range(im.height) for i in range(im.width)]
    
    # or
    pixels = [i for i in im.getdata()]
    
    #check if tuple of pixel value exists in array-pixel
    
    print((255, 0, 0) in pixels) #True if exists, False if it doesn't