From 48b5dedb0b2bd15f4e99e4b4da18a6d2f2561309 Mon Sep 17 00:00:00 2001 From: Troels Ynddal Date: Tue, 6 Feb 2024 15:53:36 +0100 Subject: [PATCH] Merge pull request #3632 from troelsy:4.x Fix a bug in knnMatchConvert when a feature couldn't be matched #3632 After I started using a mask with `knnMatchAsync`, I found that the result from `knnMatchConvert` would be clipped at random. Investigating the issue, I found that `knnMatchAsync` will initialize all `trainIdx` to `-1`, which will be overwritten by the CUDA kernel. A mask can be used to prevent certain features from being matched and this will prevent the CUDA kernel from setting the match distance. `knnMatchConvert` is not properly incrementing the pointers when `trainIdx == -1`, so an unmatched feature will get it stuck at `if (trainIdx == -1)`. Eventually the outer for-loop finishes and returns a vector with the matches up until the first missing match distance. My solution is to increment the counters the same way as a successful iteration would. ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [x] There is a reference to the original bug report and related work - [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [x] The feature is well documented and sample code can be built with the project CMake --- .../cudafeatures2d/src/brute_force_matcher.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/modules/cudafeatures2d/src/brute_force_matcher.cpp b/modules/cudafeatures2d/src/brute_force_matcher.cpp index 87316846d..d6e4618d6 100644 --- a/modules/cudafeatures2d/src/brute_force_matcher.cpp +++ b/modules/cudafeatures2d/src/brute_force_matcher.cpp @@ -791,15 +791,13 @@ namespace for (int i = 0; i < k; ++i) { const int trainIdx = *trainIdxPtr; - if (trainIdx == -1) - continue; - - const int imgIdx = imgIdxPtr ? *imgIdxPtr : 0; - const float distance = *distancePtr; - - DMatch m(queryIdx, trainIdx, imgIdx, distance); - - curMatches.push_back(m); + if (trainIdx != -1) + { + const int imgIdx = imgIdxPtr ? *imgIdxPtr : 0; + const float distance = *distancePtr; + DMatch m(queryIdx, trainIdx, imgIdx, distance); + curMatches.push_back(m); + } ++trainIdxPtr; ++distancePtr;