python-opencv Tutorials 一码人翻译(28)图像处理---- --模板匹配

目标

在这一章中,你将学习

使用模板匹配来查找图像中的对象

您将看到这些功能:cv.matchTemplate()、cv.minMaxLoc()

理论

模板匹配是一种在较大的图像中搜索和查找模板图像位置的方法。OpenCV有一个函数cv.matchTemplate()来实现这个目的。它只是将模板图像滑过输入图像(就像在2D卷积中一样),并比较模板图像下的输入图像的模板和补丁。在OpenCV中实现了几种比较方法。(你可以查看更多的详细信息)。它返回一个灰度图像,其中每个像素表示该像素的邻居与模板匹配的程度。

如果输入图像大小(WxH)和模板图像大小(WxH),输出图像将有一个大小(W-w+1、H-h+1)的大小。一旦您得到了结果,您就可以使用cvminmaxloc()函数来找到最大值/最小值的位置。将它作为矩形的左上角,并将(w,h)作为矩形的宽度和高度。这个矩形是你的模板区域。

请注意

如果你使用的是cv。tmsqdiff作为比较方法,最小值提供了最好的匹配。

OpenCV的模板匹配

在这里,作为一个例子,我们将在他的照片中寻找梅西的脸。所以我创建了一个模板如下:

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

img = cv.imread('lenna.jpg',0)
img2 = img.copy()
template = cv.imread('lennatou.jpg',0)
w, h = template.shape[::-1]

# All the 6 methods for comparison in a list
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)

    # Apply template Matching
    res = cv.matchTemplate(img,template,method)
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)

    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    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()

找连连看中的所有橘子

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

img_rgb = cv.imread('llk.jpg')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('llkjz.jpg',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.imwrite('res.png',img_rgb)

 

猜你喜欢

转载自blog.csdn.net/qq_41905045/article/details/81707019