Search code examples
pythonscikit-image

Scikit skimage regionsprops get connected regions (python)


I'm trying to find to out which regions are connected. I scoured the scikit documentation but I'm unable to find a way to do this.

This is what my code looks like

def calculate_mask_info(labeled_2DImage):
    features = pd.DataFrame()
    id = 0

    newmask = label(labeled_2DImage, connectivity=2) # seperate regions with same mean_intensity that are not connected

    for region in regionprops(newmask, intensity_image=labeled_2DImage):
        if region.mean_intensity < 1:
            # Skip background (intensity 0)
            continue
        # connected regionds Id's -> how?
        features = features.append([get_region_info(region, id)]) #function that puts region info into dictionary
        id += 1
    return features

def get_region_info(region, id):
    feat_dict = {'id': id,
                 'labelId': region.mean_intensity,
                 'y': region.centroid[0],
                 'x': region.centroid[1],
                }
    return feat_dict

Image of masks


Solution

  • What you want is a region adjacency graph, or RAG. You can create one with:

    from skimage import future
    
    rag = future.graph.RAG(newmask)  # or labeled2D_image, not sure
    

    You can then get the neighboring regions with:

    list(rag.neighbors(region.label))
    

    Note that the neighbors include the background label (0) by default, but you can remove it with:

    rag.remove_node(0)
    

    The RAG is a networkx Graph, so you can check that documentation for more information.

    Finally, note that RAG is about to move from skimage.future.graph to skimage.segmentation.graph in the upcoming 0.18 release of scikit-image, so you should watch out for that change!