FLANN算法+RANSAN算法的特征点的匹配(附代码)

FLANN 是快速最临近邻搜索包的简称Fast_Library_for_Approximate_Nearest_Neighbors的简称。它是一个对大数据集和高维特征进行最近邻搜索的算法的集合。

特点:在面对大数据集时它的效果要好于 BFMatcher。


使用FLANN算法进行匹配时,需要传入两个字典作为参数。这两个字典是为了确定要使用的算法和其他相关参数等。

  1. 第一个字典是 IndexParams。对于SIFT 和SURF 等算法我们可以传入的参数是: indexparams = dict(algorithm = F LANNINDEXKDTREE, trees = 5)
  2. 第二个字典是 SearchParams。用它来指定递归遍历的次数。值越高结果越准确,但是消耗的时间也越多。如果想修改这个值,传入参数searchparams = dict(checks = 100)。

使用一个查询图像,在其中找到一些特征点(关键点),我们又在另一幅图像中也找到了一些特征点,最后对这两幅图像之间的特征点进行匹配。简单来说就是:我们在一张杂乱的图像中找到了一个对象(的某些部分)的位置。这些信息足以帮助我们在目标图像中准确的找到(查询图像)对象。 

可以使用 calib3d 模块中的 cv2.findHomography()函数。如果将这两幅图像中的特征点集传给这个函数,他就会找到这个对象的透视图变换。然后就可以使用函数cv2.perspectiveTransform() 找到这个对象了。至少要 4 个正确的点才能找到这种变换。 

我们已经知道在匹配过程可能会有一些错误匹配,而这些错误会影响最终结果。为了解决这个问题,算法使用 RANSAC 和 LEAST_MEDIAN(可以通过参数来设定)。所以好的匹配提供的正确的估计被称为 inliers,剩下的被称为outliers cv2.findHomography() 返回一个掩模,这个掩模确定了 inlier 和outlier 点。

代码如下图所示:

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

MIN_MATCH_COUNT = 10

img1 = cv2.imread('shu1.jpg', 0)
img2 = cv2.imread('shu2.jpg', 0)

sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

FLANN_INDEX_KDTREE = 0
indexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
searchParams = dict(checks=50)

flann = cv2.FlannBasedMatcher(indexParams, searchParams)

matches = flann.knnMatch(des1, des2, k=2)

good = []
for m, n in matches:
    if m.distance < 0.7 * n.distance:
        good.append(m)

if len(good) > MIN_MATCH_COUNT:
    src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
    dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

    matchesMask = mask.ravel().tolist()
    h, w = img1.shape
    pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
    dst = cv2.perspectiveTransform(pts, M)

    img2 = cv2.polylines(img2, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)
else:
    print("Not Enough")
    matchesMask = None

drawParams = dict(matchColor=(0, 255, 0),
                  singlePointColor=None,
                  matchesMask=matchesMask,
                  flags=2
                  )
resultImage = cv2.drawMatches(img1, kp1, img2, kp2, good, None, **drawParams)
plt.xticks([]), plt.yticks([])
plt.imshow(resultImage), plt.show()

运行结果如图所示:

绿色为匹配线,白色为左边图框的单应性映射线
  • 2
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
这里提供一个基于OpenCV实现的sift+FLANN+ransac+加权融合算法代码代码中使用了两幅图像进行拼接。需要注意的是,这段代码仅供参考,具体实现需要根据实际情况进行调整和改进。 ```python import cv2 import numpy as np # 读入两幅图片 img1 = cv2.imread('img1.jpg') img2 = cv2.imread('img2.jpg') # 获取图片大小 rows1, cols1 = img1.shape[:2] rows2, cols2 = img2.shape[:2] # 使用sift算法提取特征点和特征描述子 sift = cv2.xfeatures2d.SIFT_create() keypoints1, descriptors1 = sift.detectAndCompute(img1, None) keypoints2, descriptors2 = sift.detectAndCompute(img2, None) # 使用FLANN算法进行特征匹配 FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) search_params = dict(checks=50) flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(descriptors1, descriptors2, k=2) # 进行ransac过滤 good_matches = [] for m, n in matches: if m.distance < 0.7 * n.distance: good_matches.append(m) src_pts = np.float32([keypoints1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2) dst_pts = np.float32([keypoints2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) # 计算拼接后的图像大小 h, w = img1.shape[:2] pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2) dst = cv2.perspectiveTransform(pts, M) dst += (cols1, 0) # 进行图像拼接 result = np.zeros((max(rows1, rows2), cols1 + cols2, 3), dtype=np.uint8) result[:rows1, :cols1, :] = img1 result[:rows2, cols1:, :] = img2 # 加权融合 for i in range(dst.shape[0]): x, y = dst[i][0] x, y = int(x), int(y) if 0 <= x < cols1 + cols2 and 0 <= y < max(rows1, rows2): if x < cols1: result[y, x, :] = img1[y, x, :] elif x >= cols1: result[y, x, :] = img2[y, x - cols1, :] else: result[y, x, :] = (img1[y, x, :] + img2[y, x - cols1, :]) / 2 # 显示拼接后的图像 cv2.imshow('result', result) cv2.waitKey(0) cv2.destroyAllWindows() ```
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值