Template Matching
理论
模板匹配是一种在较大的图像中搜索和查找模板图像位置的方法。OpenCV带有一个函数cv2.matchTemplate()
用于此目的.它只是简单地将模板图像放在输入图像上(就像在2D卷积中那样),并在模板图像下对输入图像的模板和补丁进行比较,在OpenCV中实现了几种比较方法,它返回一个灰度图像,每个像素表示该像素区域与模板的匹配程度.
如果输入图像的大小(W x H)且模板图像的大小(w x h),则输出图像的大小为(W-w + 1,H-h + 1).获得结果后,可以使用cv.minMaxLoc()
函数查找最大/最小值的位置。将其作为矩形的左上角,并将(w,h)作为矩形的宽度和高度.
OpenCV中的模板匹配
import cv2
import numpy as np
from matplotlib import pyplot as pltimg = cv2.imread('img.jpg',0)
img2 = img.copy()
template = cv2.imread('img_roi.png',0)
w, h = template.shape[::-1]# All the 6 methods for comparison in a list
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:img = img2.copy()method = eval(meth)# Apply template Matchingres = cv2.matchTemplate(img,template,method)min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimumif method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:top_left = min_locelse:top_left = max_locbottom_right = (top_left[0] + w, top_left[1] + h)cv2.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.minMaxLoc()
将不会提供所有的位置.在这种情况下,我们将使用阈值.
import cv2
import numpy as np
from matplotlib import pyplot as pltimg_rgb = cv2.imread('img5.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('img_roi1.png',0)
w, h = template.shape[::-1]res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)cv2.imshow('res',img_rgb)