c++opencvflannflannbasedmatcher

FlannBasedMatcher returning different results


Using the FlannBasedMatcher in OpenCV, I am getting different results calling the matcher with the same parameters. Can anyone suggest what I am doing wrong please?

The code below shows a minimal example of the problem I am having - it is simplified representative of how I use the FlannBasedMatcher - this isn't real code :)

Results output each time around the loop should be identical, but they are not.

    int const k = std::min(query_descriptors.rows,
                      std::min(train_descriptors.rows, 2));

    cv::Mat query_descriptors_original = query_descriptors.clone();
    cv::Mat train_descriptors_original = train_descriptors.clone();
    for (int loop=0; loop<2; ++loop)
    {
        cv::FlannBasedMatcher matcher;
        matcher.add(std::vector<cv::Mat>(1, train_descriptors));

        std::vector<matches_t> knnMatches;
        matcher.knnMatch(query_descriptors,  knnMatches, k);

        matches.clear();
        for (auto const &knn : knnMatches)
        {
            matches.push_back(knn[0]);
            std::cout << knn[0].queryIdx << ',' << knn[0].trainIdx << '\n';
        }
        std::cout << '\n';

        assert(cv::countNonZero(query_descriptors != query_descriptors_original) == 0);
        assert(cv::countNonZero(train_descriptors != train_descriptors_original) == 0);
    }
}

The output, although I don't think it will help(?), is

0,27
1,170
2,100
3,100
4,123
5,100
6,191
7,71
8,191
9,67
10,27
11,45
12,302
13,190
14,248
15,158
16,262
17,248
18,211
19,67
20,248
21,275

0,2
1,200
2,224
3,302
4,130
5,302
6,191
7,195
8,191
9,195
10,200
11,45
12,248
13,277
14,248
15,255
16,262
17,248
18,182
19,14
20,54
21,284

Solution

  • FLANN chooses between the randomized kd-tree algorithm and the hierarchical k-means tree algorithm to make the optimal nearest neighbors approximation. The choice of algorithm is based on several factors such as dataset structure and search precision. Each algorithm also has a set of parameters that effects the search performance.

    That means that it uses a random function to match, thats why you get different results each time ;)