【问题标题】:How to find No of inner Holes using cv::findcontours and hierarchy如何使用 cv::findcontours 和层次结构查找内孔数
【发布时间】:2013-12-27 19:59:43
【问题描述】:

我需要在下图中找到内孔的数量。即我的最终要求是仅使用opencv中的轮廓层次结构来检测和找到圆形黑洞的区域。不需要使用任何其他算法。

基于此链接Using hierarchy in findContours () in OpenCV? 我尝试了但它不起作用。

有没有其他方法可以找到图像中的孔数?

这里我附上了示例图像和代码。任何人都可以提出想法单独使用层次结构找到内部黑洞。我在轮廓层次结构方面没有太多经验。提前致谢。 我使用了opencv c++ lib。

cv::Mat InputImage = imread("New Image.jpg");
int Err;

if(InputImage.empty() == 1)
{
    InputImage.release();
    cout<<"Error:Input Image Not Loaded"<<endl;
    return 1;
}
cv::Mat greenTargetImage;

std::vector<cv::Mat> Planes;
cv::split(InputImage,Planes);

greenTargetImage = Planes[1];
cv::Mat thresholdImage = cv::Mat (greenTargetImage.size(),greenTargetImage.type());
cv::threshold(greenTargetImage,thresholdImage,128,255,THRESH_OTSU);
imwrite("thresholdImage.jpg",thresholdImage);

std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(thresholdImage,contours,hierarchy,cv::RETR_CCOMP,cv::CHAIN_APPROX_SIMPLE,cv::Point(-1,-1));
cout<<contours.size()<<endl;
cout<<hierarchy.size()<<endl;
int count = 0;
if (!contours.empty() && !hierarchy.empty())
{
    for (int i = 0;i<contours.size();i++ )
    {
        if ( hierarchy[i][3] != -1)
        {
            cv::drawContours(InputImage,contours,i,CV_RGB(0,255,0),3);
            count = count+1;
        }
    }   
}
cout<<count<<endl; //No of inner holes in same level  
imwrite("ContourImage.jpg",InputImage);

应用此代码后,我得到的输出计数值为 11。但我的要求是计数值应为 10,而且我只需要单独绘制内部黑洞,而不是外部轮廓的所有边界。对不起我的英语。

【问题讨论】:

  • 使用该图像,可以使用填充算法来完成。给定您问题中的图像,预期的输出是什么?另外,可以处理什么样的图像?
  • 我的要求是单独检测和计数内部黑洞(只有圆形)

标签: c++ opencv image-processing


【解决方案1】:

使用层次结构试试这个代码对我来说很好。

这个想法很简单,只要考虑没有孩子的轮廓。

那是

hierarchy[i][2]= -1

代码:-

  Mat tmp,thr;
  Mat src=imread("img.jpg",1);
  cvtColor(src,tmp,CV_BGR2GRAY);
  threshold(tmp,thr,200,255,THRESH_BINARY_INV);
  namedWindow("thr",0);
  imshow("thr",thr);

   vector< vector <Point> > contours; // Vector for storing contour
   vector< Vec4i > hierarchy;
   Mat dst(src.rows,src.cols,CV_8UC1,Scalar::all(0)); //create destination image
   int count=0;

   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=hierarchy[i][0] ) // iterate through each contour.
      {   
        Rect r= boundingRect(contours[i]);
        if(hierarchy[i][2]<0){
            rectangle(src,Point(r.x,r.y), Point(r.x+r.width,r.y+r.height), Scalar(0,0,255),3,8,0);
            count++;
        }
      }
  cout<<"Numeber of contour = "<<count<<endl;
  imshow("src",src);
  imshow("contour",dst);
  waitKey();

结果:-

【讨论】:

    猜你喜欢
    • 2017-05-24
    • 2016-09-04
    • 2012-01-17
    • 2014-05-16
    • 1970-01-01
    • 2016-09-21
    • 2019-03-10
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多