繁体   English   中英

如何尽快获取python中某个像素点的颜色?

[英]How to get the color of a pixel in python as fast as possible?

我在 ubuntu 上,我想每 0.1 秒检查一次屏幕上特定像素的颜色。 我怎样才能做到这一点?

我知道 PIL,但这只需要每 0.1 秒就一个像素进行完整的屏幕截图。

然后我发现这个方法使用 ctypes.windll: Faster method of reading screen pixel in Python than PIL?

但这行不通,因为我不在 Windows 上。还有其他想法吗?

编辑:感谢 b_c 解决了

from Xlib import display, X
from PIL import Image #PIL


def getColor(x,y):
    W, H = 1, 1
    dsp = display.Display()
    root = dsp.screen().root
    raw = root.get_image(x, y, W, H, X.ZPixmap, 0xffffffff)
    image = Image.frombytes("RGB", (W, H), raw.data, "raw", "BGRX")
    print image.getpixel((0, 0))
    time.sleep(0.01)

PIL 和其他类似程序通常允许您指定一个边界框来抓取较小的数量

PyAutoGui 允许您采取更小的部分

如此处所引用的https://pyautogui.readthedocs.io/en/latest/screenshot.html代码如

pyautogui.screenshot(region=(0,0, 300, 400))

可能有用

https://pillow.readthedocs.io/en/4.2.x/reference/Image.html

也可能很有用, bbox允许您只观察一个小区域。

raw.data 有时会作为字符串返回,例如当颜色为黑色时。 这会导致:

TypeError:需要类似字节的 object,而不是“str”

您发布的代码的一个肮脏的解决方法是:

from Xlib import display, X
from PIL import Image #PIL

def getColor(x,y):
    W, H = 1, 1
    dsp = display.Display()
    root = dsp.screen().root
    raw = root.get_image(x, y, W, H, X.ZPixmap, 0xffffffff)
    if isinstance(raw.data,str):
        bytes=raw.data.encode()
    else:
        bytes=raw.data
    image = Image.frombytes("RGB", (W, H), bytes, "raw", "BGRX")
    print image.getpixel((0, 0))
    time.sleep(0.01)

您好,我知道如何解决您的问题。 我创建了一个脚本,它循环检查一个或多个像素是否改变颜色。

此脚本仅使用 PIL 来执行此操作。

进行验证所需的时间为 33 毫秒。

因为那33或32ms是截屏的时间,所以无论你需要检查多少像素,时间总是33ms。 不幸的是,我还没有找到任何其他更快的 package。

import time
import keyboard
from PIL import Image, ImageGrab


while not keyboard.is_pressed('ctrl'): # press ctrl to stop.
    start_time = time.time()

    px = ImageGrab.grab().load()
    color1 = px[439, 664] # pixel 1
    color2 = px[575, 664] # pixel 2
    color3 = px[706, 664] # pixel 3
    color4 = px[842, 664] # pixel 4
    
    print(color1)

    print(f"Finish in: {round(1000 * (time.time() - start_time))} ms ") # how much  he takes to finish

暂无
暂无

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

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