【问题标题】:Subtract all contours from image except the one with the largest area从图像中减去除面积最大的轮廓之外的所有轮廓
【发布时间】:2016-04-27 09:11:03
【问题描述】:
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)。只是带有白色区域的黑色背景。 谢谢。

【问题讨论】:

    标签: c++ opencv subtraction areas opencv-contour


    【解决方案1】:

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

    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);
        }
    }
    

    【讨论】:

    • 非常感谢!这正是我所需要的。
    【解决方案2】:

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

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 2012-11-15
      • 2021-01-05
      • 2020-02-15
      • 2019-12-24
      • 1970-01-01
      • 2014-11-20
      相关资源
      最近更新 更多