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,
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With