Search code examples
pythonopencvimage-processingimage-morphology

OpenCV dilate() function not closing the gaps in all directions


I'm trying to use the Python OpenCV cv2.dilate() function to close some gaps in my image. See the images below.

(1) Original image with the gaps to be closed.

enter image description here

(2) Dilated image with iterations=10

enter image description here

(3) Dilated image with iterations=100 and the supposed gaps that should be closed.

enter image description here

Why is dilate() keeping those gaps? Am I missing some configuration?

cv2.dilate(thresh, (3,3), iterations=dilate_interations)

Solution

  • You have to adjust your kernel size so that it contains at least a non-zero element on all parts of the image.

    This is from the OpenCV documentation:

    a pixel element is ‘1’ if at least one pixel under the kernel is ‘1’

    This means that if your kernel is too small, there may be some gaps in your image where the gap is wider than the kernel's size along any given direction. Note that I generated the kernel using numpy (I think you made a mistake when specifying your kernel). I tested your code with a kernel of (5,5) (instead of (3,3) ) and after a few iterations, it closed all the gaps in your image. The (3,3) you specified is seen as a kernel of size (1,2) and not as a 3x3 kernel of ones:

    import numpy as np
    
    kernel = np.ones((5,5),np.uint8)
    
    cv2.dilate(myImage,kernel,iterations = 5)