Gap Filling Contours / Lines
Question: I have the following image:

![Image with gapped contours](http://i.stack.imgur.com/WhGXN.png)

and I would like to fill in its contours (i.e. I would like to gap fill the
lines in this image).

I have tried a morphological closing, but using a rectangular kernel of size
`3x3` with `10` iterations does not fill in the entire border. I have also
tried a `21x21` kernel with `1` iteration and also not had luck.

**UPDATE:**

I have tried this in OpenCV (Python) using:

    
    
    cv2.morphologyEx(img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (21,21)))
    

and

    
    
    cv2.morphologyEx(img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (3,3)), iterations=10)
    

and [scikit-image](http://scikit-
image.org/docs/dev/auto_examples/applications/plot_morphology.html):

    
    
    closing(img, square(21))
    

My end goal is to a have a filled version of that entire image without
distorting the area covered.


Answer: In the following snippet I calculate the distance map of the inverse image. I
threshold it to obtain a large outline of the current object, which I then
skeletonize to get the central line. This may already be enough for your
purposes. But to make it consistent with the line thickness given, I dilate
the skeleton and add it to the original, thereby closing any gaps. I also
remove the one remaining object touching the boundary.

![mind the gap](http://i.stack.imgur.com/uqg77.png)

    
    
    from skimage import io, morphology, img_as_bool, segmentation
    from scipy import ndimage as ndi
    import matplotlib.pyplot as plt
    
    image = img_as_bool(io.imread('/tmp/gaps.png'))
    out = ndi.distance_transform_edt(~image)
    out = out < 0.05 * out.max()
    out = morphology.skeletonize(out)
    out = morphology.binary_dilation(out, morphology.selem.disk(1))
    out = segmentation.clear_border(out)
    out = out | image
    
    plt.imshow(out, cmap='gray')
    plt.imsave('/tmp/gaps_filled.png', out, cmap='gray')
    plt.show()
    

