1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-29 23:33:05 +04:00

Merge pull request #27582 from MaximSmolskiy:take_into_account_overflow_for_connected_components

Take into account overflow for connected components #27582

### Pull Request Readiness Checklist

Fix #27568 

The problem was caused by a label type overflow (`debug_example.npy` contains `92103` labels, that doesn't fit in the `CV_16U` (`unsigned short`) type). If pass `CV_32S` instead of `CV_16U` as `ltype` - everything will be calculated successfully

Added overflow detection to throw exception with a clear error message instead of strange segfault/assertion error

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
This commit is contained in:
Maxim Smolskiy
2025-07-29 13:10:01 +03:00
committed by GitHub
parent 07cf36cbb0
commit 615ceefd0c
2 changed files with 76 additions and 6 deletions
@@ -798,7 +798,47 @@ TEST(Imgproc_ConnectedComponents, 4conn_regression_21366)
}
}
TEST(Imgproc_ConnectedComponents, regression_27568)
{
Mat image = Mat::zeros(Size(512, 512), CV_8UC1);
for (int row = 0; row < image.rows; row += 2)
{
for (int col = 0; col < image.cols; col += 2)
{
image.at<uint8_t>(row, col) = 1;
}
}
for (const int connectivity : {4, 8})
{
for (const int ccltype : {CCL_DEFAULT, CCL_WU, CCL_GRANA, CCL_BOLELLI, CCL_SAUF, CCL_BBDT, CCL_SPAGHETTI})
{
{
Mat labels, stats, centroids;
try
{
connectedComponentsWithStats(
image, labels, stats, centroids, connectivity, CV_16U, ccltype);
ADD_FAILURE();
}
catch (const Exception& exception)
{
EXPECT_TRUE(
strstr(
exception.what(),
"Total number of labels overflowed label type. Try using CV_32S instead of CV_16U as ltype"));
}
}
{
Mat labels, stats, centroids;
EXPECT_NO_THROW(
connectedComponentsWithStats(
image, labels, stats, centroids, connectivity, CV_32S, ccltype));
}
}
}
}
}
} // namespace