# Is it a bug in connectedComponentsWithStats?

As some demand, I want to get all small rectangle in this image

Of course, If you are old version. we can use findcontour and boundingRect to do such thing. But since we have connectedComponentsWithStats now, I try to use it to ease my life. This is my current try:

//OpenCV 3.3.1 project
#include<opencv.hpp>
#include<string>
using namespace std;
using namespace cv;

Mat highlight(Mat, Mat);
int main() {
for (int i = 0; i < mask.rows; i++) {
for (int j = 0; j < mask.cols; j++)
if ((i + j) % 2 == 0)
data[j] = 255;
}

Mat element = getStructuringElement(MORPH_RECT, Size(2,2));
Mat labels, stats, centroids;
stats.convertTo(stats, CV_8U);
Mat temImg = Mat(mask.size(), CV_8UC1, Scalar(0));

vector<Mat> rects;
for (int i = 1; i < nmask; i++) {
uchar* data = stats.ptr<uchar>(i);
rectangle(temImg, Rect(data[0], data[1], data[2], data[3]), Scalar(255));
}
imshow("temImg", temImg);

waitKey();
return 0;
}


I'm very confused, why I will get these rectangle??

Is it a bug in my code or a bug in the new function connectedComponentsWithStats?

edit retag close merge delete

Sort by » oldest newest most voted

I think problem is here :

int nmask = connectedComponentsWithStats(mask, labels, stats, centroids, 4, CV_16U);
stats.convertTo(stats, CV_8U);


when you convert in uchar some values are saturate because leftmost (or topmost) coordinate can be greater than 255 :

CC_STAT_LEFT

The leftmost (x) coordinate which is the inclusive start of the bounding box in the horizontal direction.
CC_STAT_TOP

The topmost (y) coordinate which is the inclusive start of the bounding box in the vertical direction.
CC_STAT_WIDTH

The horizontal size of the bounding box.
CC_STAT_HEIGHT

The vertical size of the bounding box.
CC_STAT_AREA

The total area (in pixels) of the connected component.


Don't convert in CV_8U :

int* data = stats.ptr<int>(i);

more

Official site

GitHub

Wiki

Documentation