Ask Your Question

Revision history [back]

Another option is to detect the edges of the image and use this code to fill holes:

void fillEdgeImage(cv::Mat edgesIn, cv::Mat& filledEdgesOut) const
    cv::Mat edgesNeg = edgesIn.clone();

    cv::floodFill(edgesNeg, cv::Point(0,0), CV_RGB(255,255,255));
    bitwise_not(edgesNeg, edgesNeg);
    filledEdgesOut = (edgesNeg | edgesIn);


The only way a hole is filled is in a closed contour with holes. So, in the end, the diffference between the original (thresholded) image and the filled image are the holes, and this indicates which contours were closed and unfilled.

In your example image, the first contour will be filled, the others will stay the same.