此代码截取屏幕截图,然后通过将其与给定模板进行比较,在屏幕上查找给定对象,然后计算找到该对象的次数。这可以在下面的马里奥硬币图片中看到,其中程序将识别每个马里奥硬币,然后计算总共有多少。我的问题是我希望程序在运行时继续计数硬币,这样如果在屏幕上添加或减去硬币,程序就会更新计数。
例如:数 19 个硬币,数 19 个硬币,数 19 个硬币,(添加两个硬币),数 21 个硬币,数 21 个硬币等。
import cv2 as cv2
import numpy
import pyautogui
# Takes a screen shot and saves the file in the specified location
loc1 = (r'Capture.png')
pyautogui.screenshot(loc1)
# Reads the screen shot and loads the image it will be compared too
img_rgb = cv2.imread(loc1)
count = 0
n = 0
while n < 5:
# Reads the file
template_file_ore = r"mario.png"
template_ore = cv2.imread(template_file_ore)
w, h = template_ore.shape[:-1]
# Compares screen shot to given image, gives error thresh hold
res = cv2.matchTemplate(img_rgb, template_ore, cv2.TM_CCOEFF_NORMED)
threshold = 0.80
loc = numpy.where(res >= threshold)
# Puts red box around matched images and counts coins
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
count = count + 1
print(count)
n = n + 1