pythonimage-morphology

Delete single pixels in binary image


Suppose I have a binary image, represented as a numpy matrix where a pixel is either background (0) or foreground (1). I'm looking for a way, to delete all pixels in the foreground, that don't have any nearest neighbour.

Suppose, the image matrix is:

a = np.array([[0,0,1,1],[1,0,0,0]])

The resulting image after single pixel deletion should be

b = np.array([[0,0,1,1],[0,0,0,0]])

My approach so far is doing a combination of openings for all possible directions:

opening1 = ndi.morphology.binary_opening(edge, structure=np.array([[0,1,0],[0,1,0],[0,0,0]]))
opening2 = ndi.morphology.binary_opening(edge, structure=np.array([[0,0,0],[0,1,1],[0,0,0]]))
opening3 = ndi.morphology.binary_opening(edge, structure=np.array([[1,0,0],[0,1,0],[0,0,0]]))
opening4 = ndi.morphology.binary_opening(edge, structure=np.array([[0,0,0],[0,1,0],[0,0,1]]))

opening = opening1 + opening2 + opening3 + opening4

An alternative way would be labeling connected components and delete them by index, however those solutions feel sub-optimal when it comes to computational complexity.


Solution

  • Actually, labelling connected components seems to be the way to go. At least this is how skimage is doing it in the remove_small_objects function here.