Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

If you're sure you'll only have inner holes inside a well defined external object contour, then one option if to make use of findcontours(), taking advantage of hierarchy:

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;

int const smooth_kernel = 11;

int main()
{
    Mat src, srcGray, srcSmooth, srcThresh;
    src = imread("source.png", 1);

    cvtColor(src, srcGray, CV_BGR2GRAY);

    for (int i = 1; i < smooth_kernel; i = i + 2)
    {
        medianBlur(srcGray, srcSmooth, i);
    }

    threshold(srcSmooth, srcThresh, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

    //retrieve only external contours (also you can retrieve list and use hierarchy)
    vector<vector<Point>> contours;
    findContours(srcThresh, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
    Mat result(src.rows, src.cols, CV_8UC1, Scalar(0));
    drawContours(result, contours, 0, Scalar(255), -1);     //draw with filling

    imshow("Final", result);
    waitKey(0);

    return 0;
}

image description

If you're sure you'll only have inner holes inside a well defined external object contour, then one option if is to make use of findcontours(), taking advantage of hierarchy:

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;

int const smooth_kernel = 11;

int main()
{
    Mat src, srcGray, srcSmooth, srcThresh;
    src = imread("source.png", 1);

    cvtColor(src, srcGray, CV_BGR2GRAY);

    for (int i = 1; i < smooth_kernel; i = i + 2)
    {
        medianBlur(srcGray, srcSmooth, i);
    }

    threshold(srcSmooth, srcThresh, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

    //retrieve only external contours (also you can retrieve list and use hierarchy)
    vector<vector<Point>> contours;
    findContours(srcThresh, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
    Mat result(src.rows, src.cols, CV_8UC1, Scalar(0));
    drawContours(result, contours, 0, Scalar(255), -1);     //draw with filling

    imshow("Final", result);
    waitKey(0);

    return 0;
}

image description