Search code examples
pythonopencvflann

Compare image vs database of images using SURF and FLANN


I'm trying to compare a single image vs a database of images.
I'm currently using Python 2.7 and OpenCV 3.3.0.
After some googling, I come up with this code:

scanned = 'tests/temp_bw.png'
surf = cv2.xfeatures2d.SURF_create(400)
surf.setUpright(True)

img1 = cv2.imread(scanned, 0)
kp1, des1 = surf.detectAndCompute(img1, None)

FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)

flann = cv2.FlannBasedMatcher(index_params, search_params)

for filename in os.listdir('images'):
    img2 = cv2.imread('images/' + filename, 0)
    kp2, des2 = surf.detectAndCompute(img2, None)
    flann.add([des2])

print str(len(flann.getTrainDescriptors()))

print "Training..."
flann.train()

print "Matching..."
indexes, matches = flann.knnSearch(des1, 2, params={})

The main problem is that in OpenCV 3.3.0 the FlannBasedMatcher has no method knnSearch. I checked current code documentation and in 2.4 such method was there, now it was removed.

Is there anything similar in OpenCV 3.3.0?
Or should I use a different approach?


Solution

  • In OpenCV 3.3.0 the function is called knnMatch

    Example usage can be found on this page under FLANN based Matcher: http://docs.opencv.org/trunk/dc/dc3/tutorial_py_matcher.html


    Edit: Sorry, I realize now that I misunderstood you. The knnSearch function is now under flann.Index(), and can be used as follows. Make sure that your database of descriptors and the query object are both float32

    flann = cv2.flann.Index()
    print "Training..."
    flann.build(des_all, index_params)
    print "Matching..."
    indexes, matches = flann.knnSearch(des1, 2)