'How to find correct template match without running the template match algorithim multiple times

I am creating a bot to play the offline chrome dino game with openCV and python. There are multiple different obstacles that are I need the computer to recognize. I need it to run as few template match algorithms as possible because when I run all of them it takes too long. Does anyone have an idea on how I would go about this?

def template_match(screen, scale, x_cords, path):
    template = cv2.imread(path, 0)
    h, w = template.shape # gives height and width of template image

    target = cv2.matchTemplate(screen, template, cv2.TM_SQDIFF_NORMED)
    _, _, min_loc, _ = cv2.minMaxLoc(target) # gives coordinates of the found image

    location = list(min_loc)
    bottom_right = (int((location[0] + w)*scale), int((location[1] + h)*scale)) # defining bottom
right of rectangle
    x, y = bottom_right 
    cv2.rectangle(screen, location, bottom_right, 0, 5)

    x_cords.append(x)
    return x, y
  
        x_cords = []

        # coordinate names correspond to size and quantity of the obstacle (ex. S2 -> 2 small cacti, B1 -> 1 big cactus)

        xD, yD = template_match(frame, 0.8, x_cords, 'C:/Users/wmcbr/OneDrive/Desktop/python/PROJECTS/Dino_Bot_Folder/assets/dino_ss.png')
        
        # All the obstacles template matching

        xB1, yB1 = template_match(frame, 1.0, x_cords, 'C:/Users/wmcbr/OneDrive/Desktop/python/PROJECTS/Dino_Bot_Folder/assets/1_big_ss.png')
        xB4, yB4 = template_match(frame, 1.0, x_cords, 'C:/Users/wmcbr/OneDrive/Desktop/python/PROJECTS/Dino_Bot_Folder/assets/4_big_ss.png')
        xS1, yS1 = template_match(frame, 1.0, x_cords, 'C:/Users/wmcbr/OneDrive/Desktop/python/PROJECTS/Dino_Bot_Folder/assets/1_small_ss.png')
        xS2, yS2 = template_match(frame, 1.0, x_cords, 'C:/Users/wmcbr/OneDrive/Desktop/python/PROJECTS/Dino_Bot_Folder/assets/2_small_ss.png')
        xS3, yS3 = template_match(frame, 1.0, x_cords, 'C:/Users/wmcbr/OneDrive/Desktop/python/PROJECTS/Dino_Bot_Folder/assets/3_small_ss.png')
        


Solution 1:[1]

I ended up only using 2 template images (1 of the bigger cactus and one of the smaller). Because all the cacti themselves look the same, I just made the template have some white space on the left so it only recognizes the caci furthest to the left in the cluster. I then just used whichever was closest to the dino to determine when to jump.

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 whm33