Python获取特征匹配结果DMatch中的像素坐标信息

Posted Z.Q.Feng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python获取特征匹配结果DMatch中的像素坐标信息相关的知识,希望对你有一定的参考价值。

文章目录


一、前言

最近使用 Python 做图像的特征匹配,使用到了 cv2 库中的 BFMatcher_create 函数,但是其返回结果却是 DMatch 类型的,无法直接查看也无法获取有用信息,查阅资料写了个函数提取我所需要的坐标信息。


二、代码

函数如下:

def get_coordinates_from_matches(matches: list, kp1: list, kp2: list):
    '''
    Created on Wed Aug 17 21:00:36 2022

    Input :
        matches : [type=DMatch, ...]
        kp1     : KeyPoints from query image, [type=KeyPoint, ...]
        kp2     : KeyPoints from train image, [type=KeyPoint, ...]

    Return:
        list1   : stores the matching keypoints for query image
        list2   : stores the matching keypoints for train image

    len(matches) == len(kp1) == len(kp2)
    @author: zqfeng
    '''
    # Initialize lists
    list_kp1 = []
    list_kp2 = []

    # For each match...
    for mat in matches:
        # Get the matching keypoints for each of the images
        img1_idx = mat.queryIdx
        img2_idx = mat.trainIdx
        # x - columns
        # y - rows
        # Get the coordinates
        (x1, y1) = kp1[img1_idx].pt
        (x2, y2) = kp2[img2_idx].pt
        # Append to each list
        list_kp1.append((x1, y1))
        list_kp2.append((x2, y2))

    return list_kp1, list_kp2

三、使用方法

首先我们有一组 Match 数据:

In [50]: len(matches)
Out[50]: 500

In [51]: type(matches[0])
Out[51]: cv2.DMatch

以及 Match 之前创建的特征匹配点 kp1(from query image), kp2(from train image)

In [9]: len(kp1)
Out[9]: 500

In [10]: type(kp1[0])
Out[10]: cv2.KeyPoint

注意这里 Match, kp1, kp2 的长度相等,我们想从 matches 中提取我们想要的坐标信息:

list_kp1, list_kp2 = get_coordinates_from_matches(ms, kp1, kp2)

这里的 list_kp1 列表便储存了我们这次 match 中 query image 的所有匹配像素点坐标了,我们可以通过 cv2.circlr() 函数在图中画出对应像素点,其数据格式如下:

In [52]: list_kp1[:10]
Out[52]: 
[(846.7200927734375, 1496.4481201171875),
 (1460.16015625, 1518.912109375),
 (1482.6241455078125, 1498.1761474609375),
 (1953.3314208984375, 1457.740966796875),
 (1283.9735107421875, 1522.852294921875),
 (1403.412841796875, 1475.5740966796875),
 (1617.4083251953125, 1460.6441650390625),
 (833.5873413085938, 1434.931396484375),
 (871.2000122070312, 1540.800048828125),
 (1728.88525390625, 1510.9083251953125)]

四、总结

以上是关于Python获取特征匹配结果DMatch中的像素坐标信息的主要内容,如果未能解决你的问题,请参考以下文章

Python获取特征匹配结果DMatch中的像素坐标信息

Python获取特征匹配结果DMatch中的像素坐标信息

如何从 OpenCV Python 中的特征匹配中获取像素坐标

[OpenCV]DMatch类和KeyPoints类:特征点匹配

使用 ORB python opencv 匹配特征

使用 OpenCV 改进特征点的匹配