从图像中减去除面积最大的轮廓之外的所有轮廓

Subtract all contours from image except the one with the largest area

本文关键字:轮廓 图像      更新时间:2023-10-16
cv::Mat thr;
std::vector<std::vector<cv::Point> > contours;
std::vector<std::vector<cv::Vec4i> > hierarchy;
int largest_area          = 0;
int largest_contour_index = 0;
cv::findContours( thr, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image
for( int i = 0; i < contours.size(); i++ )                                           // iterate through each contour.
{
   double a = contourArea( contours[i], false );                                        // Find the area of contour
   if(a > largest_area)
   {
      largest_area          = a;
      largest_contour_index = i;                                                    // Store the index of largest contour
   }
}

找到最大等高线的索引后该怎么办?如何删除所有其他轮廓及其内部区域?图像是二进制的(cv::Mat thr)。只有黑色背景与白色区域。谢谢。

在您的情况下,删除轮廓及其内部区域等于将其填充为黑色。这可以通过用黑色绘制轮廓区域来完成:

for (size_t i=0; i<contours.size(); ++i) {
    if (i != largest_contour_index) { // not the largest one
        cv::drawContours(thr, contours, i, cv::Scalar(0,0,0), CV_FILLED);
    }
}

找到轮廓后,找到最大轮廓的索引并在垫子上绘制该轮廓。

int indexOfBiggestContour = -1;
int sizeOfBiggestContour = 0;
for (int i = 0; i < contours.size(); i++)
{
    if (contours[i].size() > sizeOfBiggestContour)
    {
        sizeOfBiggestContour = contours[i].size();
        indexOfBiggestContour = i;
    }
}
cv::Mat newImage;
drawContours(newImage, contours, indexOfBiggestContour, Scalar(255), CV_FILLED, 8, hierarchy);