OpenCV 入门:cv2.matchTemplate() 单模板匹配和多模板匹配

单模板匹配和多模板匹配

单模板匹配

输入:底图 image(博客首页的图),模板图片 templ 如下:

# _*_coding:utf-8_*_
 
import cv2 as cv2
 
# 单个模板匹配
def one_match(image, templ):
    img = cv2.imread(image)
    template = cv2.imread(templ)
    h, w = template.shape[:2]
    # 匹配模板
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # 计算矩形左边
    top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    # 画矩形
    cv2.rectangle(img, top_left, bottom_right, (0, 0, 255), 5)
    # 展示结果
    cv2.imshow('img_rgb', img)
    cv2.waitKey(0)
    pass
 
if __name__ == '__main__':
    print("———————————————————— start ————————————————————\n")
    # 图片路径自己设置,下面是我本地的路径,记得替换!!!
    one_match('../img/test/guimie_03.jpg', '../img/test/guimie_04.jpg')
    print("———————————————————— end ————————————————————\n")


多模板匹配

上面的单模板匹配使用了函数 cv2.minMaxLoc() 输出结果,特点是:只会输出一个匹配系数最大值,无法给出所有匹配区域的位置信息。但是,有些情况下,要搜索的模板图像很有可能在输入图像内出现了多次,这时就需要找出多个匹配结果。

多模板匹配引入了“匹配系数” - threshold,利用数学计算函数 numpy 删选出所有大于 threshold 的图形。

输入: 模板图片 templ → 底图 image:

# _*_coding:utf-8_*_

 
import cv2 as cv2
import numpy as np
 
# 多个模板匹配
def more_match(image, templ):
    img = cv2.imread(image)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(templ, 0)
    h, w = template.shape[:2]
 
    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    # 取匹配程度大于%90的坐标
    threshold = 0.9
    # np.where返回的坐标值(x,y)是(h,w),注意h,w的顺序
    loc = np.where(res >= threshold)
    for pt in zip(*loc[::-1]):
        bottom_right = (pt[0] + w, pt[1] + h)
        cv2.rectangle(img, pt, bottom_right, (255, 0, 0), 1)
        print(pt, bottom_right)
    cv2.imshow('img_rgb', img)
    cv2.waitKey(0)
    pass
 
if __name__ == '__main__':
    print("———————————————————— start ————————————————————\n")
    # 图片路径自己设置,下面是我本地的路径,记得替换!!!
    more_match('../img/test/zhipai_03.jpg', '../img/test/zhipai_04.jpg')
    print("———————————————————— end ————————————————————\n")


————————————————
版权声明:本文为CSDN博主「Java Punk」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44259720/article/details/127263412

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值