Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find boundary pixels of each connected component in an image in opencv

Tags:

c

opencv

matlab

I have an image with text and I want to find boundary pixels of every connected component.Which method should I use in opencv 2.3,I am coding in c. This function may be just like bwboundaries of matlab.

thanks,

like image 341
ATG Avatar asked Dec 22 '22 03:12

ATG


1 Answers

In OpenCV 2.3, the function you want is called cv::findContours. Each contour (which is the boundary of the connected component) is stored as a vector of points. Here's how to access the contours in C++:

vector<vector<Point> > contours;
cv::findContours(img, contours, cv::RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
for (size_t i=0; i<contours.size(); ++i)
{
    // do something with the current contour
    // for instance, find its bounding rectangle
    Rect r = cv::boundingRect(contours[i]);
    // ...
}

If you need the full hierarchy of contours, including holes inside components and so forth, the call to findContours is like this:

vector<vector<Point> > contours;
Hierarchy hierarchy;
cv::findContours(img, contours, hierarchy, cv::RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
// do something with the contours
// ...

Note: the parameter CV_CHAIN_APPROX_SIMPLE indicates that straight line segments in the contour will be encoded by their end-points. If instead you want all contour points to be stored, use CV_CHAIN_APPROX_NONE.

Edit: in C you call cvFindContours and access the contours like this:

CvSeq *contours;
CvMemStorage* storage;
storage = cvCreateMemStorage(0);
cvFindContours(img, storage, &contours, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
CvSeq* c;
for(c=contours; c != NULL; c=c->h_next)
{
    // do something with the contour
    CvRect r = cvBoundingRect(c, 0);
    // ...
}

c->h_next points to the next contour at the same level of the hierarchy as the current contour, and c->v_next points to the first contour inside the current contour, if there is any. Of course, if you use CV_RETR_EXTERNAL like above, c->v_next will always be NULL.

like image 174
carnieri Avatar answered Dec 24 '22 02:12

carnieri