python - 计算图像出现在屏幕上的次数
问题描述
此代码截取屏幕截图,然后通过将其与给定模板进行比较,在屏幕上查找给定对象,然后计算找到该对象的次数。这可以在下面的马里奥硬币图片中看到,其中程序将识别每个马里奥硬币,然后计算总共有多少。我的问题是我希望程序在运行时继续计数硬币,这样如果在屏幕上添加或减去硬币,程序就会更新计数。
例如:数 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
解决方案
有很多方法可以做到这一点,例如创建一个包含要检查匹配的图像[屏幕截图] 的列表,并将所有代码通过列表项放在 for 循环迭代中。
list_images = ['image1.png','image2.png',..]
for img in list_images:
# here put your code
img_to_be_checked = cv2.imread(img)
# continue with your code in the while loop
要创建图像列表,您可以拍摄一些快照并使用名称存储它们或使用您的代码多次拍摄快照,但您必须在拍摄新快照之前更改桌面图像以查看任何差异。您可以使用时间戳定期拍摄快照,以便您有时间更改输入图像。最简单的方法是预先保存屏幕截图,然后像我在上面的代码中看到的那样阅读它们。
推荐阅读
- sas - 大家好。我需要填写下一个默认日期,如附件所示。所需的输出是最后一列。使用的语言是 SAS。谢谢
- java - Liquibase SQL 回滚语句不起作用
- c# - 如何下载 Block Blob (Base64) 文件并使用 Azure Blob 存储将其转换为 PNG?
- python - 检查输入内容
- vue.js - 确保元素保持在视图中至少一秒钟
- java - 当缓冲区到达其边界时,Java Nio ByteBuffer 截断 unicode 字符
- javascript - React 在渲染页面之前不会等待 Redux 状态更改完成
- docker - 无法从 Node.js 容器调用我的 Laravel API,但我可以从 Postman 调用它
- javascript - 如何从由 Javascript 而不是 HTML 生成的网页中解析数字?
- javascript - 仅在提交时运行 useEffect