实现代码:
import cv2
import numpy as np
def template_demo(tpl,target):
methods=[cv2.TM_SQDIFF_NORMED,cv2.TM_CCORR_NORMED,cv2.TM_CCOEFF_NORMED]
th,tw=tpl.shape[:2]
for md in methods:
start_time=cv2.getTickCount()
# 匹配结果
result=cv2.matchTemplate(target,tpl,md)
# 对匹配结果进行分析
min_val,max_val,min_loc,max_loc=cv2.minMaxLoc(result)
if md==cv2.TM_SQDIFF_NORMED:
tl=min_loc
else:
tl=max_loc
# 矩形右下角的点的坐标
br=(tl[0]+tw,tl[1]+th)
# 画矩形
cv2.rectangle(target,tl,br,(0,0,255),2)
cv2.imshow("match-"+str(md),target)
print("method: %d, time: %d ms"%(md,(cv2.getTickCount()-start_time)*1000/cv2.getTickFrequency()))
tpl=cv2.imread("./template.png")
print(tpl.shape)
target=cv2.imread("./target.png")
print(target.shape)
cv2.namedWindow("template image",cv2.WINDOW_NORMAL)
cv2.imshow("template image",tpl)
cv2.namedWindow("target image",cv2.WINDOW_NORMAL)
cv2.imshow("target image",target)
template_demo(tpl,target)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果: