opencv-python learning (twelve): template matching

12. Template matching

Template matching: In layman's terms, it is to find a picture with a picture, and find its position in the picture through a part of the picture

Execute template matching, using three matching methods

  • cv.TM_SQDIFF_NORMED: Use the square difference between the two to match, the best matching value is 0;
  • cv.TM_CCORR_NORMED: Use the product of the two to match, the larger the value, the better the matching degree,
  • cv.TM_CCOEFF_NORMED: Match with the correlation coefficient of the two, 1 means perfect match, -1 means worst match

code show as below:

# 引入包
import cv2 as cv
import numpy as np

def template_image():
    # 读取模板图片
    tpl = cv.imread('./static/image/cut1.jpg')
    # 读取目标图片
    target = cv.imread('./static/image/windows.jpg')
    cv.imshow("model", tpl)
    cv.imshow("image", target)
    methods = [cv.TM_SQDIFF_NORMED, cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED]
    # 获得模板图片的高宽尺寸
    th, tw = tpl.shape[:2]
    for md in methods:
        print(md)

        # 执行模板匹配,采用的匹配方式有三种
        result = cv.matchTemplate(target, tpl, md)

        # 寻找矩阵(一维数组当做向量,用Mat定义)中的最大值和最小值的匹配结果及其位置
        min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

        # 对于cv2.TM_SQDIFF及cv2.TM_SQDIFF_NORMED方法min_val越趋近与0匹配度越好,匹配位置取min_loc
        # min_loc:矩形定点
        if md == cv.TM_SQDIFF_NORMED:
            tl = min_loc

        # 对于其他方法max_val越趋近于1匹配度越好,匹配位置取max_loc
        else:
            tl = max_loc

        # 矩形的宽高
        br = (tl[0]+tw, tl[1]+th)

        # 绘制矩形边框,将匹配区域标注出来
        # tl:矩形定点
        # br:矩形的宽高
        # (0,0,225):矩形的边框颜色;2:矩形边框宽度
        cv.rectangle(target, tl, br, (0, 0, 255), 2)

        # np.str(md)
        # 匹配值转换为字符串
        # 显示结果,并将匹配值显示在标题栏上
        cv.imshow("pipei"+np.str(md), target)

template_image()
cv.waitKey(0)
cv.destroyAllWindows()

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_33538887/article/details/118805736