Search code examples
pythonopencvscikit-learnimage-segmentationscikit-image

Clean up unlabeled pixels in image segmentation


I have image segmentation results that look like this:

enter image description here

As you can see there are small gaps in the segmentation map. These gap pixels have been assigned the value 0; all other, non-gap pixels have been assigned a non-0 class value.

Is there a method, perhaps somewhere in skimage, which can perform something like k-nearest interpolation on just the null pixels, in order to assign them a value coherent with their neighborhood? I tried writing this function myself, but it too slow for my tastes.


Solution

  • You can use opencv's morphological closing operation.(reference: Link)

    I tried to perform the same operation on your image:

    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    
    img = plt.imread('image path')
    plt.imshow(img)
    

    orignal image

    kernel = np.ones((5,5),dtype='uint8')
    closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel,iterations=1)
    plt.imshow(closing)
    

    output

    You can play with kernel size and number of iterations. For small images kernel size of 3 or 5 would be find. You can increase the number of iterations to close bigger holes.