python 使用模版匹配
1.导入python及其他模块
import cv2
from matplotlib import pyplot as plt
2主程序
if __name__=="__main__":
src=r'D:\mypython\chengjiao\2.jpg'
srctempl=r'D:\mypython\chengjiao\T1.jpg'
imageMatch=ImageMatch(src,srctempl)
X,Y=ImageMatch.main(imageMatch)
print(X,Y)
input("任意键结束:")
# main()
pass
3.建立ImageMatch类
class ImageMatch:
def __init__(self,Src,Srctempl):
self.src=Src
self.srctempl=Srctempl
4.类中的主运行函数
def main(self):
# src=r'D:\mypython\chengjiao\2.jpg'
# srctempl=r'D:\mypython\chengjiao\T1.jpg'
result,imagebase,imagetempl=self.match(self.src, self.srctempl)
X,Y=self.GetPoint(result,imagebase,imagetempl)
return X,Y
6.使用matplotlib 来显示图像
def show(self,image, name):
# plt.subplot(121)
plt.title(name)
plt.imshow(image)
plt.axis('off')
plt.show()
7.获取匹配结果
def match(self,src,srctempl):
method=5#cv::TM_CCOEFF_NORMED = 5 标准相关匹配
imagebase=cv2.imread(src)
#self.show(imagebase ,"imagebase")
# imagetempl = imagebase[15:137,134:183].copy()
imagetempl=cv2.imread(srctempl)
#self.show(imagetempl ,"imagetempl")
print('imagetempl.shape:',imagetempl.shape)
shape=imagetempl.shape
result=cv2.matchTemplate(imagebase,imagetempl,method)
print('result.shape:',result.shape)
print('result.dtype:',result.dtype)
return result,imagebase,imagetempl
8.获取匹配结果
#计算中心点位置
def GetPoint(self,result,imagebase,imagetempl):
method=5
min_max = cv2.minMaxLoc(result)
if method == 0 or method == 1: #根据不同的模式最佳匹配位置取值方法不同
match_loc = min_max[2]
else:
match_loc = min_max[3]
right_bottom = (match_loc[0] + imagetempl.shape[1], match_loc[1] + imagetempl.shape[0])
print('result.min_max:',min_max,'method=',method)
# print('match_loc:',match_loc,type(match_loc))
# print('right_bottom',right_bottom,type(right_bottom))
#self.show(imagebase ,"imagebase ")
X=int(match_loc[0])+int((right_bottom[0]-match_loc[0])/2)
Y=int(match_loc[1])+int((right_bottom[1]-match_loc[1])/2)
print(X,Y)
if method==5 and float(min_max[1])< 0.5:
X=0
Y=0
#标注位置
img_disp = imagebase.copy()
cv2.rectangle(img_disp, match_loc,right_bottom, (0,255,0), 5, 8, 0 )
cv2.normalize( result, result, 0, 255, cv2.NORM_MINMAX, -1 )
cv2.circle(result, match_loc, 10, (255,0,0), 2 )
self.show(img_disp ,"img_disp ")
return X,Y
9.运行效果图: