How to distinguish between multiple shapes in a figure or array?
Question: I have a 2D array in Python containing values of either 0 or 1, arranged to
form various shapes. For my current project I need a method to distinguish
between the shapes in the image.

I am currently attempting to do this by setting the values of the first shape
to 1, the second shape values to 2 and so on. However, this is proving too
difficult for me to code, so I was wondering if anyone knew a good algorithm
to do this, or knew of another method. Thanks.


Answer: I suspect you are looking for [label
features](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.measurements.label.html)
which is available in `scipy.ndimage`. Despite the name, it is not
neccessarily specific to image analysis. Quoting from the documentation "Any
non-zero values in input are counted as features and zero values are
considered the background."

The result will be an array, of the same size, with features numbered. For
example, the following code:

    
    
    import numpy as np
    from scipy.ndimage import measurements
    
    arr = np.array([
    [0,0,0,0,0,0],
    [0,1,1,0,0,0],
    [0,1,1,0,0,1],
    [0,0,0,0,1,1],
    [0,0,0,0,1,1]
    ])
    
    labeled_array, number_of_features = measurements.label(arr)
    print(labeled_array)
    

...will produce the following output, with the two features numbered 1 and 2
respectively:

    
    
    array([[0, 0, 0, 0, 0, 0],
           [0, 1, 1, 0, 0, 0],
           [0, 1, 1, 0, 0, 2],
           [0, 0, 0, 0, 2, 2],
           [0, 0, 0, 0, 2, 2]], dtype=int32)
    

The second return parameter contains the `number_of_features` in the array
(here 2).

