首页 > 解决方案 > 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!

标签: pythonpython-3.ximagecolorspng

解决方案


我建议您使用PIL-GetpixelPIL -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

推荐阅读