Search code examples
pythonpyautogui

Image Recongition with pyautogui: How do I search for multiple areas at once?


I'm using python to search for images and I can do that with one area but how can I adapt this code for multiple areas?

found_image = pyautogui.locateOnScreen(image)
if found_image !=None:
    pyautogui.click(found_image)

Solution

  • welcome to stack! PIL has a flag for regions literally called region. If you specify where you regions are top left x and y and bottom right x and y you can them loop through the regions with for region_name, region in regions.items(): and then do something if your image is found in any of the regions.

    regions = {
    "Top left": (top, left, bottom, right),
    "Bottom left": (top, left, bottom, right),
    "Top right": (top, left, bottom, right),
    "Bottom right": (top, left, bottom, right)
    }
    
    for region_name, region in regions.items():
        found_image = py.locateOnScreen(image, region=region)
        if found_image != None:
            print(f"Clicked found_image in {region_name} region.")
            py.click(found_image )