环境: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)