'How to detect if a certain image is present or not in Python

I'm trying to create a robot that executes an condition if a certain image is present, but another if the image isn't on the screen. It's possible to do that with pyautogui? If it isn't which library can I use instead?

The program works fine if the image is on the screen, but sometimes it will be not be present so the program show an error.

print('Robô iniciado...')
p.hotkey('win', 'r')
p.sleep(2)
p.typewrite('C:\Program Files (x86)\AnyDesk\AnyDesk.exe')
p.sleep(3)
p.press('enter')
p.sleep(5)
janela = p.getActiveWindow()
janela.maximize()
p.sleep(4)
p.click(x=102, y=48)
p.sleep(2)
p.typewrite('Ulsan CG Oficina')
p.sleep(3)
p.press('down')
p.press('enter')
p.sleep(10)
p.click(x=300, y=300)
p.sleep(3)
localRem = p.locateOnScreen('Remmina.png', confidence=0.7)
localRemmina = p.center(localRem)
xRem, yRem = localRemmina
p.moveTo(xRem, yRem, duration=1)
p.doubleClick(xRem, yRem)
p.sleep(3)


Solution 1:[1]

I'm assuming the error is when your image Remmina.png is not on screen and so cannot be found.

The pyautogui docs say that:

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, it would be a good idea to put the locate function in a try-except block. Also, use locateCenterOnScreen instead of locateOnScreen + center.

Here is your code with the try-except.

.
.
.
p.click(x=300, y=300)
p.sleep(3)
try:
    localRemmina = p.locateCenterOnScreen('Remmina.png', confidence=0.7)
    xRem, yRem = localRemmina
    p.moveTo(xRem, yRem, duration=1)
    p.doubleClick(xRem, yRem)
    p.sleep(3)

except p.ImageNotFoundException:
    # do something else here

If this is not what you wanted, please comment with the details :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Codeman