Skip to content

Commit 18440c1

Browse files
committed
Merge pull request opencv#18314 from gilsho:components
2 parents 9f69ca5 + 1612db5 commit 18440c1

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

modules/imgproc/src/connectedcomponents.cpp

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -145,14 +145,21 @@ namespace cv{
145145
void finish(){
146146
for (int l = 0; l < statsv.rows; ++l){
147147
int *row =& statsv.at<int>(l, 0);
148-
row[CC_STAT_WIDTH] = row[CC_STAT_WIDTH] - row[CC_STAT_LEFT] + 1;
149-
row[CC_STAT_HEIGHT] = row[CC_STAT_HEIGHT] - row[CC_STAT_TOP] + 1;
150-
151-
Point2ui64& integral = integrals[l];
152-
double *centroid = &centroidsv.at<double>(l, 0);
153148
double area = ((unsigned*)row)[CC_STAT_AREA];
154-
centroid[0] = double(integral.x) / area;
155-
centroid[1] = double(integral.y) / area;
149+
double *centroid = &centroidsv.at<double>(l, 0);
150+
if (area > 0){
151+
row[CC_STAT_WIDTH] = row[CC_STAT_WIDTH] - row[CC_STAT_LEFT] + 1;
152+
row[CC_STAT_HEIGHT] = row[CC_STAT_HEIGHT] - row[CC_STAT_TOP] + 1;
153+
Point2ui64& integral = integrals[l];
154+
centroid[0] = double(integral.x) / area;
155+
centroid[1] = double(integral.y) / area;
156+
} else {
157+
row[CC_STAT_WIDTH] = 0;
158+
row[CC_STAT_HEIGHT] = 0;
159+
row[CC_STAT_LEFT] = -1;
160+
centroid[0] = std::numeric_limits<double>::quiet_NaN();
161+
centroid[1] = std::numeric_limits<double>::quiet_NaN();
162+
}
156163
}
157164
}
158165

modules/imgproc/test/test_connectedcomponents.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,5 +225,19 @@ TEST(Imgproc_ConnectedComponents, parallel_wu_labels)
225225
EXPECT_EQ(nbPixels, area);
226226
}
227227

228+
TEST(Imgproc_ConnectedComponents, missing_background_pixels)
229+
{
230+
cv::Mat m = Mat::ones(10, 10, CV_8U);
231+
cv::Mat labels;
232+
cv::Mat stats;
233+
cv::Mat centroids;
234+
EXPECT_NO_THROW(cv::connectedComponentsWithStats(m, labels, stats, centroids, 8, CV_32S, cv::CCL_WU) );
235+
EXPECT_EQ(stats.at<int32_t>(0, cv::CC_STAT_WIDTH), 0);
236+
EXPECT_EQ(stats.at<int32_t>(0, cv::CC_STAT_HEIGHT), 0);
237+
EXPECT_EQ(stats.at<int32_t>(0, cv::CC_STAT_LEFT), -1);
238+
EXPECT_TRUE(std::isnan(centroids.at<double>(0, 0)));
239+
EXPECT_TRUE(std::isnan(centroids.at<double>(0, 1)));
240+
}
241+
228242

229243
}} // namespace

0 commit comments

Comments
 (0)