python - 模板匹配使用 opencv 的屏幕截图
问题描述
我想要实现的是实时捕获我的屏幕并让它检测框架内何时显示某个图像。到目前为止,我想出的是:
屏幕截图:
last_time = time.time()
while(True):
screen = np.array(ImageGrab.grab(bbox=(0,40, 800, 640)))
print('Loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
cv2.imshow('window', cv2.cvtColor(screen, cv2.COLOR_BGR2RGB))
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
模板匹配:
import cv2
import numpy as np
img_rgb = cv2.imread('frame.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('template.png',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2)
cv2.imshow('Detected',img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()
我让他们两个单独工作,但无法将它们融合在一起。我主要努力的是 imread() 当前帧,因为它作为 nparray 从捕获中返回,而 cv2.imread() 需要图片文件(png.、jpg.等)
解决方案
while(True)
在循环之前加载模板图像;- 在循环内部,确保
screen
从 RGB 转换为 GREY; - 然后,执行这3行模板匹配代码;
- 最后,要使用矩形显示输出,请将它们绘制在 上
screen
,而不是在其灰度对应物上。
推荐阅读
- python - 如何格式化 JSON 对象以通过 python 中的标头发送它?
- azure - 无法获取 Runbook 测试(在门户中)以请求输入参数
- javascript - 以编程方式延迟 Mocha 测试
- c# - 为什么这段代码这么快就耗尽了连接池?
- reactjs - 使用管道在 Heroku 审查应用程序中自动设置环境变量
- audiokit - 如何运行示例:没有这样的模块 AudioKit
- azure - 使用用户委托 SAS 创建使用用户委托密钥获取 blob 内容
- python - Flask SQLAlchemy:具有多个父级的子表?
- swift - UTC 时间的重复本地通知
- c - While循环内的优先级