栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【千律】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)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980297.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号