python cv2 feature matching give different results

Skip to first unread message

Zhang Xun

Aug 21, 2018, 10:30:18 PM8/21/18
to OpenCV with Python Blueprints
Hi,I am new to opencv. When I match SIFT feature using FLANN,I found same input descriptor give different match pairs in same process.

I found the matches in line 11 is different although my input descriptor(des1,des2) is same,I guess the reason is kd-tree cache,but I can't solve it.Any one could help me?

I want the matches result is always same. My cv2 version is 3.4.0, Thanks in advance.

import cv2
 def match(des_q, des_t):
    ratio = 0.7  
    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
    search_params = dict(checks=50)
    flann1 = cv2.FlannBasedMatcher(index_params, search_params)
    two_nn = flann1.knnMatch(des_q, des_t, k=2)
    matches = [(first.queryIdx, first.trainIdx) for first, second in two_nn
                   if first.distance < ratio * second.distance]

def img_sim(img1, img2):
    img1 = cv2.cvtColor(img1, cv2.IMREAD_GRAYSCALE)
    img2 = cv2.cvtColor(img2, cv2.IMREAD_GRAYSCALE)
    sift = cv2.xfeatures2d.SIFT_create()
    eps = 1e-7
    # find the keypoints and descriptors with SIFT
    kp1, des1 = sift.detectAndCompute(img1, None)
    des1 /= (des1.sum(axis=1, keepdims=True) + eps)
    des1 = np.sqrt(des1)
    kp2, des2 = sift.detectAndCompute(img2, None)
    des2 /= (des2.sum(axis=1, keepdims=True) + eps)
    des2 = np.sqrt(des2)
    match(des1, des2)
    match(des1, des2)

img1 = cv2.cvtColor(cv2.imread(img1), cv2.COLOR_BGR2RGB)
img2 = cv2.cvtColor(cv2.imread(img2), cv2.COLOR_BGR2RGB)
img_sim(img1, img2)

Michael Beyeler

Dec 11, 2018, 12:42:47 PM12/11/18
to OpenCV with Python Blueprints

You're not the only one having this problem. FLANN uses some probabilistic method to find the matches. That's why you get different results each time.

Unfortunately, I don't think you can seed the random generator in Python... Or even in C++... Bad design.

Reply all
Reply to author
0 new messages