我需要在下面的图像中找到内孔的数量。我的最终要求是使用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,而且我只需要绘制内部黑洞而不是所有外部轮廓的边界。我的英语。
答案 0 :(得分:10)
使用层次结构尝试此代码可以正常使用。
这个想法很简单,只考虑没有孩子的轮廓。
那是
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();
结果: -