diff --git a/modules/core/src/stat.cpp b/modules/core/src/stat.cpp index e43df94448..8a6bd54721 100644 --- a/modules/core/src/stat.cpp +++ b/modules/core/src/stat.cpp @@ -3826,6 +3826,11 @@ void cv::findNonZero( InputArray _src, OutputArray _idx ) Mat src = _src.getMat(); CV_Assert( src.type() == CV_8UC1 ); int n = countNonZero(src); + if( n == 0 ) + { + _idx.release(); + return; + } if( _idx.kind() == _InputArray::MAT && !_idx.getMatRef().isContinuous() ) _idx.release(); _idx.create(n, 1, CV_32SC2); diff --git a/modules/core/test/test_arithm.cpp b/modules/core/test/test_arithm.cpp index 14c741edc0..77a17b60bd 100644 --- a/modules/core/test/test_arithm.cpp +++ b/modules/core/test/test_arithm.cpp @@ -1791,3 +1791,13 @@ INSTANTIATE_TEST_CASE_P(Arithm, SubtractOutputMatNotEmpty, testing::Combine( testing::Values(perf::MatType(CV_8UC1), CV_8UC3, CV_8UC4, CV_16SC1, CV_16SC3), testing::Values(-1, CV_16S, CV_32S, CV_32F), testing::Bool())); + + +TEST(Core_FindNonZero, singular) +{ + Mat img(10, 10, CV_8U, Scalar::all(0)); + vector pts, pts2(10); + findNonZero(img, pts); + findNonZero(img, pts2); + ASSERT_TRUE(pts.empty() && pts2.empty()); +}