是否可以使用python检测像素颜色?

问题描述 投票:-1回答:1

我试图编写一个程序,只是要通过颜色来检测确切的像素,然后执行某种操作,无论是否找到该像素。我认为您(显然)无法使用香草python做到这一点,但是我还没有找到任何模块来做到这一点。如果可能的话,我想举一些例子。感谢您的建议。

编辑:基本上,我需要扫描一个像素并获取RGB值

python colors pixel
1个回答
0
投票

您可以尝试以下功能。它是https://stackoverflow.com/a/765829/8581025中代码的修改版本。

from PIL import Image

def detect_color(rgb, filename):
    img = Image.open(f'{filename}')
    img = img.convert('RGBA')
    data = img.getdata()

    for item in data:
        if item[0] == rgb[0] and item[1] == rgb[1] and item[2] == rgb[2]:
            return True
    return False

例如,如果您想知道example.png文件中是否有红色像素(255,0,0),则可以使用以下代码。

detect_color((255, 0, 0), filename)  # returns True if there is a red pixel, False otherwise.
© www.soinside.com 2019 - 2024. All rights reserved.