2

for example, this rectangle center is hole. (white each pixel value = 255, black value = 0)

enter image description here

but, I want to fill this hole. (like picture below)

enter image description here

how to fill hole by rectangle using OpenCV.

warl0ck
  • 3,356
  • 4
  • 27
  • 57
Geun Mo Lee
  • 111
  • 2
  • 12
  • Python, C++ or Java? – rayryeng Nov 11 '15 at 07:01
  • This is called region filling, if you are on matlab then this might help you: http://www.mathworks.com/matlabcentral/answers/111131-how-to-fill-the-region-of-interest-by-white-color – mumair Nov 11 '15 at 07:29
  • same problem answered here: http://stackoverflow.com/questions/1716274/fill-the-holes-in-opencv – mumair Nov 11 '15 at 07:30

1 Answers1

4

First find its convex hull, then fill in the inner region of it:

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));

Given your original image:

enter image description here

This is your final result:

enter image description here