使用 OpenCV 进行 Harris 角点检测和特征匹配

本代码使用 OpenCV 库在 Python 中实现 Harris 角点检测和特征匹配算法,并展示如何处理匹配结果以绘制匹配的角点。

import cv2
import numpy as np
from matplotlib import pyplot as plt

# 读取图像
img1 = cv2.imread('1.png')
img2 = cv2.imread('4.png')

# 归一化图像像素值到 0 到 1 之间
img1 = cv2.normalize(img1, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_32F)
img2 = cv2.normalize(img2, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_32F)

# 将图像转换为灰度图像
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray1 = np.float32(gray1)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
gray2 = np.float32(gray2)

# 使用 Harris 角点检测算法检测角点
dst1 = cv2.cornerHarris(gray1, 2, 3, 0.04)
img1[dst1 > 0.1 * dst1.max()] = [0, 0, 255]
dst2 = cv2.cornerHarris(gray2, 2, 23, 0.04)
img2[dst2 > 0.1 * dst2.max()] = [0, 0, 255]

# 从 Harris 响应图像中获取角点
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
    candidate_values = [harrisim[c[0], c[1]] for c in coords]
    index = np.argsort(candidate_values)[::-1]
    allowed_locations = np.zeros(harrisim.shape)
    allowed_locations[min_dist:-min_dist, min_dist:-min_dist] = 1
    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

# 获取每个角点的描述符
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)
    matchscores = ndx[:, 0]
    return matchscores

# 双向匹配
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)

# 绘制匹配结果
def plot_matches(img1, img2, locs1, locs2, matchscores, show_below=False):
    img3 = appendimages(img1, img2)
    if show_below:
        img3 = np.vstack((img3, img3))
    plt.imshow(img3)
    cols1 = img1.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')

# 获取角点描述符并进行匹配
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()
cv2.waitKey(0)
cv2.destroyAllWindows()

代码解释:

  1. 导入库: 导入必要的库:cv2 用于图像处理,numpy 用于数组操作,matplotlib.pyplot 用于绘图。

  2. 读取图像: 使用 cv2.imread() 读取两幅图像。

  3. 图像归一化: 使用 cv2.normalize() 将图像像素值归一化到 0 到 1 之间,以避免 imshow 函数报错。

  4. 转换为灰度图像: 使用 cv2.cvtColor() 将图像转换为灰度图像,因为 Harris 角点检测算法只适用于灰度图像。

  5. Harris 角点检测: 使用 cv2.cornerHarris() 函数检测图像中的角点。

  6. 获取角点: 定义 get_harris_points() 函数,从 Harris 响应图像中获取角点。

  7. 获取描述符: 定义 get_descriptors() 函数,获取每个角点的描述符。

  8. 匹配描述符: 定义 match() 函数,使用归一化互相关匹配描述符。

  9. 双向匹配: 定义 match_twosided() 函数,进行双向匹配,以确保匹配的可靠性。

  10. 拼接图像: 定义 appendimages() 函数,将两幅图像拼接在一起。

  11. 绘制匹配结果: 定义 plot_matches() 函数,绘制匹配的角点。

  12. 主函数: 获取角点描述符并进行匹配,最后绘制匹配结果。

注意:

  • 本代码使用的是 OpenCV 3.x 版本,如果使用其他版本,可能需要修改一些代码。
  • 为了获得最佳匹配结果,可以调整代码中的参数,例如阈值和描述符大小。
  • 您可以将 1.png4.png 替换为您的图像文件。

运行结果:

运行代码后,您将看到一张包含两个拼接图像的图片,匹配的角点之间用蓝色线连接起来。

使用 OpenCV 进行 Harris 角点检测和特征匹配 - Python 实现

核心代码

import cv2
import numpy as np
from matplotlib import pyplot as plt

# 读取图像
img1 = cv2.imread('1.png')
img2 = cv2.imread('4.png')

# 归一化图像像素值到 0 到 1 之间
img1 = cv2.normalize(img1, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_32F)
img2 = cv2.normalize(img2, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_32F)

# 将图像转换为灰度图像
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray1 = np.float32(gray1)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
gray2 = np.float32(gray2)

# 使用 Harris 角点检测算法检测角点
dst1 = cv2.cornerHarris(gray1, 2, 3, 0.04)
img1[dst1 > 0.1 * dst1.max()] = [0, 0, 255]
dst2 = cv2.cornerHarris(gray2, 2, 23, 0.04)
img2[dst2 > 0.1 * dst2.max()] = [0, 0, 255]

# 从 Harris 响应图像中获取角点
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
    candidate_values = [harrisim[c[0], c[1]] for c in coords]
    index = np.argsort(candidate_values)[::-1]
    allowed_locations = np.zeros(harrisim.shape)
    allowed_locations[min_dist:-min_dist, min_dist:-min_dist] = 1
    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

# 获取每个角点的描述符
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)
    matchscores = ndx[:, 0]
    return matchscores

# 双向匹配
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)

# 绘制匹配结果
def plot_matches(img1, img2, locs1, locs2, matchscores, show_below=False):
    img3 = appendimages(img1, img2)
    if show_below:
        img3 = np.vstack((img3, img3))
    plt.imshow(img3)
    cols1 = img1.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')

# 获取角点描述符并进行匹配
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()
cv2.waitKey(0)
cv2.destroyAllWindows()

代码解析

  1. 导入库: 导入必要的库:cv2 用于图像处理,numpy 用于数组操作,matplotlib.pyplot 用于绘图。

  2. 读取图像: 使用 cv2.imread() 读取两幅图像。

  3. 图像归一化: 使用 cv2.normalize() 将图像像素值归一化到 0 到 1 之间,以避免 imshow 函数报错。

  4. 转换为灰度图像: 使用 cv2.cvtColor() 将图像转换为灰度图像,因为 Harris 角点检测算法只适用于灰度图像。

  5. Harris 角点检测: 使用 cv2.cornerHarris() 函数检测图像中的角点。

  6. 获取角点: 定义 get_harris_points() 函数,从 Harris 响应图像中获取角点。

  7. 获取描述符: 定义 get_descriptors() 函数,获取每个角点的描述符。

  8. 匹配描述符: 定义 match() 函数,使用归一化互相关匹配描述符。

  9. 双向匹配: 定义 match_twosided() 函数,进行双向匹配,以确保匹配的可靠性。

  10. 拼接图像: 定义 appendimages() 函数,将两幅图像拼接在一起。

  11. 绘制匹配结果: 定义 plot_matches() 函数,绘制匹配的角点。

  12. 主函数: 获取角点描述符并进行匹配,最后绘制匹配结果。

运行结果

运行代码后,您将看到一张包含两个拼接图像的图片,匹配的角点之间用蓝色线连接起来。

注意

  • 本代码使用的是 OpenCV 3.x 版本,如果使用其他版本,可能需要修改一些代码。
  • 为了获得最佳匹配结果,可以调整代码中的参数,例如阈值和描述符大小。
  • 您可以将 '1.png' 和 '4.png' 替换为您的图像文件。
OpenCV Harris 角点检测和特征匹配:Python 代码实现

原文地址: https://www.cveoy.top/t/topic/knte 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录