Search code examples
pythonopencvimage-processingnearest-neighborkdtree

knn search with opencv in python


I have this sample code for opencv in c++:

flann::KDTreeIndexParams indexParams;
flann::Index kdtree(Mat(cloud2d).reshape(1), indexParams);
vector<float> query;
query.push_back(370); 
query.push_back(464); 
vector<int> indices;
vector<float> dists;
kdtree.knnSearch(query, indices, dists, 3);

how can I do the same in python ? Tried, but can't create kdtree or KDTreeIndexParams with cv2.


Solution

  • FLANN is a library for ANN, that is written in C++, and is independent from OpenCV. It offers bindings for Python, in pyflann.

    An example can be found here:

    from pyflann import *
    import numpy as np
    
    dataset = np.array(
        [[1., 1, 1, 2, 3],
         [10, 10, 10, 3, 2],
         [100, 100, 2, 30, 1]
         ])
    testset = np.array(
        [[1., 1, 1, 1, 1],
         [90, 90, 10, 10, 1]
         ])
    flann = FLANN()
    result, dists = flann.nn(
        dataset, testset, 2, algorithm="kmeans", branching=32, iterations=7, checks=16)
    print result
    print dists
    
    dataset = np.random.rand(10000, 128)
    testset = np.random.rand(1000, 128)
    flann = FLANN()
    result, dists = flann.nn(
        dataset, testset, 5, algorithm="kmeans", branching=32, iterations=7, checks=16)
    print result
    print dists
    

    This example should be enough to get you started.