counting the number of child contours inside a contour in opencv
I have a source image
and I have applied binary thresholding to get this,to get
I used contours to differentiate between the ones having child contours and ones that don't.The resultant pic is
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);
For myself, I always use this tutorial on hierarchy to make sure I call the right child contours!
I actually don't need to find the call a particular child contours . I just need to get their total count
@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...