Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Get nearest neighbors

Hello,

The problem we will discuss is pretty common, I want to search the nearest neighbors with Opencv. I found dozens of example but the program always sends me wrong informations.

here is the example I get:

std::vector<cv::Point2f> pointsForSearch;

for (int c = 100; c < 640; c += 100) {
    for (int l = 100; l < 640; l += 100) {
        pointsForSearch.emplace_back(cv::Point2f(float(c), float(l)));
    }
}

cv::Mat_<float> features(0,2);

 for(auto && point : pointsForSearch) {

   //Fill matrix
   cv::Mat row = (cv::Mat_<float>(1, 2) << point.x, point.y);
   features.push_back(row);
 }
 std::cout << features << std::endl;

 cv::flann::Index flann_index(features, cv::flann::KDTreeIndexParams(1));


 unsigned int max_neighbours = 10;
 cv::Mat query = (cv::Mat_<float>(1, 2) << 313.0, 245.6);
 cv::Mat indices, dists; //neither assume type nor size here !
 double radius= 2000.0;

 flann_index.radiusSearch(query, indices, dists, radius, max_neighbours,
     cv::flann::SearchParams(32));

 std::cerr << indices.type() << std::endl << indices << std::endl;
 std::cerr << dists.type() << std::endl << dists << std::endl;

The result is :

4
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
5
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The result is alway zero. What is wrong with the previous example?