我有这个源图像
我已经应用了二进制阈值来得到这个
我使用轮廓来区分具有子轮廓的轮廓和没有子轮廓的轮廓。结果图片是
但是如何计算每个绿色轮廓包含的子轮廓的数量?这是我用过的代码:-
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-1-我在最后添加了来自 Humam 的代码以检查它:
std::vector<int> number_of_inner_contours(contours.size(), -1);
int number_of_childs = 0;
for (size_t i = 0; i < contours.size(); i++)
{
int first_child_index = hierarchy[i][2];
if (first_child_index >= 0)
{
int next_child_index = hierarchy[first_child_index][0];
if (number_of_inner_contours[next_child_index]<0)
{
number_of_childs = number_of_inner_contours[next_child_index];
}
else
{
while (next_child_index >= 0)
{
next_child_index = hierarchy[next_child_index][0];
++number_of_childs;
}
number_of_inner_contours[i] = number_of_childs;
}
}
else
{
number_of_inner_contours[i] = 0;
}
cout << "\nThe contour[" << i << "] has " << number_of_inner_contours[i] << "child contours";
}
但我得到的输出是这样的:
The contour[456 ] has 0 child contours
The contour[457 ] has 0 child contours
The contour[458 ] has 0 child contours
The contour[459 ] has -1 child contours