Fill the holes in OpenCV


Question

I have an edge map extracted from edge detection module in OpenCV (canny edge detection). What I want to do is to fill the holes in the edge map.

I am using C++, and OpenCV libraries. In OpenCV there is a cvFloodFill() function, and it will fill the holes with a seed (with one of the location to start flooding). However, I am trying to fill all the interior holes without knowing the seeds.(similar to imfill() in MATLAB)

Q1: how to find all the seeds, so that I could apply 'cvFloodFill()'?
Q2: how to implement a 'imfill()' equivalent?

Newbie in OpenCV, and any hint is appreciated.

1
33
10/3/2012 11:46:23 AM

Accepted Answer

According to the documentation of imfill in MATLAB:

BW2 = imfill(BW,'holes');

fills holes in the binary image BW. A hole is a set of background pixels that cannot be reached by filling in the background from the edge of the image.

Therefore to get the "holes" pixels, make a call to cvFloodFill with the left corner pixel of the image as a seed. You get the holes by complementing the image obtained in the previous step.

MATLAB Example:

BW = im2bw( imread('coins.png') );
subplot(121), imshow(BW)

% used here as if it was cvFloodFill
holes = imfill(BW, [1 1]);    % [1 1] is the starting location point

BW(~holes) = 1;               % fill holes
subplot(122), imshow(BW)

screenshot1 screenshot2

34
5/19/2017 9:48:55 PM

the cvDrawContours function has an option to fill the contours that you have drawn.

Here is a short example cvDrawContours( IplImage, contours, color, color, -1, CV_FILLED, 8 );

Here is the documentation

http://opencv.willowgarage.com/documentation/drawing_functions.html?highlight=cvdrawcontours#cvDrawContours

I guess you posted this a long time ago, but I hope it helps someone.

This is the source code (in C#):

        Image<Gray, byte> image = new Image<Gray, byte>(@"D:\final.bmp");
        CvInvoke.cvShowImage("image 1", image);

        var contours = image.FindContours();
        while (contours != null)
        {
            CvInvoke.cvDrawContours(image, contours, new Gray(255).MCvScalar, new Gray (255).MCvScalar, 0, -1, Emgu.CV.CvEnum.LINE_TYPE.CV_AA, new DPoint(0, 0));
            contours = contours.HNext;
        }
        CvInvoke.cvShowImage("image 2", image);

Result


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon