Opencv Python 简明教程
OpenCV Python - Template Matching
模板匹配技术用于检测图像中与样本或模板图像匹配的一个或多个区域。
The technique of template matching is used to detect one or more areas in an image that matches with a sample or template image.
Cv.matchTemplate() 函数在 OpenCV 中定义用作此目的,对该函数的命令如下所示:
Cv.matchTemplate() function in OpenCV is defined for the purpose and the command for the same is as follows:
cv.matchTemplate(image, templ, method)
其中 image 为输入图像,其中要查找 templ(模板)模式。method 参数采用以下值之一 −
Where image is the input image in which the templ (template) pattern is to be located. The method parameter takes one of the following values −
-
cv.TM_CCOEFF,
-
cv.TM_CCOEFF_NORMED, cv.TM_CCORR,
-
cv.TM_CCORR_NORMED,
-
cv.TM_SQDIFF,
-
cv.TM_SQDIFF_NORMED
此方法使模板图像在输入图像上滑动。这与卷积的过程相似,并将输入图像下的模板和补丁与模板图像进行比较。
This method slides the template image over the input image. This is a similar process to convolution and compares the template and patch of input image under the template image.
它返回一个灰度图像,其中每个像素都表示它与模板的匹配程度。如果输入图像大小为 (WxH),并且模板图像大小为 (wxh),则输出图像的大小将为 (W-w+1, H-h+1)。因此,该矩形是模板的区域。
It returns a grayscale image, whose each pixel denotes how much it matches with the template. If the input image is of size (WxH) and template image is of size (wxh), the output image will have a size of (W-w+1, H-h+1). Hence, that rectangle is your region of template.
Example
在下面的示例中,将印度板球队队员 Virat Kohli 的脸部图像用作模板,与另一张描绘他和另一位印度板球队队员 M.S.Dhoni 合影的图像进行匹配。
In an example below, an image having Indian cricketer Virat Kohli’s face is used as a template to be matched with another image which depicts his photograph with another Indian cricketer M.S.Dhoni.
以下程序使用 80% 的阈值并围绕匹配的脸部绘制一个矩形 −
Following program uses a threshold value of 80% and draws a rectangle around the matching face −
import cv2
import numpy as np
img = cv2.imread('Dhoni-and-Virat.jpg',1)
cv2.imshow('Original',img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread('virat.jpg',0)
cv2.imshow('Template',template)
w,h = template.shape[0], template.shape[1]
matched = cv2.matchTemplate(gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( matched >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2)
cv2.imshow('Matched with Template',img)