Search code examples
c++opencvimage-processingcontour

OpenCV - Filling empty spaces in object using c++


How can I fill empty space of object in OpenCV ?

Let me clarify my question.
I have an image below

enter image description here

Now I want to fill all the gaps in the image like this :

enter image description here

in Matlab I have done it by convex hull, but I don't know how to do it in C++.

Thanks.


Solution

  • Try morphological operations. If you go this way, note, that you may vary either kernel size (increase to decrease number of iterations), or iterations (more iterations will eliminate empty space even if kernel is small), or both.

    cv::Mat img = cv::imread("cwyX5.jpeg");
    cv::imshow("image", img);
    
    cv::Size kernelSize(5, 5);
    cv::Mat kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, kernelSize);
    
    cv::Mat result;
    int iterations = 3;
    cv::morphologyEx(img, result, cv::MORPH_OPEN, kernel, cv::Point(-1,-1), iterations);
    
    cv::imshow("result", result);
    
    cv::waitKey();