Search code examples
pythonarraysconnected-components

How to do connected component labeling in 3 dimensional array in python?


Helo everyone, i have a problem dealing with connected component in 3D array. Actually i'm working on 3D CT scan data for neuroimaging research. for simple explanation, there is an example of 3D array :

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

And this is how it's look like :

This how it's look like

The question is, is there any way for me to do connected component directly in 3D space? maybe like using 26 neighborhood pixel? or maybe just for labeling the object in 3D Because i already try to use open cv connected component to processing each slice (in 2D array) and this is how i process 2D array (slice) and its work :

# Largest Connected Component
# slice array is from thresholding process (the value is 0, 1, 2)
    new_img = np.zeros_like(slice)                                        
    for val in np.unique(slice)[1:]:                                      
        mask = np.uint8(slice == val)                                     
        labels, stats = cv2.connectedComponentsWithStats(mask, 4)[1:3]      
        largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])          
        new_img[labels == largest_label] = val 

but after i stacking it, the result is bad. Some slice have lost value. Maybe someone here have an experience to dealing with this problem before, your answer will be really helpfull. Thanks!


Solution

  • I found solution about this problem. there is a library that support not only 2D image but also 3D create by William Silversmith. Here is the link : https://pypi.org/project/connected-components-3d/

    The documentation is clear enough. I hope this helpful if you facing the same problem.