繁体   English   中英

如何在 Python 中获取和使用 RGB 值?

[英]How to get and work with a RGB Value in Python?

我想创建一个检测像素颜色的脚本,如果它是红色(例如),它应该在脚本中进一步移动。 所以我对某个区域进行截图,保存并检测我想要的像素的颜色。

current = pyautogui.screenshot(region=(116, 710, 40, 15))
current.save("./current.png")

def rgb_of_pixel(img_path, x, y):
    im = Image.open(img_path).convert('RGB')
    r, g, b = im.getpixel((x, y))
    a = (r, g, b)
    return a

img = "./current.png"
print(rgb_of_pixel(img, 5, 5))
time.sleep(1) code here

这就是我到目前为止所得到的。 我可以打印出来,但我不知道如何用它做一个 if 语句。 同样,如果像素的颜色是红色,我希望它做一些事情。

您可以这样做(如果我正确理解您的查询):

if a == (255, 0, 0):
    print('It is red!')

这主要取决于你所说的红色,我认为,这不是一个真正的编程问题,例如,如果红色通道超过 100,并且是绿色或蓝色的两倍以上,你可以称之为红色,代码是:

def isRed(a):
    r,g,b = a
    if r>100 and g<r/2 and b<r/2:
        return True
    else:
        return False

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM