简体   繁体   English

我想更快地检测 python 中的颜色

[英]I want to detect color in python faster

I made a script in python that detects color on the screen and clicks我在 python 中制作了一个脚本,它检测屏幕上的颜色并点击

import pyautogui
def get_pixel_colour(i_x, i_y):
   import PIL.ImageGrab
   return PIL.ImageGrab.grab().load()[i_x, i_y]



while(True):
   print (get_pixel_colour(400, 400))
   if (get_pixel_colour(400, 400)) == (75, 219, 106):
       pyautogui.click(400, 400)

I want to make this script faster since it only goes at about 50ms and i would like to get it to half of that.我想让这个脚本更快,因为它只运行大约 50 毫秒,我想把它缩短到一半。 I'm fairly new to coding so I have no idea what to do to make it faster我对编码还很陌生,所以我不知道该怎么做才能使它更快

In conclusion:综上所述:

import pyautogui
import PIL.ImageGrab

def get_pixel_colour(i_x, i_y):
    return PIL.ImageGrab.grab().load()[i_x, i_y]


while(True):
   c = get_pixel_colour(400, 400)
   print(c)
   if c == (75, 219, 106):
       pyautogui.click(400, 400)

First, cache the result from get_pixel_colour by storing it in a variable.首先,通过将get_pixel_colour的结果存储在一个变量中来缓存它。 This will reduce the time by half as it won't do a costly screenshot for both your print and comparison.这将减少一半的时间,因为它不会为您的打印和比较做一个昂贵的屏幕截图。

Secondly, remove the import from the function.其次,从 function 中删除导入。 It's a convention to always have the imports at the top of the file.始终将导入放在文件顶部是一个惯例。 It's also a bit more efficient as the import statement has to be evaluated multiple times if you keep it in the function.如果将 import 语句保存在 function 中,那么它的效率也会更高一些。 It won't import the module every time, but it still costs a small fraction of time.它不会每次都导入模块,但它仍然花费一小部分时间。

Thirdly, you probably want to be more efficient about it and only grab the pixels you're interested in. grab takes an argument bbox which defines a bounding box of the pixels you want to grab.第三,您可能希望提高效率,只抓取您感兴趣的像素grab接受一个参数bbox ,它定义了您要抓取的像素的边界框。

import pyautogui
import PIL.ImageGrab


def get_pixel_colour(x, y):
    return PIL.ImageGrab.grab(bbox=(x, y, x+1, y+1)).load()[0, 0]


while True:
    colour = get_pixel_colour(400, 400)
    print(colour)
    if colour == (75, 219, 106):
        pyautogui.click(400, 400)

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

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