Search code examples
pythonopencvnumpyflann

Can't load a saved FLANN index


After adding all descriptors to a FLANN index, I'm saving it using this code:

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

        des_all = np.concatenate((des_all, des2))

    print "Training..."
    flann.build(des_all, index_params)

    print "Saving..."
    flann.save('saved_index')

This correctly creates a binary file containing all the info.
However, I'm having hard times to load the same file. Even if I supply the correct params to load its contents:

    flann = cv2.flann.Index()
    des_all = np.empty((281578, 64), dtype=np.float32)
    flann.load(des_all, 'saved_index')

I tried to switch np.empty with np.zeros and to manually set the array writeable using des_all.flags.writeable = True, but still nothing.
The shape and type of the of the Numpy array is correct, the same applied to the file path: if I try to use some wrong values I get a warn in the console.

No matter what, my des_all array is always filled with zeros and any searches on that index will always return nothing.
Any suggestions?


Solution

  • After a lot of playing around, I finally found a solution.
    Documentation doesn't help very much, so I had to do a lot of trial and errors.
    As far as I can understand, the whole search process is split in two parts:

    • The actual data
    • The index for fast processing

    This means that when I try to restore a previous state, I have to supply the FLANN index the same data, then I can load the saved data.
    Otherwise the index points to invalid positions, resulting in an empty result.
    You can easily store the original data using Numpy built-in functions.