如何使用opencv自动检测和填充封闭区域?

时间:2014-07-23 07:46:58

标签: opencv image-processing

我只有以下位图: original contours image 我要做的是自动填充轮廓,如下所示: filled 它类似于MS Painter中的填充功能。初始轮廓不会越过图像的边界。

我还没有好主意。 OpenCV中有没有方法可以做到这一点?或任何建议?

提前致谢!

2 个答案:

答案 0 :(得分:1)

可能Contours Hierarchy可能会帮助您实现这一目标,

您需要这样做,

  • 查找每个轮廓。
  • 检查每个轮廓的层次结构。
  • 基于层次结构将每个轮廓绘制为厚度为filled1的新Mat。

答案 1 :(得分:0)

如果你知道必须关闭区域,你可以只是水平扫描并保持边缘数:

// Assume image is an CV_8UC1 with only black and white pixels.
uchar white(255);
uchar black(0);
cv::Mat output = image.clone();

for(int y = 0; y < image.rows; ++y)
{
    uchar* irow = image.ptr<uchar>(y)
    uchar* orow = output.ptr<uchar>(y)
    uchar previous = black;
    int filling = 0;

    for(int x = 0; x < image.cols; ++x)
    {
       // if we are not filling, turn it on at a black to white transition
       if((filling == 0) && previous == black && irow[x] == white)
           ++filling ;

       // if we are filling, turn it off at a white to black transition
       if((filling != 0) && previous == white && irow[x] == black)
           --filling ;

       // write output image
       orow[x] = filling != 0 ? white : black;

       // update previous pixel
       previous = irow[x];
    }
}
相关问题