python opencv3 FLANN單應性匹配


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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM