Here's the code that I'm trying to run:
import pyautogui r=pyautogui.locateOnScreen('C:\Users\David\Desktop\index.png',grayscale=False) print r
It has to be a pixel-perfect match in order to be found. To allow for any sort of deviance you can invoke a confidence parameter.
loc = pyautogui.locateOnScreen(image, grayscale=True, confidence=.5)
However, in order to use the confidence parameter you have to have opencv_python installed. This is easy to install with pip:
./python -m pip install opencv_python
After that is in place, you should be able to account for minor differences.
locateOnScreen() function returns
None if the image wasn't found on the screen. Remember, the match has to be pixel-perfect in order to match it, so be sure to crop index.png to the smallest recognizable size to prevent extra details from ruining your match. Also, make sure the thing you are looking for is not obscured by any other windows on top of it.
I had same issue and kept returning None value.
I did several trials and found the solution for me. OS : MacOS
I saved photo with my system screenshot tool ( command+shift+5) and saved. it seems it's different pixel info as what it's displayed in my screen. Therefore I used pyautogui screenshot instead to save the photo which I wanted to.
pyautogui.screenshot('num7_.png', region=(260,360, 110, 100))
After that, it's working good regardless of grayscale parameter.
pyautogui.locateOnScreen('num7_.png') Box(left=260, top=360, width=110, height=100)
The official documentation says;
The Locate Functions NOTE: As of version 0.9.41, if the locate functions can’t find the provided image, they’ll raise ImageNotFoundException instead of returning None.
So you can decide whether an exception was raise or not. Also you should try for a finite number of times not a
While True loop.
retry_counter = 0 while retry_counter < 5: try: result = pyautogui.locateOnScreen(IMAGE_PATH_TO_FIND) if result: time.sleep(1) retry_counter = 10 # to break the loop except: time.sleep(1) # retry after some time, i.e. 1 sec retry_counter += 1
import pyautogui image = '9.png' loc = pyautogui.locateOnScreen(image, grayscale=True, confidence=.5) print (loc)
import pyautogui import time time.sleep(5) image = '9.png' loc = pyautogui.locateOnScreen(image, grayscale=True, confidence=.5) print (loc)
Summary: Just add this two lines:
import time time.sleep(5)
Box(left=1686, top=248, width=70, height=47) >>> import time time.sleep(5)