最简单的模式匹配方法,但是条件必须良好才高效。 模板匹配具有自身的局限性,主要表现在它只能进行平行移动,若原图像中的匹配目标发生旋转或大小变化,该算法无效。
关于参数 method:
CV_TM_SQDIFF 平方差匹配法:该方法采用平方差来进行匹配;最好的匹配值为0;匹配越差,匹配值越大。
CV_TM_CCORR 相关匹配法:该方法采用乘法操作;数值越大表明匹配程度越好。
CV_TM_CCOEFF 相关系数匹配法:1表示完美的匹配;-1表示最差的匹配。
CV_TM_SQDIFF_NORMED 归一化平方差匹配法
CV_TM_CCORR_NORMED 归一化相关匹配法
CV_TM_CCOEFF_NORMED 归一化相关系数匹配法
归一化
def template_match(target, tpl):
# 归一化(0~1 之间):平方差匹配,相关匹配,相关系数匹配
methods = [cv.TM_SQDIFF_NORMED, cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED]
th, tw = tpl.shape[:2]
for md in methods:
print(md)
result = cv.matchTemplate(target, tpl, md)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
# tl:矩形左上角那个点
if md == cv.TM_SQDIFF_NORMED:
tl = min_loc
else:
tl = max_loc
br = (tl[0]+tw, tl[1]+th) # 矩形右下角
'''
cv.rectangle:
img – Image.
pt1 – Vertex of the rectangle.
pt2 – Vertex of the recangle opposite to pt1 .
r – Alternative specification of the drawn rectangle.
color – Rectangle color or brightness (grayscale image).
thickness – Thickness of lines that make up the rectangle.
'''
cv.rectangle(target, tl, br, (0, 0, 255), 2)
cv.imshow("match-"+np.str(md), target)
cv.imshow("match-"+np.str(md), result)