Skip to content

features: accept CV_Bool masks in SIFT detect (#25895) - #29679

Merged
asmorkalov merged 4 commits into
opencv:5.xfrom
Neal006:features/keypoint-bool-mask
Aug 14, 2026
Merged

asmorkalov merged 4 commits into
opencv:5.xfrom
Neal006:features/keypoint-bool-mask

Conversation

@Neal006

@Neal006 Neal006 commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Problem

cv::Mat_<bool>::depth() returns CV_Bool in 5.0, where it returned CV_8U in 4.x. SIFT_Impl::detectAndCompute gates the mask at sift.dispatch.cpp:980, so a boolean detection mask now fails with:

(-5:Bad argument) mask has incorrect type (!=CV_8UC1) in function 'cv::SIFT_Impl::detectAndCompute'

Fix

Allow CV_BoolC1 in that check, and update the message accordingly.

No conversion is needed. The mask is consumed by KeyPointsFilter::runByPixelsMask, whose MaskPredicate reads it with Mat::at<uchar>, and Mat::at only asserts that the element size matches (CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()). CV_Bool is one byte like CV_8U, so the existing read is already correct for a boolean mask.

That is also why FastFeatureDetector and SimpleBlobDetector, which have no explicit mask type check and route through the same predicate, already accepted boolean masks. The only thing standing in the way was SIFT's own check.

This follows the same approach goodFeaturesToTrack already uses in this module (featureselect.cpp:301 accepts CV_8UC1 || CV_BoolC1).

Test

Features2d_Detector_Keypoints_BoolMask.matches_uchar_mask builds a synthetic image with circles and rectangles, runs FAST, SIFT and SimpleBlobDetector with a Mat_<bool> mask and with the equivalent CV_8UC1 mask, and requires the same keypoints from each.

Verified locally on 5.x: the test fails without the change (SIFT throws the error above) and passes with it. FAST and SimpleBlobDetector are included to pin their already-working behaviour against future regressions. No test data needed, the test is synthetic.

Part of #25895.

Pull Request Readiness Checklist

  • I agree to contribute to the project under Apache 2 License.
  • 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
  • The PR is proposed to the proper branch
  • There is a reference to the original bug report and related work
  • There is accuracy test, performance test and test data in opencv_extra repository, if applicable
    Patch to opencv_extra has the same branch name.
  • The feature is well documented and sample code can be built with the project CMake

cv::Mat_<bool>::depth() returns CV_Bool in 5.0, where it returned CV_8U in
4.x, so SIFT::detect with a boolean mask now fails:

  (-5:Bad argument) mask has incorrect type (!=CV_8UC1)

Allow CV_BoolC1 in that check. No conversion is needed: the mask reaches
KeyPointsFilter::runByPixelsMask, whose MaskPredicate reads it with
Mat::at<uchar>, and Mat::at only asserts that the element size matches.
CV_Bool is one byte like CV_8U, so the existing read is already correct.

FAST and SimpleBlobDetector have no explicit mask type check and route
through the same predicate, so they already accepted boolean masks. The
test covers all three to keep that behaviour pinned.

Added a regression test comparing a Mat_<bool> mask against the equivalent
CV_8UC1 mask and requiring the same keypoints from each detector.
Copilot AI lite review requested due to automatic review settings August 8, 2026 11:07

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@Neal006

Neal006 commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor Author

@asmorkalov Both points addressed in 9a23bfe.

The test now reads features2d/tsukuba.png from opencv_extra, the same input the rest of test_keypoints.cpp already uses, with the mask covering the centre half of the image. The redundant comment above the test is gone.

Switching to a real image turned up something worth mentioning: your reliability concern was well founded. Once I added ASSERT_FALSE(kp_uchar.empty()) to make sure the reference mask actually selects keypoints, SimpleBlobDetector turned out to find nothing at all on tsukuba, so its bool-vs-uchar comparison had been passing vacuously on an empty vector. I removed it from the detector list, leaving FAST and SIFT, which both find plenty inside the masked region.

I briefly tried ORB as a third detector and it throws (-210:Unsupported format) from cv::threshold on a CV_Bool mask. That is a separate unfixed CV_Bool site rather than anything to do with SIFT, so I have left it out of this PR to keep the diff on topic. Happy to open a follow-up for it if useful.

Rebuilt and reran: the test passes, and the negative test is reconfirmed, without the sift.dispatch.cpp change it fails with mask has incorrect type (!=CV_8UC1) from SIFT_Impl::detectAndCompute.

Address review feedback: the synthetic test image was too small and had too
few features to exercise SIFT reliably, so switch to features2d/tsukuba.png
from opencv_extra, the input the rest of this file already uses.
Also drop the redundant comment above the test and assert that the reference
CV_8U mask actually yields keypoints, so the bool-vs-uchar comparison cannot
pass vacuously. SimpleBlobDetector finds nothing on tsukuba, so it is removed
from the detector list.
@Neal006
Neal006 force-pushed the features/keypoint-bool-mask branch from 04f4f7d to 9a23bfe Compare August 10, 2026 11:51
@asmorkalov

Copy link
Copy Markdown
Contributor

Please do not touch ORB for now. It builds pyramid of masks and does some other manipulations that are not supported for bool type yet.

@Neal006

Neal006 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@asmorkalov Understood, I will leave ORB alone and will not open the follow-up I mentioned.

To be clear about the current state of this PR: ORB is already out of it. I only tried it briefly as a third detector while switching to tsukuba, saw the throw, and removed it again before pushing, so 9a23bfe tests FAST and SIFT only. Nothing to revert here.

Thanks for the detail about the mask pyramid, that is useful. It explains that the cv::threshold throw I hit is only the first symptom rather than the whole story, so a type gate relax would not have been anywhere near sufficient. Good to know before spending time on it.

Thanks for the review and the approval.

Address review feedback: turn the loop over detectors into a value
parameterized test, one INSTANTIATE_TEST_CASE_P per detector, following
test_descriptors_invariance.cpp. The detector name now shows up in the
test case name, each detector runs as an independent iteration, and
adding another one is a single line.

The parameter is a factory function rather than a Ptr, for the reason
already noted in test_descriptors_invariance.impl.hpp: parameters live
for the whole test program run.
@Neal006

Neal006 commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

@asmorkalov , sorry for the delay, but I have done the fix for which you provided the friendly reminder earlier today.
Please, review and let me know what changes you would like me to make.
Thanks!

@asmorkalov

Copy link
Copy Markdown
Contributor

Build warnings:

    [1823/1824] Building CXX object modules/features/CMakeFiles/opencv_test_features.dir/test/test_keypoints.cpp.o
    In file included from /usr/include/c++/13/functional:59,
                     from /home/ubuntu/opencv/modules/core/include/opencv2/core/mat.hpp:57,
                     from /home/ubuntu/opencv/modules/core/include/opencv2/core.hpp:58,
                     from /home/ubuntu/opencv/modules/ts/include/opencv2/ts.hpp:10,
                     from /home/ubuntu/opencv/modules/features/test/test_precomp.hpp:7,
                     from /home/ubuntu/opencv/modules/features/test/test_keypoints.cpp:42:
    In copy constructor 'std::function<_Res(_ArgTypes ...)>::function(const std::function<_Res(_ArgTypes ...)>&) [with _Res = cv::Ptr<cv::Feature2D>; _ArgTypes = {}]',
        inlined from 'testing::internal::ValueArray1<T1>::ValueArray1(T1) [with T1 = std::function<cv::Ptr<cv::Feature2D>()>]' at /home/ubuntu/opencv/modules/ts/include/opencv2/ts/ts_gtest.h:12320:33,
        inlined from 'testing::internal::ValueArray1<T1> testing::Values(T1) [with T1 = std::function<cv::Ptr<cv::Feature2D>()>]' at /home/ubuntu/opencv/modules/ts/include/opencv2/ts/ts_gtest.h:17952:38,
        inlined from 'testing::internal::ParamGenerator<std::function<cv::Ptr<cv::Feature2D>()> > opencv_test::{anonymous}::gtest_SIFTFeatures2d_Detector_Keypoints_BoolMask_EvalGenerator_()' at /home/ubuntu/opencv/modules/features/test/test_keypoints.cpp:191:1:
    /usr/include/c++/13/bits/std_function.h:391:17: warning: '<anonymous>' may be used uninitialized [-Wmaybe-uninitialized]
      391 |             __x._M_manager(_M_functor, __x._M_functor, __clone_functor);
          |             ~~~~^~~~~~~~~~
    /usr/include/c++/13/bits/std_function.h: In function 'testing::internal::ParamGenerator<std::function<cv::Ptr<cv::Feature2D>()> > opencv_test::{anonymous}::gtest_SIFTFeatures2d_Detector_Keypoints_BoolMask_EvalGenerator_()':
    /usr/include/c++/13/bits/std_function.h:267:7: note: by argument 2 of type 'const std::_Any_data&' to 'static bool std::_Function_handler<_Res(_ArgTypes ...), _Functor>::_M_manager(std::_Any_data&, const std::_Any_data&, std::_Manager_operation) [with _Res = cv::Ptr<cv::Feature2D>; _Functor = opencv_test::{anonymous}::gtest_SIFTFeatures2d_Detector_Keypoints_BoolMask_EvalGenerator_()::<lambda()>; _ArgTypes = {}]' declared here
      267 |       _M_manager(_Any_data& __dest, const _Any_data& __source,
          |       ^~~~~~~~~~
    In file included from /home/ubuntu/opencv/modules/ts/include/opencv2/ts.hpp:128:
    /home/ubuntu/opencv/modules/ts/include/opencv2/ts/ts_gtest.h:17952:20: note: '<anonymous>' declared here
    17952 |   return internal::ValueArray1<T1>(v1);
          |                    ^~~~~~~~~~~~~~~~~~~
    In copy constructor 'std::function<_Res(_ArgTypes ...)>::function(const std::function<_Res(_ArgTypes ...)>&) [with _Res = cv::Ptr<cv::Feature2D>; _ArgTypes = {}]',
        inlined from 'testing::internal::ValueArray1<T1>::ValueArray1(T1) [with T1 = std::function<cv::Ptr<cv::Feature2D>()>]' at /home/ubuntu/opencv/modules/ts/include/opencv2/ts/ts_gtest.h:12320:33,
        inlined from 'testing::internal::ValueArray1<T1> testing::Values(T1) [with T1 = std::function<cv::Ptr<cv::Feature2D>()>]' at /home/ubuntu/opencv/modules/ts/include/opencv2/ts/ts_gtest.h:17952:38,
        inlined from 'testing::internal::ParamGenerator<std::function<cv::Ptr<cv::Feature2D>()> > opencv_test::{anonymous}::gtest_FASTFeatures2d_Detector_Keypoints_BoolMask_EvalGenerator_()' at /home/ubuntu/opencv/modules/features/test/test_keypoints.cpp:188:1:
    /usr/include/c++/13/bits/std_function.h:391:17: warning: '<anonymous>' may be used uninitialized [-Wmaybe-uninitialized]
      391 |             __x._M_manager(_M_functor, __x._M_functor, __clone_functor);
          |             ~~~~^~~~~~~~~~
    /usr/include/c++/13/bits/std_function.h: In function 'testing::internal::ParamGenerator<std::function<cv::Ptr<cv::Feature2D>()> > opencv_test::{anonymous}::gtest_FASTFeatures2d_Detector_Keypoints_BoolMask_EvalGenerator_()':
    /usr/include/c++/13/bits/std_function.h:267:7: note: by argument 2 of type 'const std::_Any_data&' to 'static bool std::_Function_handler<_Res(_ArgTypes ...), _Functor>::_M_manager(std::_Any_data&, const std::_Any_data&, std::_Manager_operation) [with _Res = cv::Ptr<cv::Feature2D>; _Functor = opencv_test::{anonymous}::gtest_FASTFeatures2d_Detector_Keypoints_BoolMask_EvalGenerator_()::<lambda()>; _ArgTypes = {}]' declared here
      267 |       _M_manager(_Any_data& __dest, const _Any_data& __source,
          |       ^~~~~~~~~~
    /home/ubuntu/opencv/modules/ts/include/opencv2/ts/ts_gtest.h:17952:20: note: '<anonymous>' declared here
    17952 |   return internal::ValueArray1<T1>(v1);
          |                    ^~~~~~~~~~~~~~~~~~~
    [1824/1824] Linking CXX executable bin/opencv_test_features

Fixes the -Wmaybe-uninitialized warnings GCC 13 reports on
test_keypoints.cpp. The warning comes from std::function's copy
constructor reading _M_functor out of the temporary that
testing::Values builds, and gtest copies the parameter several times
on the way into ParamGenerator.

The factories are captureless lambdas, so a plain function pointer
holds them. It is trivially copyable, there is no type-erased buffer
to warn about, and the test case line now prints the factory address
instead of a 64 byte hex dump of the std::function object.
@asmorkalov
asmorkalov merged commit 54b61d8 into opencv:5.x Aug 14, 2026
27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants