4

I am doing a c++ program and as part of my program, I need to perform a filling operation on a GRAYSCALE image which is similar to Matlab's imfill function (http://www.mathworks.com/help/images/ref/imfill.html).

I tried searching the internet for sample codes in c++ which does this and uses OpenCV libraries, but I only found codes which does something equivalent to Matlab's imfill for BINARY images (Fill the holes in OpenCV and Filling holes inside a binary object).

Is there anyway to perform something similar to imfill for GRAYSCALE images using only OpenCV? If not, are there other open-source libraries I can use to fill holes in grayscale images in c++ without knowing the seeds?

Community
  • 1
  • 1
  • [floodFill](http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#floodfill) works on grayscale, or even color, images. I have not used it with a mask (hence the comment) but if you add the tag [tag:opencv] I'm sure you'll find someone who has. – beaker Sep 01 '15 at 17:14
  • I didn't notice that I haven't put on an opencv tag! Thanks for telling me :) – EndlessParadox Sep 01 '15 at 17:44
  • 5
    Maybe show a before and after image too. – Mark Setchell Sep 01 '15 at 18:51
  • 1
    Greyscale filling is essentially "threshold input image, binary fill, apply mask to original input image". – MSalters Sep 02 '15 at 09:59

1 Answers1

0

See @MSalters comment for the correct answer.

You need some logic or criteria that determines what pixels are considered holes and which aren't. This is used to produce the Binary image(where '0' is the value of non hole pixels and '255' (1 in Matlab world) is the value of hole pixels) which can be used to fill every hole. Then simply add the threshold image to So basically there will always be a binary image to decide where to fill the holes, derived from a grayscale image that happens to be the source.

An example in C++:

    Mat GrayImage; // INPUT grayscale image
    Mat ThresholdImage; // binary mask image
    Mat DrawImage; // OUTPUT filled image
    GrayImage.copyTo(DrawImage);

    // create a mask where to fill
    int thresh = 90;
    cv::threshold(GrayImage, ThresholdImage, thresh, 255, cv::ThresholdTypes::THRESH_BINARY);

    int fillvalue = 120;
    bitwise_and(GrayImage, Scalar(0), DrawImage, ThresholdImage);
    bitwise_or(DrawImage, Scalar(fillvalue), DrawImage, ThresholdImage);
    // BONUS logically equivalent operation of the above two lines
    //bitwise_or(GrayImage, Scalar(255), DrawImage, ThresholdImage);
    //bitwise_and(DrawImage, Scalar(fillvalue), DrawImage, ThresholdImage);

    imshow("grayimage", GrayImage);
    imshow("thresholdimage", ThresholdImage);
    imshow("drawimage", DrawImage);

See the following links for various ways of implementing criteria to determine holes.

Reference 1

Reference 2

OpenCV Documentation

Community
  • 1
  • 1
Benjamin-M-Dale
  • 131
  • 1
  • 6