opencv中 在特征点匹配代码举例,以及queryIdx和trainIdx的用法。

一、用法

在特征点匹配中,queryIdx和trainIdx是匹配对中的两个索引,用于指示匹配点在不同图像或特征向量中的位置。
1.假设我们有两幅图像A和B,并使用特征点提取算法(如SIFT)从它们中提取出特征点和对应的描述子。
2.在进行特征点匹配时,我们得到了一个匹配对,其中包含了两个特征点:特征点A和特征点B。
queryIdx:特征点A在图像A中的索引。
trainIdx:特征点B在图像B中的索引。
换句话说,queryIdx是指示特征点在查询图像(图像A)中的位置,而trainIdx是指示特征点在训练图像(图像B)中的位置。
举个具体的例子:
假设匹配对中的queryIdx为10,trainIdx为5。
这意味着特征点A是图像A中的第11个特征点(索引从0开始),而特征点B是图像B中的第6个特征点。
在特征点匹配中,queryIdx和trainIdx提供了特征点在不同图像中的对应关系,使我们能够在不同图像间建立联系并进行后续的操作,例如计算视角变换矩阵或进行图像配准等。

二、代码示例

import cv2
import numpy as np

# 读取图像
img1 = cv2.imread('image1.jpg', 0)
img2 = cv2.imread('image2.jpg', 0)

# 创建SIFT对象并检测特征点
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

# 创建BFMatcher对象
bf = cv2.BFMatcher()

# 使用KNN算法进行特征点匹配
matches = bf.knnMatch(des1, des2, k=2)

# 通过筛选最佳匹配对获取特征点坐标
good_matches = []
for m, n in matches:
    if m.distance < 0.75 * n.distance:
        good_matches.append(m)

# 对匹配对按照距离进行排序
good_matches = sorted(good_matches, key=lambda x: x.distance, reverse=True)

# 获取距离最远的前十个匹配对的特征点坐标
top_matches = good_matches[:10]
points1 = np.float32([kp1[m.queryIdx].pt for m in top_matches])
points2 = np.float32([kp2[m.trainIdx].pt for m in top_matches])
#.pt是KeyPoint类的一个属性,用于表示特征点的坐标。

# 打印匹配对中特征点的坐标
for i in range(len(top_matches)):
    pt1 = tuple(map(int, points1[i]))
    pt2 = tuple(map(int, points2[i]))
    print(f"Match {i+1}: Point 1: {pt1}, Point 2: {pt2}")

输出结果:

Match 1: Point 1: (430, 79), Point 2: (170, 76)
Match 2: Point 1: (363, 56), Point 2: (100, 39)
Match 3: Point 1: (309, 225), Point 2: (29, 216)
Match 4: Point 1: (445, 3), Point 2: (181, 7)
Match 5: Point 1: (346, 77), Point 2: (80, 60)
Match 6: Point 1: (359, 94), Point 2: (100, 79)
Match 7: Point 1: (365, 80), Point 2: (106, 66)
Match 8: Point 1: (53, 53), Point 2: (298, 81)
Match 9: Point 1: (456, 363), Point 2: (168, 337)
Match 10: Point 1: (349, 110), Point 2: (84, 94)
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值