git:https://github.com/linyi0604/Computer-Vision
匹配准确率非常高。
单应性指的是图像在投影发生了 畸变后仍然能够有较高的检测和匹配准确率
1 # coding:utf-8
2
3 """
4 单应性匹配: 5 两幅图像中的一幅 出现投影畸变的时候,他们还能彼此匹配 6 """
7
8 import cv2 9 import numpy as np 10 # 最小匹配数量设为10个, 大于这个数量从中筛选出10个最好的
11 MIN_MATCH_COUNT = 10
12
13 # 读入两幅图片 图片中有相同部分
14 img1 = cv2.imread("../data/logo1.png", cv2.IMREAD_GRAYSCALE) 15 img2 = cv2.imread("../data/album1.png", cv2.IMREAD_GRAYSCALE) 16
17 # 获取sift特征检测器
18 sift = cv2.xfeatures2d.SIFT_create() 19 # 检测关键点 计算描述符
20 kp1, des1 = sift.detectAndCompute(img1, None) 21 kp2, des2 = sift.detectAndCompute(img2, None) 22
23 # kdtree建立索引方式的常量参数
24 FLANN_INDEX_KDTREE = 0 25 index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) 26 search_params = dict(checks=50) # checks指定索引树要被遍历的次数
27 flann = cv2.FlannBasedMatcher(index_params, search_params) 28 # 进行匹配搜索
29 matches = flann.knnMatch(des1, des2, k=2) 30
31 # 寻找距离近的放入good列表
32 good = [] 33 for m, n in matches: 34 if m.distance < 0.7 * n.distance: 35 good.append(m) 36
37 # 如果足够多 就筛选
38 if len(good) > MIN_MATCH_COUNT: 39 # 通过距离近的描述符 找到两幅图片的关键点
40 src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2) 41 dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2) 42
43 # 单应性匹配图关键点匹配线。。不懂啥意思
44 M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) 45 matchesMask = mask.ravel().tolist() 46
47 h, w = img1.shape 48
49 # 计算第二张图相对于第一张图的畸变
50 pts = np.float32([[0, 0], [0, h-1], [w-1, 0]]).reshape(-1, 1, 2) 51 dst = cv2.perspectiveTransform(pts, M) 52 img2 = cv2.polylines(img2, [np.int32(dst)], True, 255, 3, cv2.LINE_AA) 53 else: 54 matchesMask = None 55
56 draw_params = dict( 57 matchColor=(0, 255, 0), 58 singlePointColor=None, 59 matchesMask=matchesMask, 60 flags=2
61 ) 62
63 img3 = cv2.drawMatches(img1, kp1, img2, kp2, good, None, **draw_params) 64 cv2.imshow("", img3) 65 cv2.waitKey()