基于灰度值平方差的图像匹配

    科技2022-07-10  140

    import numpy as np import math import cv2 # 读取目标图片 target = cv2.imread("Resources/target3.jpg") # 读取模板图片 template = cv2.imread("Resources/template2.jpg") # 将目标图片转换为灰度图片 target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY) # 将模板图片转换为灰度图片 template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) # 获取目标图片的大小 target_x, target_y = target.shape # 获取模板图片的大小 template_x, template_y = template.shape # 计算候选框的数量 candidate_x = target_x - template_x candidate_y = target_y - template_y # 进行灰度匹配并记录方差 SQUSum = np.zeros((candidate_x, candidate_y), np.int) # 记录每个候选框概率分布 # 循环每一个候选框 for i in range(candidate_x): # print(f'loop {i}') for j in range(candidate_y): # 1.计算候选框的概率分布 for m in range(template_x): for n in range(template_y): # 统计第i行第j列的候选框的每个灰度值的数量 SQUSum[i][j] += math.pow(int(target[i + m, j + n]) - int(template[m][n]), 2) bm = SQUSum.min() # 获取最小值 index = np.unravel_index(SQUSum.argmin(), SQUSum.shape) # 获取最小值索引 print("最小平方差", bm) print('最小平方差索引', index) cv2.rectangle(target, index, (index[0] + template_y, index[1] + template_x), (0, 255, 225), 2) cv2.imshow('Result', target) cv2.resizeWindow('Result', 200, 50) cv2.imshow('Template', template) cv2.resizeWindow('Template', 200, 50) cv2.waitKey()

     

    Processed: 0.018, SQL: 8