简体   繁体   English

实时获取特定像素的RGB值

[英]Get the RGB value of a specific pixel live

How would I be able to get the RGB value of a pixel on my screen live with python? 如何使用python实时获取屏幕上像素的RGB值? I have tried using 我尝试使用

from PIL import ImageGrab as ig
while(True):
    screen = ig.grab() 
    g = (screen.getpixel((358, 402))) 
    print(g)

to get the value but there is noticeable lag. 获得价值,但存在明显的滞后。

Is there another way to do this without screen capturing? 没有屏幕捕获还有另一种方法吗? Because I think this is the cause of lag. 因为我认为这是造成延迟的原因。 Is there a way to drastically speed up this process? 有没有办法大大加快这个过程?

is it possible to constrain the ig.grab() to 358, 402 and get the values from there? 是否可以将ig.grab()约束为358、402并从中获取值?

The following change will speed up it by 15% 以下更改将使速度提高15%

pixel = (358, 402)
pixel_boundary = (pixel + (pixel[0]+1, pixel[1]+1))
g = ig.grab(pixel_boundary)
return g.getpixel((0,0))

Runtime: 运行:

  • proposed: 383 ms ± 5.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 建议:383 ms±5.1 ms每个循环(平均±标准偏差,共7次运行,每个循环1次)

  • original: 450 ms ± 5.31 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 原始值:每个循环450毫秒±5.31毫秒(平均±标准偏差,共7次运行,每个循环1次)

You will probably find it faster to use mss , which is specifically designed to provide high speed screenshot capabilities in Python, and can be used like so: 您可能会发现使用mss更快,后者是专门设计用来在Python中提供高速屏幕截图功能的,可以这样使用:

import mss

with mss.mss() as sct:
    pic = sct.grab({'mon':1, 'top':358, 'left':402, 'width':1, 'height':1})
    g = pic.pixel(0,0)

See the mss documentation for more information. 有关更多信息,请参见mss文档。 The most important thing is that you want to avoid repeatedly doing with mss.mss() as sct but rather re-use a single object. 最重要的是,您要避免重复with mss.mss() as sct ,而要重用单个对象。

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

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