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

I have an image with text and I want to find boundary pixels for each connected component. Which method should be used in opencv 2.3, I code in c. This function may be the same as bwboundaries from matlab.

thanks,

+4
source share
3 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 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 a complete outline hierarchy, including holes inside components, etc., the findContours call looks 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 CV_CHAIN_APPROX_SIMPLE parameter indicates that the straight line segments in the path will be encoded at their endpoints. If instead you want to save all contour points, use CV_CHAIN_APPROX_NONE .

Edit: in C, you call cvFindContours and gain access to such contours:

 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 path at the same hierarchy level as the current path, and c->v_next points to the first path inside the current path, if any. Of course, if you use CV_RETR_EXTERNAL as above, c->v_next will always be NULL .

+11
source

You can use cvFindContours (this is a version 1.0 call, but there should be a similar call in version 2.3)

+1
source

In OpenCV, such a function is not implemented. You should either look for morphological operations (sub-adjustments of your image and the same advanced ones), or take a look at cvbloblib http://opencv.willowgarage.com/wiki/cvBlobsLib

It was designed specifically for this purpose;).

-1
source

Source: https://habr.com/ru/post/1390432/


All Articles