From: https://github.com/ducha-aiki/affnet/blob/master/examples/SIFT-AffNet-HardNet-kornia-matching.ipynb
import cv2
import numpy as np
def extract_sift_keypoints_upright(img, n_feat = 5000):
sift = cv2.xfeatures2d.SIFT_create(2 * n_feat,
contrastThreshold=-10000, edgeThreshold=-10000)
keypoints = sift.detect(img, None)
response = np.array([kp.response for kp in keypoints])
respSort = np.argsort(response)[::-1]
kpts = [cv2.KeyPoint(keypoints[i].pt[0], keypoints[i].pt[1], keypoints[i].size, 0) for i in respSort]
kpts_unique = []
for x in kpts:
if x not in kpts_unique:
kpts_unique.append(x)
return kpts_unique[:n_feat]
#
def match_snn(desc1, desc2, snn_th = 0.8):
index_params = dict(algorithm=1, trees=4)
search_params = dict(checks=128) # or pass empty dictionary
matcher = cv2.FlannBasedMatcher(index_params, search_params)
matches = matcher.knnMatch(desc1.astype(np.float32), desc2.astype(np.float32), k=2)
good_matches = []
for m,n in matches:
if m.distance < snn_th * n.distance:
good_matches.append(m)
return good_matches