OpenCV has findContours() which used to find the contours in the image, So as a first step detect all the contours in the image, then decide whether the contour is closed or not by examining the hierarchy passed to the findContours() function. The hierarchy parameter return the contour property like whether contour contain child contours, the level of hierarchy etc.
For Example if we define hierarchy like,
vector< Vec4i > hierarchy
and the property for the
hierarchy will looks
hierarchy[i][0] = next contour at the same hierarchical level
hierarchy[i][1] = previous contour at the same hierarchical level
hierarchy[i][2] = denotes its first child contour
hierarchy[i][3] = denotes index of its parent contour
And for a contour,
ifthere
is no next, previous, parent, or nested contours, the elements ofhierarchy[i]
will be negative.
So by checking the value hierarchy[i][2]
you can decide the contour is closed or open,
Simply if a contour hierarchy[i][2] = -1
, and no child then its opened contour.
And one more points to note that in findContours() function we should use
CV_RETR_CCOMP which retrieves all of the contours and organises them
into a two-level hierarchy.
Here is the C++ code.
Mat tmp,thr;
Mat src=imread("src.png",1);
cvtColor(src,tmp,CV_BGR2GRAY);
threshold(tmp,thr,200,255,THRESH_BINARY_INV);
vector< vector <Point> > contours;
vector< Vec4i > hierarchy;
findContours( thr, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
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) //Check if there is a child contour
rectangle(src,Point(r.x-10,r.y-10), Point(r.x+r.width+10,r.y+r.height+10), Scalar(0,0,255),2,8,0); //Opened contour
else
rectangle(src,Point(r.x-10,r.y-10), Point(r.x+r.width+10,r.y+r.height+10), Scalar(0,255,0),2,8,0); //closed contour
}
No comments:
Post a Comment