Fix signed integer overflow in connected components

pull/18314/head
Gil Shotan 5 years ago
parent 03bee14372
commit 1612db5f91
  1. 21
      modules/imgproc/src/connectedcomponents.cpp
  2. 14
      modules/imgproc/test/test_connectedcomponents.cpp

@ -145,14 +145,21 @@ namespace cv{
void finish(){ void finish(){
for (int l = 0; l < statsv.rows; ++l){ for (int l = 0; l < statsv.rows; ++l){
int *row =& statsv.at<int>(l, 0); int *row =& statsv.at<int>(l, 0);
row[CC_STAT_WIDTH] = row[CC_STAT_WIDTH] - row[CC_STAT_LEFT] + 1;
row[CC_STAT_HEIGHT] = row[CC_STAT_HEIGHT] - row[CC_STAT_TOP] + 1;
Point2ui64& integral = integrals[l];
double *centroid = &centroidsv.at<double>(l, 0);
double area = ((unsigned*)row)[CC_STAT_AREA]; double area = ((unsigned*)row)[CC_STAT_AREA];
centroid[0] = double(integral.x) / area; double *centroid = &centroidsv.at<double>(l, 0);
centroid[1] = double(integral.y) / area; if (area > 0){
row[CC_STAT_WIDTH] = row[CC_STAT_WIDTH] - row[CC_STAT_LEFT] + 1;
row[CC_STAT_HEIGHT] = row[CC_STAT_HEIGHT] - row[CC_STAT_TOP] + 1;
Point2ui64& integral = integrals[l];
centroid[0] = double(integral.x) / area;
centroid[1] = double(integral.y) / area;
} else {
row[CC_STAT_WIDTH] = 0;
row[CC_STAT_HEIGHT] = 0;
row[CC_STAT_LEFT] = -1;
centroid[0] = std::numeric_limits<double>::quiet_NaN();
centroid[1] = std::numeric_limits<double>::quiet_NaN();
}
} }
} }

@ -225,5 +225,19 @@ TEST(Imgproc_ConnectedComponents, parallel_wu_labels)
EXPECT_EQ(nbPixels, area); EXPECT_EQ(nbPixels, area);
} }
TEST(Imgproc_ConnectedComponents, missing_background_pixels)
{
cv::Mat m = Mat::ones(10, 10, CV_8U);
cv::Mat labels;
cv::Mat stats;
cv::Mat centroids;
EXPECT_NO_THROW(cv::connectedComponentsWithStats(m, labels, stats, centroids, 8, CV_32S, cv::CCL_WU) );
EXPECT_EQ(stats.at<int32_t>(0, cv::CC_STAT_WIDTH), 0);
EXPECT_EQ(stats.at<int32_t>(0, cv::CC_STAT_HEIGHT), 0);
EXPECT_EQ(stats.at<int32_t>(0, cv::CC_STAT_LEFT), -1);
EXPECT_TRUE(std::isnan(centroids.at<double>(0, 0)));
EXPECT_TRUE(std::isnan(centroids.at<double>(0, 1)));
}
}} // namespace }} // namespace

Loading…
Cancel
Save