原文地址:http://www.woshicver.com/FifthSection/4_12_%E6%A8%A1%E6%9D%BF%E5%8C%B9%E9%85%8D/
opencv中的模板匹配使用模板匹配的图像中查找对象;用于在较大图像中搜索和查找模板图像位置
相关函数:cv.matchTemplate():将模板图像滑动到输入图像上,然后在模板图像下比较模板和输入图像的拼图。如果输入图像的大小为(WxH),而模板图像的大小为(wxh),则输出图像的大小将为(W-w + 1,H-h + 1)。得到结果后,可以使用cv.minMaxLoc()函数查找最大/最小值在哪。将其作为矩形的左上角,并以(w,h)作为矩形的宽度和高度。
如果使用cv.TM_SQDIFF作为比较方法,则最小值提供最佳匹配。
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('C:\Users\Desktop\empire.jpeg',0)
img2 = img.copy()
template = cv.imread('C:\Users\Desktop\temp.jpeg',0)
w,h = template.shape[::-1]
#6种模板匹配的方法
methods = ['cv.TM_CCOEFF','cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR','cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
method = eval(meth)
#应用模板匹配
res = cv.matchTemplate(img,template,method)
min_val,max_val,min_loc,max_loc = cv.minMaxLoc(res)
#如果方法是TM_SQDIFF或者TM_SQDIFF_NORMED取最小值
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(img,top_left,bottom_right,255,2)
plt.subplot(121),plt.imshow(res,cmap = 'gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img,cmap = 'gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
备注:cv.TM_CCORR的匹配效果较差。
多对象的模板匹配当要搜索的对象多次出现时,cv.minMaxLoc()不会提供所有位置,需要阈值化处理。
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img_rgb = cv.imread('C:\Users\Desktop\empire.jpeg')
img_gray = cv.cvtColor(img_rgb,cv.COLOR_BGR2GRAY)
template = cv.imread('C:\Users\Desktop\temp.jpeg',0)
w,h = template.shape[::-1]
res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res>=threshold)
for pt in zip(*loc[::-1]):
cv.rectangle(img_rgb,pt,(pt[0]+w,pt[1]+h),(0,0,255),2)
cv.imshow('image',img_rgb)
cv.waitKey(0)
cv.destroyAllWindows()



