c++ - 识别开放和封闭的形状opencv

标签 c++ opencv image-processing shape-recognition

如何在 opencv 中检测开放和封闭的形状。

enter image description here

这些是我想要检测的简单样本形状。我使用 findContoursapproxPolyDP 检测到矩形,而不是检查 vector 之间的角度。

现在我想检测开放形状,approxPolyDP 函数将封闭形状的 bool 设置为 true,并且在返回的点上检查 isCounterConvex,加上 contourArea 限制。

我应该如何继续检测此类图像的任何想法。

最佳答案

只需使用 findContours()在您的图像中,然后通过检查传递给 findContours() 函数的层次结构来确定轮廓是否闭合。从第二幅图中可以清楚地看出,与第一幅图像相比,没有轮廓具有子轮廓,您将从层次参数中获得此数据,该参数是可选的输出 vector ,包含有关图像拓扑的信息。它的元素与轮廓的数量一样多。

这里我们将使用层次结构作为

vector< Vec4i > hierarchy

第 i 个轮廓的位置

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

如果轮廓 i 没有下一个、上一个、父级或嵌套轮廓,则 hierarchy[i] 的相应元素将为负数。见 findContours()功能了解更多详情。

所以通过检查 hierarchy[i][2] 的值,您可以确定轮廓是否属于闭合,即如果 hierarchy[i][2] = -1 那么没有 child ,它属于打开的。

还有一件事是,在 findContours() 函数中,您应该使用 CV_RETR_CCOMP 检索所有轮廓并将它们组织成两级层次结构。

这是如何实现这一点的 C++ 代码。

    Mat tmp,thr;
    Mat src=imread("1.png",1);
    cvtColor(src,tmp,CV_BGR2GRAY);
    threshold(tmp,thr,200,255,THRESH_BINARY_INV);

    vector< vector <Point> > contours; // Vector for storing contour
    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
    }

结果:

enter image description here

关于c++ - 识别开放和封闭的形状opencv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22240746/

相关文章:

c++ - opencv中拼接人脸问题

python - 使用 OpenCV 和 Python 检测接触/重叠的圆/椭圆

.net - 至少有潜在危险的错误,你会怎么做?

ios - OpenCV 以像素为单位获取坐标/半径

c++ - IplImage 的 cvLoadImage 工作,但 cv::Mat 的 cv::imread 不工作

c++ - 用什么代替 C++ Qt 上的 glob?

c++ - 如何提高OpenCV模板跟踪精度?使用什么参数?

c++ - 在 C++ 中使用指针引用替换数组元素

c++ - 检测音频输出+语音合成库的建议

c++ - 在频域中过滤图像