模板匹配代码
import cv2
import matplotlib.pyplot as plt
# 加载主图像和模板图像
filepath = 'D:\\data\\8.jpeg'
template = cv2.imread(r"D:\data\tep_8.png")
# 打开图像
image = cv2.imread(file)
# 制作图像的副本
image_copy = image.copy()
# 将图像转换为灰度图像
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# 获取模板图像的宽度和高度
template_h, template_w = template.shape[:2]
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
# 匹配方法的真值
method = eval(meth)
# 使用归一化交叉相关方法执行模板匹配
result = cv2.matchTemplate(image_gray, template_gray, method) #cv2.TM_CCOEFF_NORMED
# 找到结果矩阵中最佳匹配的位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
print(meth, ':\n', min_val, max_val, min_loc, max_loc)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
# 在最佳匹配周围绘制矩形
bottom_right = (top_left[0] + template_w, top_left[1] + template_h)
image_copy = cv2.rectangle(image_copy, top_left, bottom_right, 255, 2)
plt.subplot(121), plt.imshow(result , cmap='gray')
plt.subplot(122), plt.imshow(image_copy, cmap='gray')
plt.savefig(f'./{meth}.png')
plt.show()