Efficient way to remove holes in an object
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:
i wonder, what is your expectation finally. do you want to detect that there is two rectangular 2d object. and their corner points? also you can try the code here
@sturkmen In the end, I would like to detect objects in my picture and find their features like length, area etc.