模板匹配
模板匹配是用来在一副大图中搜寻查找模版图像位置的方法。
cv2.matchTemplate() 输入为灰度化的大图(W, H)、模板图像(w,h)、匹配方法。用模板图像在输入图像(大图)上滑动,并在每一个位置对模板图像和与其对应的输入图像的子区域进行比较。返回(W-w+1, H-h+1)的浮点型的灰度图,灰度图中的灰度值表示此区域于模板的匹配程度,值越大越匹配。
匹配方法
cv2.minMaxLoc() 输入为矩阵[cv2.matchTemplate()的返回结果],返回值分别为矩阵中的最小值、最大值、最小值对应的位置点、最大值对应的位置点。
代码
import cv2
import numpy as np
from matplotlib import pyplot as plt
src = cv2.imread(r'F:\OPENCV\Opencv\animal.png', cv2.IMREAD_COLOR)
img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
img1 = img.copy()
template = cv2.imread(r'F:\OPENCV\Opencv\dog.png', cv2.IMREAD_GRAYSCALE)
h, w = template.shape[:]
# match methods
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:
img2 = img1.copy()
img3 = src.copy()
method = eval(meth)
res = cv2.matchTemplate(img2, template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# if method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img2, top_left, bottom_right, 255, 2)
cv2.rectangle(img3, top_left, bottom_right, (0, 0, 255), 2)
# show result
titles = ['Matching result', 'Detected Point', 'result']
images = [res, img2, img3[:, :, ::-1]]
plt.figure(figsize=(6, 3))
for i in range(len(images)):
plt.suptitle(meth)
plt.subplot(1, 3, i + 1)
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.savefig(r'F:\OPENCV\Opencv\{}.jpg'.format(meth))
plt.show()
结果显示
原始图像