counting the number of child contours inside a contour in opencv

asked 2016-08-02 06:14:26 -0500

avpai gravatar image

updated 2016-08-02 06:14:55 -0500

I have a source image

image description

and I have applied binary thresholding to get this,to get

image description

I used contours to differentiate between the ones having child contours and ones that don't.The resultant pic is

image description

But how do I count the number of child contours that each green contour contains (the red ones inside th green)?. This is code I have used:-

Mat binMask = lung;// the thresholded image
Mat lung_src = imread("source.tiff");// the source image
 //imshow("bin mask", binMask);
  vector<std::vector<cv::Point>> contours;
  vector<cv::Vec4i> hierarchy;
    int count = 0, j;

     double largest_area = 0;
        int largest_contour_index = 0;

  findContours(binMask, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));

       for (int i = 0; i < contours.size(); i++)
         {
double a = contourArea(contours[i], false);  //  Find the area of contour
if (a>largest_area)
{
    largest_area = a;
    largest_contour_index = i;
}
for (j = 0; j <= i; j++)
{
    if (hierarchy[j][2] != -1) // means it has child contour
    {

            drawContours(lung_src, contours, j, Scalar(0, 255, 0), 1, 8, hierarchy, 0, Point());

    }           
    else  // means it doesn't have any child contour
    {
        drawContours(lung_src, contours, j, Scalar(0, 0, 255), 1, 8, hierarchy, 0, Point());
    }
     }
  }
     drawContours(lung_src, contours, largest_contour_index, Scalar(255, 0, 0), 1, 8, hierarchy, 0, Point());
     imshow("lung-mapped", lung_src);
edit retag flag offensive close merge delete

Comments

For myself, I always use this tutorial on hierarchy to make sure I call the right child contours!

StevenPuttemans gravatar imageStevenPuttemans ( 2016-08-03 04:45:28 -0500 )edit

I actually don't need to find the call a particular child contours . I just need to get their total count

avpai gravatar imageavpai ( 2016-08-03 23:47:38 -0500 )edit

@avpai, if you get them one by one, then you can call them all right? You just have to check for nodes with a parent but no children nodes. Those will be your red blobs...

StevenPuttemans gravatar imageStevenPuttemans ( 2016-08-04 02:42:47 -0500 )edit