Search code examples
pythonscikit-image

How to do component labeling of a binary image in python


I am trying to apply component-labeling via contour tracing of a simple array as an example.

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

This represents a binary image, with 0 being empty space and 1 representing the shape.

The result I am trying to get is separately labeling these two polygons and showing in a graph via matplotlib each polygon in a different color (as proof that each point in the polygon has been labeled to a respective region.

I thought that the combination of skimage.measure.regionprops, skimage.measure.label, and skimage.measure.find_contours would do the trick, but I haven't been able to find any examples that I am looking for to work off of.

I have spent hours trying to understand the documentation and searching for previous posts and am at a dead end now. This post hereseems like something similar to my problem, although I would want to be able to label each pixel inside shape rather then just the perimeters.

Any help or explanation of what I SHOULD be doing instead muchly appreciated. Thank you


Solution

  • You just need to use skimage.measure.label:

    import numpy as np
    from skimage.measure import label
    from skimage import io
    
    arr = np.array([[1,0,1,0,0,0,0],
                    [1,1,1,0,0,0,0],
                    [0,1,1,0,0,0,1],
                    [0,1,1,0,0,1,1],
                    [0,0,0,0,1,1,1],
                    [0,0,0,1,1,1,1],
                    [0,0,0,1,1,1,1]])
    
    img = label(arr)
    io.imshow(img)
    

    labeled

    In [12]: img
    Out[12]: 
    array([[1, 0, 1, 0, 0, 0, 0],
           [1, 1, 1, 0, 0, 0, 0],
           [0, 1, 1, 0, 0, 0, 2],
           [0, 1, 1, 0, 0, 2, 2],
           [0, 0, 0, 0, 2, 2, 2],
           [0, 0, 0, 2, 2, 2, 2],
           [0, 0, 0, 2, 2, 2, 2]], dtype=int64)