如何使用opencv填充轮廓线?

时间:2015-11-11 06:16:41

标签: opencv

例如,这个矩形中心是洞。 (白色每个像素值= 255,黑色值= 0)

enter image description here

但是,我想填补这个漏洞。 (如下图所示)

enter image description here

如何使用OpenCV逐个矩形填充。

1 个答案:

答案 0 :(得分:2)

首先找到它的凸包,然后填充它的内部区域:

cv::Mat inputImage = cv::imread("input.jpg", CV_LOAD_IMAGE_GRAYSCALE);
cv::threshold(inputImage, inputImage, 10, 255, 0);

// find non-zero elements
cv::Mat nonZeroCoordinates;
cv::findNonZero(inputImage, nonZeroCoordinates);

cv::vector<cv::Point> points;
for (int i = 0; i < nonZeroCoordinates.total(); i++)
{
    points.push_back(nonZeroCoordinates.at<cv::Point>(i));
}

// Find convex hull
std::vector<int> hull;
cv::convexHull(cv::Mat(points), hull, false);

cv::vector<cv::Point> hullpoints;
int hullcount = (int)hull.size();

for (int i = 0; i < hullcount; i++)
{
    cv::Point pt = points[hull[i]];
    hullpoints.push_back(pt);
}

std::vector<std::vector<cv::Point> > fillContAll;
fillContAll.push_back(hullpoints);

cv::Mat result = cv::Mat::zeros(inputImage.size(), CV_8UC1);
cv::fillPoly(result, fillContAll, cv::Scalar(255));

鉴于您的原始图片:

enter image description here

这是你的最终结果:

enter image description here