Find continuous area without narrow bottlenecks using OpenCV

985 views Asked by At

I want to get the contours of a continues area, but without having very narrow places in the output.

The input image can look like this image (after applying the threshold):Input image

By just calling OpenCVs findContours method, I get following result:Actual output

My problem is that I don't want to have the narrow (white) peaks in the result. Just blurring the image will not work, because I must not include the black peak(s). So the wanted output should look like this green line: Ideal output

Is it possible the tell OpenCV (findContours) a minimum "thickness" of the area?

2

There are 2 answers

0
ilke444 On BEST ANSWER

Erosion can be thought as adding the boundary pixels to the background. Thus, it gets rid of such narrow pieces in your input. However, since it distorts all the boundaries, you need to apply dilation afterwards, to undo the effect of erosion on the actual boundary. The erosion+dilation process is called opening.

The code portion below generates the desired output. Play with k_size according to your image size. Then apply findContours.

# Read and binarize the image
image = cv2.imread("test.png",cv2.IMREAD_GRAYSCALE)
ret, im_th =cv2.threshold(image,150,255,cv2.THRESH_BINARY)

# Set the kernel and perform opening
k_size = 7
kernel = np.ones((k_size,k_size),np.uint8)
opened = cv2.morphologyEx(im_th, cv2.MORPH_OPEN, kernel)
cv2.imwrite("opened.png", opened)

The output:

Opened output with no islands

0
bobo On

Use erosion, followed by dilation with a small kernel before you do findContours. There's a special kind of operator in OpenCV that does just that, called Opening with morphologyEx

Something like this should work:

morphologyEx(src, dst, MORPH_OPEN, Mat());