问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

OpenCV模板匹配教程:理论与实践

创作时间:
作者:
@小白创作中心

OpenCV模板匹配教程:理论与实践

引用
1
来源
1.
https://docs.opencv.org/4.x/d4/dc6/tutorial_py_template_matching.html

目标

本章将学习如何使用模板匹配在图像中查找对象,具体包括:

  • 使用模板匹配在图像中查找对象
  • 了解cv.matchTemplate()和cv.minMaxLoc()函数的使用

理论

模板匹配是一种在大图像中搜索和定位模板图像位置的方法。OpenCV提供了cv.matchTemplate()函数来实现这一功能。该函数通过在输入图像上滑动模板图像(类似于2D卷积),比较模板图像与输入图像中模板大小的区域。OpenCV实现了多种比较方法(更多细节请参考官方文档)。该函数返回一个灰度图像,其中每个像素表示其邻域与模板的匹配程度。

如果输入图像大小为(WxH),模板图像大小为(wxh),则输出图像大小为(W-w+1, H-h+1)。获取结果后,可以使用cv.minMaxLoc()函数找到最大/最小值的位置。将该位置作为矩形的左上角,将(w,h)作为矩形的宽度和高度,该矩形即为模板所在区域。

注意:如果使用cv.TM_SQDIFF作为比较方法,最小值表示最佳匹配。

OpenCV中的模板匹配

以梅西的照片为例,我们将搜索梅西的脸部。为此,我们创建了一个模板图像:

我们将尝试所有比较方法,以便了解它们的结果:

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]

# 所有6种比较方法的列表
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)
    
    # 应用模板匹配
    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_CCOEFF

  • cv.TM_CCOEFF_NORMED

  • cv.TM_CCORR

  • cv.TM_CCORR_NORMED

  • cv.TM_SQDIFF

  • cv.TM_SQDIFF_NORMED

可以看出,使用cv.TM_CCORR的结果并不理想。

多个对象的模板匹配

在上一节中,我们在图像中搜索了梅西的脸部,这在图像中只出现一次。如果要搜索在图像中多次出现的对象,cv.minMaxLoc()将无法提供所有位置。在这种情况下,我们将使用阈值处理。因此,在这个例子中,我们将使用著名的马里奥游戏截图,并查找其中的硬币。

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

img_rgb = cv.imread('mario.png')
assert img_rgb is not None, "file could not be read, check with os.path.exists()"
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
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]

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)

结果如下:

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号