Search code examples
pythonpyautogui

How do I fix the pyautogui's locateOnScreen not finding anything?


Here is the code,

import pyautogui
import time

while 1:
    if pyautogui.locateOnScreen("something.png", region=(0,400,575,400), confidence =0.6 )  != None:
        print(" I see")
        time.sleep(0.1)
    else:
        print("Me no see")
        time.sleep(0.1)

It just prints "Me no see" over and over no matter how much I try. I have tried putting the confidence to 0.5 but that just prints "I see".


Solution

  • You can find a great documentation about Screenshot Functions for pyautogui.

    The confidence argument is optional and must have OpenCV to work. The region argument is also optional, you can remove and the image will be still found. You can use the argument grayscale=True if you want. As doc says: This desaturates the color from the images and screenshots, speeding up the locating but potentially causing false-positive matches.

    The only not optional argument is the image, which needs to be a .png extension.
    You also need to provide the image taken from the same resolution and scale took from the screen.

    Suppose you are providing the image something.png that has been taken from a browser with 150% zoom, and also searching this image from a 100% zoom, it won't find the image no matter the arguments you are using it!

    So remember to save the images again in order to find them!

    import pyautogui
    
    if pyautogui.locateOnScreen("something.png", grayscale=True, confidence=0.8) != None:
        print("I see")