使用python对比SSD和NCC的图像模板匹配

一、概况

        在图像识别领域,SSD(Single Shot MultiBox Detector)和NCC(Normalized Cross-Correlation)是两种具有不同特点和应用场景的算法。

        SSD是一种基于深度学习的目标检测算法,它能够在单次前向传递过程中同时进行目标的分类和定位,无需额外的区域提议步骤,从而实现了实时、高效的目标检测。SSD算法使用了多尺度的特征图来检测不同大小的物体,并在每个特征图上定义了一系列的先验框(也称为默认框或Anchor box),用于预测物体的位置和类别。

        NCC算法是一种用于度量两个序列或图像相似程度的方法,全称为归一化互相关算法。它的核心优点在于标准化特性、对光照变化具有鲁棒性、以及简单易执行。NCC算法通过计算两个序列或图像之间的标准化交叉相关度,来确定它们之间的相似程度。

二、核心代码

SSD计算

for y in range(target_h - template_h + 1):
    for x in range(target_w - template_w + 1):
        # 提取目标图像中当前位置的子区域
        patch = target_imgS2[y:y + template_h, x:x + template_w]
        ssd = np.sum((patch - template_img2) ** 2)   # 计算SSD
        resultS[y, x] = ssd # 存储SSD值
print("SSD calculation completed.")

# 找到SSD最小的位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(resultS)
top_left = min_loc
bottom_right = (top_left[0] + template_h, top_left[1] + template_w)
# 在目标图像上绘制SSD匹配矩形框
cv2.rectangle(target_imgS, top_left, bottom_right, (0, 255, 0), 2)  #绿框
print("SSD completed.")

NCC计算

for y in range(target_h - template_h + 1):
    for x in range(target_w - template_w + 1):
        # 提取目标图像中当前位置的子区域
        patch = target_imgN2[y:y + template_h, x:x + template_w]
        # 计算模板图像和目标图像子区域的均值
        mean_template = np.mean(template_img2)
        mean_patch = np.mean(patch)
        # 计算模板图像和目标图像子区域的标准差(用于归一化)
        std_template = np.std(template_img2)
        std_patch = np.std(patch)
        eps = 1e-10 # 避免除以零的情况
        
        # 计算归一化互相关系数
        numerator = np.sum((patch - mean_patch) * (template_img2 - mean_template))
        denominator = std_patch * std_template * (target_h * target_w - 1)  # 减1是因为我们计算的是样本标准差,但这里为了简化直接用了总体大小
        ncc = numerator / (denominator + eps)  # 加eps防止除以零
        
        resultN[y, x] = ncc # 存储NCC值
print("NCC calculation completed.")

# 找到NCC最大的位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(resultN)
top_left = max_loc
bottom_right = (top_left[0] + template_h, top_left[1] + template_w)

# 在目标图像上绘制NCC匹配矩形框
cv2.rectangle(target_imgN, top_left, bottom_right, (0), 2)  # 黑框
print("NCC completed.")

三、效果

四、全部代码

import cv2
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 加载目标图像和模板图像
target_img = cv2.imread('a1.jpg')    #请更换为您的目标图片名称(同文件夹下)
template_img = cv2.imread('a2.jpg')    #请更换为您的模板图片名称(同文件夹下)

# 检查图像是否成功加载
if target_img is None or template_img is None:
    print("Error loading images!")
    exit()
target_imgS = target_img.copy()
target_imgN = target_img.copy()
target_imgS2 = cv2.cvtColor(target_imgS, cv2.COLOR_BGR2GRAY)
target_imgN2 = cv2.cvtColor(target_imgN, cv2.COLOR_BGR2GRAY)
template_img2 = cv2.cvtColor(template_img, cv2.COLOR_BGR2GRAY)

# 获取目标图像和模板图像的宽高
target_h, target_w = target_imgS2.shape
template_h, template_w = template_img2.shape

# 创建两个结果数组来分别存储SSD值和NCC值
resultS = np.full((target_h - template_h + 1, target_w - template_w + 1), np.inf)
resultN = np.zeros((target_h - template_h + 1, target_w - template_w + 1), dtype=np.float32)
print("Initialization completed.")

# 计算SSD
for y in range(target_h - template_h + 1):
    for x in range(target_w - template_w + 1):
        # 提取目标图像中当前位置的子区域
        patch = target_imgS2[y:y + template_h, x:x + template_w]
        ssd = np.sum((patch - template_img2) ** 2)   # 计算SSD
        resultS[y, x] = ssd # 存储SSD值
print("SSD calculation completed.")

# 找到SSD最小的位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(resultS)
top_left = min_loc
bottom_right = (top_left[0] + template_h, top_left[1] + template_w)
# 在目标图像上绘制SSD匹配矩形框
cv2.rectangle(target_imgS, top_left, bottom_right, (0, 255, 0), 2)  #绿框
print("SSD completed.")

# 计算NCC
for y in range(target_h - template_h + 1):
    for x in range(target_w - template_w + 1):
        # 提取目标图像中当前位置的子区域
        patch = target_imgN2[y:y + template_h, x:x + template_w]
        # 计算模板图像和目标图像子区域的均值
        mean_template = np.mean(template_img2)
        mean_patch = np.mean(patch)
        # 计算模板图像和目标图像子区域的标准差(用于归一化)
        std_template = np.std(template_img2)
        std_patch = np.std(patch)
        eps = 1e-10 # 避免除以零的情况
        
        # 计算归一化互相关系数
        numerator = np.sum((patch - mean_patch) * (template_img2 - mean_template))
        denominator = std_patch * std_template * (target_h * target_w - 1)  # 减1是因为我们计算的是样本标准差,但这里为了简化直接用了总体大小
        ncc = numerator / (denominator + eps)  # 加eps防止除以零
        
        resultN[y, x] = ncc # 存储NCC值
print("NCC calculation completed.")

# 找到NCC最大的位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(resultN)
top_left = max_loc
bottom_right = (top_left[0] + template_h, top_left[1] + template_w)

# 在目标图像上绘制NCC匹配矩形框
cv2.rectangle(target_imgN, top_left, bottom_right, (0), 2)  # 黑框
print("NCC completed.")

# 显示结果图像
plt.subplot(2, 2, 1)
plt.title('目标图像')
plt.imshow(target_img)
plt.axis('off')

plt.subplot(2, 2, 2)
plt.title('模板图像')
plt.imshow(template_img)
plt.axis('off')

plt.subplot(2, 2, 3)
plt.title('SSD匹配图像')
plt.imshow(target_imgS)
plt.axis('off')

plt.subplot(2, 2, 4)
plt.title('NCC匹配图像')
plt.imshow(target_imgN)
plt.axis('off')

plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值