OpenCV 角点检测和特征匹配:使用 Harris 角点检测和归一化互相关进行图像匹配
import cv2
import numpy as np
from matplotlib import pyplot as plt
img1 = cv2.imread('1.png')
img2 = cv2.imread('4.png')
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray1 = np.float32(gray1)
dst1 = cv2.cornerHarris(gray1, 2, 3, 0.04)
img1[dst1 > 0.01 * dst1.max()] = [0, 0, 255]
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
gray2 = np.float32(gray2)
dst2 = cv2.cornerHarris(gray2, 2, 23, 0.04)
img2[dst2 > 0.01 * dst2.max()] = [0, 0, 255]
# 从一幅 Harris 响应图像中返回角点,min_dist 为分割角点和图像边界的最少像素数目
def get_harris_points(harrisim, min_dist=10, threshold=0.1):
# 寻找高于阈值的候选角点
corner_threshold = harrisim.max() * threshold
harrisim_t = (harrisim > corner_threshold) * 1
# 得到候选点的坐标
coords = np.array(harrisim_t.nonzero()).T
# 以及它们的 Harris 响应值
candidate_values = [harrisim[c[0], c[1]] for c in coords]
# 对候选点按照 Harris 响应值进行排序
index = np.argsort(candidate_values)[::-1]
# 将可行点的位置保存到数组中
allowed_locations = np.zeros(harrisim.shape)
allowed_locations[min_dist:-min_dist, min_dist:-min_dist] = 1
# 按照 min_distance 原则,选择最佳 Harris 点
filtered_coords = []
for i in index:
if allowed_locations[coords[i, 0], coords[i, 1]] == 1:
filtered_coords.append(coords[i])
allowed_locations[(coords[i, 0] - min_dist):(coords[i, 0] + min_dist),
(coords[i, 1] - min_dist):(coords[i, 1] + min_dist)] = 0
return filtered_coords
# 对于每个返回的点,返回点周围 2*wid+1 个像素的值(假设选取点的 min_distance > wid)
def get_descriptors(image, filtered_coords, wid=5):
desc = []
for coords in filtered_coords:
patch = image[coords[0] - wid:coords[0] + wid + 1,
coords[1] - wid:coords[1] + wid + 1].flatten()
desc.append(patch)
return desc
# 对于第一幅图像中的每个角点描述子,使用归一化互相关,选取它在第二幅图像中的匹配角点
def match(desc1, desc2, threshold=0.5):
n = len(desc1[0])
# 点对的距离
d = -np.ones((len(desc1), len(desc2)))
for i in range(len(desc1)):
for j in range(len(desc2)):
d1 = (desc1[i] - np.mean(desc1[i])) / np.std(desc1[i])
d2 = (desc2[j] - np.mean(desc2[j])) / np.std(desc2[j])
ncc_value = sum(d1 * d2) / (n - 1)
if ncc_value > threshold:
d[i, j] = ncc_value
ndx = np.argsort(-d) # 从大 0 到小排序
matchscores = ndx[:, 0] # 最大一个数的位置坐标
return matchscores
# 两边对称版本的 match()
def match_twosided(desc1, desc2, threshold=0.5):
matches_12 = match(desc1, desc2, threshold)
matches_21 = match(desc2, desc1, threshold)
ndx_12 = np.where(matches_12 >= 0)[0]
# 去除非对称的匹配
for n in ndx_12:
if matches_21[matches_12[n]] != n:
matches_12[n] = -1
return matches_12
# 返回将两幅图像并排拼接成的一幅新图像
def appendimages(im1, im2):
row1 = im1.shape[0]
row2 = im2.shape[0]
if row1 < row2:
im1 = np.concatenate((im1, np.zeros((row2 - row1, im1.shape[1], im1.shape[2]))), axis=0)
elif row1 > row2:
im2 = np.concatenate((im2, np.zeros((row1 - row2, im2.shape[1], im2.shape[2]))), axis=0)
return np.concatenate((im1, im2), axis=1)
# 显示一幅带有连接匹配之间连线的图片
# 输入:im1,im2(数组图像),locs1,locs2(特征位置),matchscores(match 的输出),
def plot_matches(im1, im2, locs1, locs2, matchscores):
im3 = appendimages(im1, im2)
plt.imshow(im3)
cols1 = im1.shape[1]
for i, m in enumerate(matchscores):
if m > 0:
plt.plot([locs1[i][1], locs2[m][1] + cols1], [locs1[i][0], locs2[m][0]], 'c')
plt.axis('off')
plt.show()
#cv2.imshow('corners-1',img1)
#cv2.imshow('corners-2',img2)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
wid = 9 # 比较像素点数目
filtered_coords1 = get_harris_points(dst1, wid + 1, 0.1) # 图 1 大于阈值的坐标
filtered_coords2 = get_harris_points(dst2, wid + 1, 0.1) # 图 2 大于阈值的坐标
d1 = get_descriptors(img1, filtered_coords1, wid)
d2 = get_descriptors(img2, filtered_coords2, wid)
matches = match_twosided(d1, d2, 0.8) # 图 1 的阈值点与图二哪个阈值点相关度最高,输出与图一相关性最大点的坐标
plt.figure(figsize=(30, 20));
plot_matches(img1, img2, filtered_coords1, filtered_coords2, matches)
cv2.waitKey()
cv2.destroyAllWindows()
# 为什么代码运行出来只有两幅图像上的角点变蓝了,但是没有连线
# 改为 r 也没有反应
# 内容:可能是因为在函数 plot_matches 中,连线的颜色被写死成了 'c',可以尝试修改为 'red' 或者其他颜色,例如:
#
# if m > 0:
# plt.plot([locs1[i][1], locs2[m][1] + cols1], [locs1[i][0], locs2[m][0]], color='red')
代码解释:
- 导入库:首先导入必要的库,包括 OpenCV (cv2),NumPy (np) 和 Matplotlib (pyplot)。
- 读取图像:使用
cv2.imread()读取两幅图像1.png和4.png。 - Harris 角点检测:使用
cv2.cornerHarris()函数进行 Harris 角点检测。gray1和gray2是将图像转换为灰度图像。dst1和dst2是包含 Harris 角点响应的图像。img1[dst1>0.01*dst1.max()] = [0,0,255]和img2[dst2>0.01*dst2.max()] = [0,0,255]将检测到的角点设置为蓝色 (BGR)。
- 获取 Harris 角点:
get_harris_points()函数从 Harris 响应图像中获取角点。- 函数接受 Harris 响应图像、最小距离(
min_dist)和阈值(threshold)作为输入。 - 函数返回一个包含所有角点坐标的列表。
- 函数接受 Harris 响应图像、最小距离(
- 获取描述符:
get_descriptors()函数从图像中获取每个角点的描述符。- 函数接受图像、角点坐标列表和描述符窗口大小(
wid)作为输入。 - 函数返回一个包含每个角点描述符的列表。
- 函数接受图像、角点坐标列表和描述符窗口大小(
- 特征匹配:
match()和match_twosided()函数使用归一化互相关 (NCC) 算法匹配两个图像中的特征点。match()函数计算两幅图像中所有描述符之间的 NCC,并将匹配结果存储在一个数组中。match_twosided()函数是对称地执行 NCC 匹配,以确保匹配是双向的。
- 拼接图像:
appendimages()函数将两幅图像并排拼接在一起。 - 绘制匹配结果:
plot_matches()函数绘制两幅图像,并用线连接匹配的特征点。- 函数接受两幅图像、角点坐标列表和匹配结果数组作为输入。
- 函数将匹配结果可视化。
- 运行代码:代码的最后部分执行上述步骤,并使用
cv2.waitKey()和cv2.destroyAllWindows()显示结果图像。
代码示例:
import cv2
import numpy as np
from matplotlib import pyplot as plt
# 读取图像
img1 = cv2.imread('1.png')
img2 = cv2.imread('4.png')
# Harris 角点检测
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray1 = np.float32(gray1)
dst1 = cv2.cornerHarris(gray1, 2, 3, 0.04)
img1[dst1 > 0.01 * dst1.max()] = [0, 0, 255]
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
gray2 = np.float32(gray2)
dst2 = cv2.cornerHarris(gray2, 2, 23, 0.04)
img2[dst2 > 0.01 * dst2.max()] = [0, 0, 255]
# 获取 Harris 角点
wid = 9
filtered_coords1 = get_harris_points(dst1, wid + 1, 0.1)
filtered_coords2 = get_harris_points(dst2, wid + 1, 0.1)
# 获取描述符
d1 = get_descriptors(img1, filtered_coords1, wid)
d2 = get_descriptors(img2, filtered_coords2, wid)
# 特征匹配
matches = match_twosided(d1, d2, 0.8)
# 绘制匹配结果
plt.figure(figsize=(30, 20))
plot_matches(img1, img2, filtered_coords1, filtered_coords2, matches)
plt.show()
解决连线问题:
在 plot_matches() 函数中,连线的颜色被写死成了 'c',可以通过将 'c' 更改为 'red' 或其他颜色来解决连线问题:
def plot_matches(im1, im2, locs1, locs2, matchscores):
im3 = appendimages(im1, im2)
plt.imshow(im3)
cols1 = im1.shape[1]
for i, m in enumerate(matchscores):
if m > 0:
# 将颜色更改为 'red'
plt.plot([locs1[i][1], locs2[m][1] + cols1], [locs1[i][0], locs2[m][0]], color='red')
plt.axis('off')
plt.show()
注意事项:
- 确保
1.png和4.png存在于代码的同级目录下。 - 图像的特征点数量和匹配的质量会影响最终的匹配结果。
- 您可以尝试调整 Harris 角点检测器和 NCC 匹配算法的参数,以获得更好的结果。
总结:
本教程演示了如何使用 OpenCV 库中的 Harris 角点检测器和归一化互相关算法来找到两幅图像之间的对应特征点。代码示例展示了如何实现这些算法,并解释了如何解决常见问题。您可以通过修改代码参数和算法,根据具体需求进行调整。
原文地址: https://www.cveoy.top/t/topic/knoW 著作权归作者所有。请勿转载和采集!