Hello,
I would like to remove holes in an object after I apply threshold function. Right now, I am applying dilate function a few times, then the erode function. It does okay, but in some cases, it changes the shape of the object.
I also tried to use the MORPH_CLOSE, but I guess it is no good against big holes.
I tried with different element size and shape but none of them helped.
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
Mat src, srcGray, srcSmooth, srcThresh;
int morpho_elem = 1; // 0: MORPH_RECT, 1: MORPH_CROSS, 2: MORPH_ELLIPSE
int morpho_size = 3;
int morpho_qty = 9;
int const smooth_kernel = 11;
int main()
{
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);
int dilation_type;
if (morpho_elem == 0){ dilation_type = MORPH_RECT; }
else if (morpho_elem == 1){ dilation_type = MORPH_CROSS; }
else if (morpho_elem == 2) { dilation_type = MORPH_ELLIPSE; }
Mat dilationDst, erosionDst;
Mat element = getStructuringElement(dilation_type,
Size(2 * morpho_size + 1, 2 * morpho_size + 1),
Point(morpho_size, morpho_size));
// Apply the dilation operation
dilate(srcThresh, dilationDst, element);
for (int i = 1; i < morpho_qty; i++)
{
dilate(dilationDst, dilationDst, element);
}
// Apply the erosion operation
erode(dilationDst, erosionDst, element);
for (int i = 1; i < morpho_qty; i++)
{
erode(erosionDst, erosionDst, element);
}
imshow("Final", erosionDst);
cvWaitKey(0);
return 0;
}
Source image:
Binary image with holes:
Output of my attempt: