Search code examples
pythonnumpyimage-processingscikit-imageconnected-components

Connected component labeling for arrays / quasi-images with many dimension


Problem

I am trying to do connected component labling for arrays of more than 3 dimensions. What I mean by that is that my boolean array has a .shape e.g. like (5,2,3,6,10) which would be 5 dimensions.

For 2D images (instead of my >3D problem), connected component labling would is putting labels to connected areas (hyper-volumes in my case). Two (hpyer-)pixels are connected if the are next to each other and both are True in the boolean array.

enter image description here enter image description here

What I already tried

For 2 dimensions this can be done with OpenCV and with up to 3 dimensions this can be done with scikit-image's skimage.measure.label. However, I am not sure how to it for my case.


Further material for the interested reader (but it does not help my question):


Solution

  • scipy.ndimage.label does what you want directly:

    In [1]: import numpy as np
    In [2]: arr = np.random.random((5,2,3,6,10)) > 0.5
    In [3]: from scipy import ndimage as ndi
    In [4]: labeled, n = ndi.label(arr)
    In [5]: n
    Out[5]: 11