Brute-Force蛮力匹配
cv2.BFMatcher(crossCheck = True)
crossCheck表示两个特征点相互匹配
例如A中的第i个特征点与B中的第j个特征点最近,并且B中的第j个特征点到A中的第i个特征点也是
NORM_L2:归一化数组的(欧几里得距离),如果其他特征计算方法需要考虑不同的匹配计算方法
import cv2
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inlinedef show_photo(name,picture):#图像显示函数cv2.imshow(name,picture)cv2.waitKey(0)cv2.destroyAllWindows()img1 = cv2.imread('E:\Jupyter_workspace\study\data/box.png',0)
img2 = cv2.imread('E:\Jupyter_workspace\study\data/box_1.png',0)show_photo('img1',img1)
show_photo('img2',img2)sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None)#kp1为关键点,des1为对应的特征向量
kp2, des2 = sift.detectAndCompute(img2,None)
bf = cv2.BFMatcher(crossCheck = True)#1对1的匹配
matches = bf.match(des1,des2)
matches = sorted(matches, key = lambda x:x.distance)
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=2)
show_photo('img3',img3)#k对最佳匹配
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1,des2,k=2)good = []
for m,n in matches:if m.distance <0.75 * n.distance:good.append([m])img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2)
show_photo('img3',img3)
模板:
原图:
1对1的匹配:
k对最佳匹配: