如何在opencv中查找图像中每个连通分量的边界像素

ATG*_*ATG 4 c matlab opencv

我有一个带文本的图像,我想找到每个连接组件的边界像素.我应该在opencv 2.3中使用哪种方法,我在c编码.这个函数可能就像matlab的bwboundaries一样.

谢谢,

car*_*eri 11

在OpenCV 2.3中,您想要的功能称为cv :: findContours.每个轮廓(它是连接组件的边界)存储为点矢量.以下是如何使用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]);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果您需要轮廓的完整层次结构,包括组件内部的孔等,则对findContours的调用如下所示:

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

注意:该参数CV_CHAIN_APPROX_SIMPLE表示轮廓中的直线段将由其端点编码.如果您希望存储所有轮廓点,请使用CV_CHAIN_APPROX_NONE.

编辑:在C中,您可以调用cvFindContours并访问这样的轮廓:

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);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

c->h_next指向与当前轮廓处于同一层级的下一个轮廓,并c->v_next指向当前轮廓内的第一个轮廓(如果有).当然,如果你CV_RETR_EXTERNAL像上面那样使用,c->v_next将永远如此NULL.