我正在创建一个程序,该程序记录游戏的屏幕并进行模板匹配以对设置的动作做出反应。我想知道当OpenCV突出显示每个模板图像时,最好返回当前模板图像的路径名吗,因为当前解决方案遍历数组会引起诸如多次反应之类的问题?
我尝试将图像放入一个数组中,并按照所述程序进行迭代,直到引起程序问题。
import numpy as np
from PIL import ImageGrab
import cv2
import time
import glob
import pyautogui
def ow_check(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# template
template_data = []
files1= glob.glob('F:\Coding\Python\Test\Templates\*.png')
for myfile in files1:
template = cv2.imread(myfile,0)
template_data.append(template)
for tmp in template_data:
(w, h) = tmp.shape[::--1]
res = cv2.matchTemplate(processed_img, tmp, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
#drawing of the rectangle
for pt in zip(*loc[::-1]):
cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
#print('target spotted')
for file in files1:
template2 = cv2.imread(file,0)
if np.array_equal(template2,tmp):
print(file)
if file == 'F:\Coding\Python\Test\Templates\BS.PNG':
# gives us time to get situated in the game
#overworld code
print('s')
pyautogui.keyDown('s')
pyautogui.keyUp('s')
time.sleep(1.0)
仅返回if文件部分一次而不是多次?
答案 0 :(得分:0)
您可以尝试以下方法:
对检索到的文件名进行排序,以便可以将操作连接到特定的数组位置。
files1 = sorted(glob.glob('F:\Coding\Python\Test\Templates\*.png'))
然后使用枚举遍历模板。这将返回模板及其索引。
for index, tmp in enumerate(template_data):
如果找到匹配项,则可以使用索引来确定要执行的操作。
例如,如果“ BS.png”是按字母顺序排列的第一个图像文件,则在索引为0时执行所需的操作。