目标
在本章中,您将学习
理论
模板匹配是一种在大图像中搜索和查找模板图像位置的方法。 OpenCV为此目的提供了一个函数cv.matchTemplate()。 它只是将模板图像在输入图像上滑动(如在2D卷积中),并比较模板图像下的模板和输入图像的patch。 OpenCV中实现了几种比较方法。(您可以查看文档以获取更多详细信息)。 它返回一个灰度图像,其中每个像素表示该像素的邻域与模板的匹配程度。
如果输入图像的大小为(WxH),模板图像的大小为(wxh),则输出图像的大小将为(W-w + 1,H-h + 1)。 获得结果后,可以使用cv.minMaxLoc()函数找到最大/最小值的位置。 将其作为矩形的左上角,并将(w,h)作为矩形的宽度和高度。 该矩形是您的模板区域。
- 注意
- 如果您使用cv.TM_SQDIFF作为比较方法,则最小值给出最佳匹配。
OpenCV中的模板匹配
在这里,作为一个例子,我们将在他的照片中搜索梅西的脸。 所以我创建了如下模板
image
我们将尝试所有比较方法,以便我们可以看到它们的结果如何
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img =
cv.imread(
'messi5.jpg', cv.IMREAD_GRAYSCALE)
assert img is not None, "file could not be read, check with os.path.exists()"
img2 = img.copy()
template =
cv.imread(
'template.jpg', cv.IMREAD_GRAYSCALE)
assert template is not None, "file could not be read, check with os.path.exists()"
w, h = template.shape[::-1]
methods = ['TM_CCOEFF', 'TM_CCOEFF_NORMED', 'TM_CCORR',
'TM_CCORR_NORMED', 'TM_SQDIFF', 'TM_SQDIFF_NORMED']
for meth in methods
img = img2.copy()
method = getattr(cv, meth)
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)
plt.subplot(121),plt.imshow(res,cmap = 'gray')
plt.title('匹配结果'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img,cmap = 'gray')
plt.title('检测到的点'), plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
void minMaxLoc(InputArray src, double *minVal, double *maxVal=0, Point *minLoc=0, Point *maxLoc=0, InputArray mask=noArray())
查找数组中的全局最小值和最大值。
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
从文件加载图像。
void rectangle(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
绘制一个简单、粗或填充的矩形。
void matchTemplate(InputArray image, InputArray templ, OutputArray result, int method, InputArray mask=noArray())
将模板与重叠图像区域进行比较。
查看下面的结果
image
image
image
image
image
image
您可以看到使用cv.TM_CCORR的结果不如我们预期的好。
多对象的模板匹配
在上一节中,我们搜索了图像中梅西的脸,它在图像中只出现一次。 假设您正在搜索一个具有多个匹配项的对象,cv.minMaxLoc()不会给您所有位置。 在这种情况下,我们将使用阈值。 因此,在本示例中,我们将使用著名游戏马里奥的屏幕截图,我们将在其中找到金币。
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
assert img_rgb is not None, "file could not be read, check with os.path.exists()"
template =
cv.imread(
'mario_coin.png', cv.IMREAD_GRAYSCALE)
assert template is not None, "file could not be read, check with os.path.exists()"
w, h = template.shape[::-1]
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_EXPORTS_W bool imwrite(const String &filename, InputArray img, const std::vector< int > ¶ms=std::vector< int >())
将图像保存到指定文件。
void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0, AlgorithmHint hint=cv::ALGO_HINT_DEFAULT)
将图像从一个颜色空间转换为另一个颜色空间。
结果
image