根据轮廓区域大小对轮廓进行分类的问题

时间:2019-09-23 09:26:05

标签: c++ opencv opencv-contour watershed

我正在分割岩石。为了比较细分结果,我:

  1. 找到分割图像的二值图像轮廓
  2. 找到轮廓区域
  3. 对区域进行排序
  4. 找到最大的n,并将其与基本事实进行比较

问题是:

->排序不给出n个最大的轮廓(例如5)。我不明白为什么。

这是输入图像:

Input Image

排序后的所有轮廓:

all contours

然后,前5个轮廓图像:

5 contours

我期望的结果只是最大轮廓的前5或n个。具体来说,第一大和第二大应该是rgb图像右侧的棕色大块岩石。

用于排序的代码来自page 417

我的代码(其中的一部分)显示了前5个轮廓,如下所示:

 // Sorting by descending order
struct AreaCmp {    
AreaCmp(const vector<float>& _areas) : areas(&_areas) {}    
bool operator()(int a, int b) const { return (*areas)[a] > (*areas)[b]; }   
 const vector<float>* areas;};


int main{

  std::vector<std::vector<cv::Point>> contours;
  std::vector<cv::Vec4i> hierarchy;// There is no hierarchy formed because of CV_RETR_LIST

  cv::findContours(input_image, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);//CV_CHAIN_APPROX_SIMPLE

  std::vector<int> sortIdx(contours.size());
  std::vector<float> areas(contours.size());

  for( int n = 0; n < (int)contours.size(); n++)
  {
      sortIdx[n] = n;
      areas[n] = cv::contourArea(contours[n], false);
  }

  std::sort(sortIdx.begin(), sortIdx.end(), AreaCmp(areas));

  FINROC_LOG_PRINT(DEBUG, "sortIdx size", (int)sortIdx.size());
  FINROC_LOG_PRINT(DEBUG, "contours size", (int)contours.size());

  int q = 0;
  for( int n = 0; n < (int)sortIdx.size(); n++)
  {
      int idx = sortIdx[n];
      cv::drawContours(input_rgb_image, contours, idx, cv::Scalar(0,255,0), 1, 8, hierarchy);
      q++;
      if(q > 5) break; // to draw only the first 5

  }
}

0 个答案:

没有答案