How can I make image recognition faster on python?

Question:

I want to recognize some photos from a game and used python for it, if I run code with less characters code works fine but when I continue to add characters it often can’t recognize characters because they disappear fast. I think the main problem is my code is working slow with lots of characters but I don’t know how to fix it.

from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con
name = ["char1", "char2","char3","char4","char5","char6","char7"]
    
while 1:
    for i in name:
      if pyautogui.locateOnScreen(i + '.png', region=(0,40,500,130), grayscale=True, confidence=0.6) != None:
        print(i)
      else:
        print(" ")
Asked By: protocolHost

||

Answers:

The code you posted executes the locateOnScreen function for each character. However, such invocations are executed sequentially, which means that the total execution time of the program can be estimated to be O(n) where n is the number of characters to recognize. Thus, the more characters you need to recognize, the more time is needed to complete each iteration.
What I suggest you is to try to change the approach of solving such problem either:

  • acquiring a single screenshot of the screen and then perform multiple locations on it (however, when the results of all detections are returned the screen could have changed)
  • using multithreading to perform multiple locateOnScreen in parallel.

The proper solution strictly depends on the needs for your application.

Answered By: Niccolò Borgioli
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.