4

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
cdmh
  • 3,294
  • 2
  • 26
  • 41
  • I am stuck at almost similar problem, I am using flannbased knn match.(opencv 3.1) for finding matching for image stitching. If I am using 3 images, it gives same set of result for each image pair. If I run the same code for 4 images, knn_matches for previous exiting pair gets changed, but same on each rerun. Can you explain why – Garvita Tiwari Nov 21 '16 at 06:10
  • i wonder if you can solve this issue. I get this issue too –  Dec 25 '18 at 02:48

1 Answers1

5

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 ;)

Øystein W.
  • 517
  • 3
  • 16
  • Thanks for the confirmation. I understood the approximation to be stable with consistent descriptors, and not random. Makes sense now. – cdmh May 01 '14 at 11:41