实现代码:
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()
运行结果:文章来源:https://www.toymoban.com/news/detail-501791.html
文章来源地址https://www.toymoban.com/news/detail-501791.html
到了这里,关于模板匹配Template Matching的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!