笔记和用法都在代码注释中:
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# 原图像大小为: AxB
# 模板大小图像: axb
# 那么:输出矩阵的大小: (A-a+1)x(B-b+1)
# TM_SQDIFF:计算平方不同,计算出来的值越小,越相关
# TM_CCORR:计算相关性,计算出来的值越大,越相关
# TM_CCOEFF:计算相关系数,计算出来的值越大,越相关
# 最好用下面的这三种!!!!
# TM_SQDIFF_NORMED:计算归一化平方不同,计算出来的值越接近0,越相关
# TM_CCORR_NORMED:计算归—化相关性,计算出来的值越接近1,越相关
# TM_CCOEFF_NORMED:计算归一化相关系数,计算出来的值越接近1,越相关
# ------------------------------------------图像匹配:
# img = cv.imread('666.jpg')
# img = cv.resize(img,(500,500)) #原图
# template = cv.imread('template.jpg') #模板图
# print(img.shape)
# print(template.shape) #大小不一样!!!
#
# h,w = template.shape[:2]
#
# methods = ['cv.TM_SQDIFF',
# 'cv.TM_CCORR',
# 'cv.TM_CCOEFF',
# 'cv.TM_SQDIFF_NORMED',
# 'cv.TM_CCORR_NORMED',
# 'cv.TM_CCOEFF_NORMED']
#
# for meth in methods:
# img2 =img.copy()
#
# #匹配方法的真值:
# method = eval(meth)
# print(method)
# res = cv.matchTemplate(img,template,method)
# min_val,max_val,min_loc,max_loc = cv.minMaxLoc(res)
#
# if method in [cv.TM_SQDIFF,cv.TM_SQDIFF_NORMED]:
# top_left = min_loc
# else:
# top_left = max_loc
# bottom_right = (top_left[0] + w, top_left[1] + h)
#
# #画矩形:
# cv.rectangle(img2,top_left,bottom_right,255,2)
#
# plt.subplot(121),plt.imshow(res,cmap='gray')
# plt.xticks([]),plt.yticks([]) #隐藏坐标轴
# plt.subplot(121),plt.imshow(img2,cmap='gray')
# plt.subplot(meth)
# plt.show()