首页 > 解决方案 > 模板匹配使用 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.等)

标签: pythonopencv

解决方案


  • while(True)在循环之前加载模板图像;
  • 在循环内部,确保screen从 RGB 转换为 GREY;
  • 然后,执行这3行模板匹配代码;
  • 最后,要使用矩形显示输出,请将它们绘制在 上screen,而不是在其灰度对应物上。

推荐阅读