33 lines
1.2 KiB
Python
33 lines
1.2 KiB
Python
|
# Initiate SIFT detector
|
||
|
sift = cv2.SIFT_create()
|
||
|
# find the keypoints and descriptors with SIFT
|
||
|
# Here img1 and img2 are grayscale images
|
||
|
kp1, des1 = sift.detectAndCompute(img1,None)
|
||
|
kp2, des2 = sift.detectAndCompute(img2,None)
|
||
|
|
||
|
# FLANN parameters
|
||
|
# I literally copy-pasted the defaults
|
||
|
FLANN_INDEX_KDTREE = 1
|
||
|
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
|
||
|
search_params = dict(checks=50) # or pass empty dictionary
|
||
|
# do the matching
|
||
|
flann = cv2.FlannBasedMatcher(index_params,search_params)
|
||
|
matches = flann.knnMatch(des1,des2,k=2)
|
||
|
|
||
|
## OPTIONAL - Show matches ##
|
||
|
|
||
|
# Need to draw only good matches, so create a mask
|
||
|
matchesMask = [[0,0] for i in range(len(matches))]
|
||
|
# ratio test as per Lowe's paper <- this is a criterion for matches selection
|
||
|
for i,(m,n) in enumerate(matches):
|
||
|
if m.distance < 0.7*n.distance:
|
||
|
matchesMask[i]=[1,0]
|
||
|
draw_params = dict(matchColor = (0,255,0),
|
||
|
singlePointColor = (255,0,0),
|
||
|
matchesMask = matchesMask,
|
||
|
flags = cv2.DrawMatchesFlags_DEFAULT)
|
||
|
|
||
|
img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None, **draw_params)
|
||
|
f, ax = plt.subplots(1, figsize=(15,15))
|
||
|
ax.imshow(img3)
|
||
|
plt.show()
|