Reputation: 1
I made a script in python that detects color on the screen and clicks
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. I'm fairly new to coding so I have no idea what to do to make it faster
Upvotes: 0
Views: 352
Reputation: 9756
First, cache the result from get_pixel_colour
by storing it in a variable. 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. 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. 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.
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)
Upvotes: 0
Reputation: 2921
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)
Upvotes: 1