Opencv模板匹配

文章目录

  • 1 理论
  • 2 测试图像
    • 2.1 单对象
    • 2.2 多对象
  • 3 单对象的模板匹配
  • 4 多对象的模板匹配

1 理论

  模板匹配是一种用于在目标图像中搜索给定模板位置的方法。对此,Opencv中带有函数cv.matchTemplate(),其将模板在目标图像上滑动,然后在模板图像下比较模板和输入图像的拼盘。返回对象为一个灰度图像,每个像素表示该像素的邻域与模板的匹配程度。
  令 W × H W \times H W×H表示目标图像的大小, w × h w \times h w×h表示模板大小,则输出图像的大小为 ( W − w + 1 ) × ( H − h + 1 ) (W - w + 1) \times (H - h + 1 ) (Ww+1)×(Hh+1)。之后,可以使用**cv.minMaxLoc()**查看最大最小值。

2 测试图像

2.1 单对象

  1)目标图像:

  2)模板
Opencv模板匹配_第1张图片

2.2 多对象

  1)目标图像:
Opencv模板匹配_第2张图片
  2)模板:

3 单对象的模板匹配

import cv2 as cv
import matplotlib.pyplot as plt
import warnings

warnings.filterwarnings("ignore")


def get_match_template(
        target_path: str,
        template_path: str,
        methods: list = None
):
    if methods is None:
        methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
                   'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']

    target = cv.imread(target_path, 0)
    target_copy = target.copy()
    template = cv.imread(template_path, 0)

    w, h = template.shape[::-1]
    for meth in methods:
        method = eval(meth)
        target = target_copy.copy()

        res = cv.matchTemplate(target, template, method)
        min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
        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(target, top_left, bottom_right, 255, 2)
        plt.subplot(121), plt.imshow(res, 'gray')
        plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
        plt.subplot(122), plt.imshow(target, 'gray')
        plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
        plt.suptitle(meth)
        plt.show()


def test_get_match_template(
):
    target_path = "haizeiwang.png"
    template_path = "moban.png"
    get_match_template(target_path, template_path)


if __name__ == '__main__':
    test_get_match_template()

  输出如下:
Opencv模板匹配_第3张图片

4 多对象的模板匹配

import cv2 as cv
import numpy as np
import warnings

warnings.filterwarnings("ignore")


def get_match_template(
        target_path: str,
        template_path: str,
        threshold: float = 0.65
):

    target = cv.imread(target_path)
    target_gray = cv.cvtColor(target, cv.COLOR_BGR2GRAY)
    template = cv.imread(template_path, 0)
    w, h = template.shape[::-1]
    res = cv.matchTemplate(target_gray, template, cv.TM_CCOEFF_NORMED)

    loc = np.where(res >= threshold)
    for pt in zip(*loc[::-1]):
        cv.rectangle(target, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
    cv.imshow("", target)
    cv.waitKey()


def test_get_match_template(
):
    target_path = "xiaoxiaole.png"
    template_path = "green.png"
    get_match_template(target_path, template_path)


if __name__ == '__main__':
    test_get_match_template()

  输出如下:


参考文献:
【1】Opencv中文文档。

你可能感兴趣的:(编程实战之Python,Opencv,模板匹配,FanSmale,因吉)