【千律】OpenCV基础:基于梯度的模板匹配

环境:Python3.8 和 OpenCV

内容:基于梯度的模板匹配


主要关注边缘信息,能够较好的识别不同颜色的目标
实现步骤:
1.给定原图像I和模板T
2.指定差异度(相似度)评分标准
   截取与模板大小相同的原图像区域P,与模板计算评分
   1) 计算图片P上各点的x和y方向的梯度Px和Py
   2) 计算图片T上各点的x和y方向的梯度Tx和Ty
   3) 计算对应点的点乘结果并标准化,求和
3.从左向右,从上到下,寻找最佳匹配。
注:如果恰好完美匹配,则评分为1,若P和T完全无关,则评分为0 

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


# 封装图片显示函数
def image_show(image):
    if image.ndim == 2:
        plt.imshow(image, cmap='gray')
    else:
        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
        plt.imshow(image)
    plt.show()


if __name__ == '__main__':

    # 读取灰度图
    img_lenna = cv.imread('lenna.png', 0)

    # 截取感兴趣区域
    img_part = img_lenna[200: 300, 200: 300]

    # 获取模板图片的长和宽
    height, width = img_part.shape

    # 获取原图像的梯度
    img_gradx = cv.Sobel(img_lenna, cv.CV_64F, 1, 0)
    img_grady = cv.Sobel(img_lenna, cv.CV_64F, 0, 1)

    # 获取模板图像的梯度
    img_partx = cv.Sobel(img_part, cv.CV_64F, 1, 0)
    img_party = cv.Sobel(img_part, cv.CV_64F, 0, 1)

    # 循环计算评价值
    score = np.zeros((img_lenna.shape[0] - height, img_lenna.shape[1] - width))
    for i in range(img_lenna.shape[0] - height):
        for j in range(img_lenna.shape[1] - width):
            img_matchx = img_gradx[i: i + height, j: j + width]
            img_matchy = img_grady[i: i + height, j: j + width]

            socre1 = (img_matchx * img_partx) + (img_matchy * img_party)
            socre2 = np.sqrt(img_matchx ** 2 + img_matchy ** 2) * np.sqrt(img_partx ** 2 + img_party ** 2)

            score[i, j] = (socre1 / (socre2 + 1e-9)).mean()

    # 绘制热力图
    plt.imshow(score.clip(0, 0.5), cmap='jet')
    plt.show()

    # 设定阈值
    threshold = 0.6

    # 循环选择区域
    img_x, img_y = np.where(score > threshold)

    for (x, y) in zip(img_x, img_y):
        img_lenna = cv.rectangle(img_lenna, (x, y), (x + height, y + width), (255, 255, 255), 1)

    # 显示结果
    image_show(img_lenna)

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿飞_Y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值