2

我尝试使用 opencv2 匹配模板。

这是我正在搜索的模板和屏幕: screen_template

这是我用来匹配模板的代码:

import cv2
import numpy as np
img_bgr = cv2.imread("screen.png")
img_gray = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2GRAY)
template = cv2.imread("red.png",0)
w,h = template.shape[::-1]

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.4
loc = np.where(res>=threshold)

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_bgr,pt,(pt[0]+w,pt[1]+h),(0,255,255),2)

cv2.imshow("detected",img_bgr)
cv2.waitKey(0)
cv2.imwrite('img_bgr.png',img_bgr)
cv2.imwrite('gray_image.png',img_gray)

当我使用 0.4 的阈值时,结果是: 结果

即使我使用的是红色典当模板,opencv2 也仅与 0.4 阈值的蓝色典当匹配。

4

0 回答 0