-2

I managed to do what I need with Python code I found on Stack Overflow:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
labelnum, labelimg, contours, GoCs = cv2.connectedComponentsWithStats(gray)
for label in xrange(1, labelnum):
    x,y,w,h,size = contours[label]
    if size <= N:
         img_white[y:y+h, x:x+w] = 0
cv2.imwrite("img_filter.png", img_white)

It managed to remove small areas (small blobs and particles) by accessing contours elements.

I want to do this in C++. Is it possible? I have found this function:

int connectedComponentsWithStats(InputArray image, OutputArray labels, OutputArray stats, OutputArray centroids, int connectivity=8, int ltype=CV_32S)

But I don't see how to access the contours elements. Any tip?

Jongware
  • 22,200
  • 8
  • 54
  • 100
AA10
  • 207
  • 1
  • 7

3 Answers3

1

The stats output array contains, amongst others, the CC_STAT_AREA column, which will give you the area in pixels of the connected component.

The code for filtering out components smaller than N would apply the condition if (stats.at<int>(label, CC_STAT_AREA) < N) {…}. Check the full example given in this post

Note that connected components will not give you the contours, just the connected region stats. You’ll need to use OpenCV’s findContours function in order to obtain the list of all points along a region’s contours.

M. F.
  • 1,654
  • 11
  • 16
  • If your label is different than 1 (3 for example), the output CC_STAT_AREA area is not constant. It varies every time I run the program. Is that normal? – AA10 Dec 18 '17 at 10:22
  • Not 100% sure, but it may be that the labels are not always assigned in the same order, except for the 1st one which always corresponds to the background. You can test this behavior by assigning a pseudo-color to each label and render the result for several runs of the algorithm. – M. F. Dec 18 '17 at 15:51
0

Maybe just erode your image should help.

Morphological Transformations OpenCV

0

You can use below code with good performance:

   Mat stats, centroids, labelImage, imshow_mat;
   int nLabels =
           connectedComponentsWithStats(bin_img, labelImage, stats, centroids, 4);
   Mat mask(labelImage.size(), CV_8UC1, Scalar(0));
   Mat surfSup=stats.col(4)>sz_min;

   int tmp_label;


   for (int i = 1; i < bin_img.rows; i++){
       for (int j = 1; j < bin_img.cols ; j++){

           tmp_label = labelImage.at<int>(i,j);

           mask.at<char>(i,j) = (char) surfSup.at<char>(tmp_label,0);

   }
   }

   Mat r(bin_img.size(), CV_8UC1, Scalar(0));

   bin_img.copyTo(r,mask);
Bashid
  • 433
  • 5
  • 15