Implement imfill matlab in c++ and opencv

asked 2014-02-03 05:28:14 -0500

vsay gravatar image

updated 2014-02-03 05:40:18 -0500

Hi I am very new with opencv and c++. I tested some functions with Matlab.

In matlab, I used imfill (BW2 = imfill(BW,'holes')) to the image to fill the holes of the images.

I searched in this forum and I encountered this question Fill holes of a binary image; the accepted answer by HD_Mouse. His Answer :

cv::threshold(image, image_thresh, 125, 255, cv::THRESH_BINARY);
// Loop through the border pixels and if they're black, floodFill from there
cv::Mat mask;
image_thresh.copyTo(mask);
for (int i = 0; i < mask.cols; i++) {
    if (mask.at<char>(0, i) == 0) {
        cv::floodFill(mask, cv::Point(i, 0), 255, 0, 10, 10);
    }   
    if (mask.at<char>(mask.rows-1, i) == 0) {
        cv::floodFill(mask, cv::Point(i, mask.rows-1), 255, 0, 10, 10);
    }
}
for (int i = 0; i < mask.rows; i++) {
    if (mask.at<char>(i, 0) == 0) {
        cv::floodFill(mask, cv::Point(0, i), 255, 0, 10, 10);
    }
    if (mask.at<char>(i, mask.cols-1) == 0) {
        cv::floodFill(mask, cv::Point(mask.cols-1, i), 255, 0, 10, 10);
    }
}


// Compare mask with original.
cv::Mat newImage;
image.copyTo(newImage);
for (int row = 0; row < mask.rows; ++row) {
    for (int col = 0; col < mask.cols; ++col) {
        if (mask.at<char>(row, col) == 0) {
            newImage.at<char>(row, col) = 255;
        }           
    }
}

Instead of using this binarisation

cv::threshold(image, image_thresh, 125, 255, cv::THRESH_BINARY);

I use otsu binarisation from this source

http://kristou.com/2009/08/25/opencv-otsu-thresholding/

I applied this to my image but only some holes are fill while others holes are not filled. I think it might be because of the binarisation. Any idea?? Thank

edit retag flag offensive close merge delete

Comments

Please, if you want people to compare, supply your own full code also. It could be that the problem lies somewhere else then pure on the otsu thresholding.

StevenPuttemans gravatar imageStevenPuttemans ( 2014-02-05 04:44:23 -0500 )edit