Extract Largest Connected Component from Binary Image

  • Share this:

Code introduction


This function extracts the largest object from a binary image using connected component analysis. It first binarizes the image, then labels the connected components of the binarized image, and finally extracts the largest connected component.


Technology Stack : Scikit-image, NumPy, Connected Component Analysis

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def extract_largest_object(image, threshold=128):
    """
    Extracts the largest object from a binary image using connected component analysis.

    Parameters:
    - image: A 2D NumPy array representing the image.
    - threshold: A value to binarize the image (values above this threshold are set to 1).

    Returns:
    - largest_object: A NumPy array representing the largest object in the image.
    """
    import numpy as np
    from skimage import measure, color

    # Binarize the image
    binary_image = image > threshold
    binary_image = binary_image.astype(np.uint8)

    # Perform connected component analysis
    labeled_image, num_features = measure.label(binary_image)

    # Find the largest connected component
    largest_label = sorted(zip(num_features, labeled_image.ravel()))[-1][1]
    largest_object = np.where(labeled_image == largest_label, 1, 0).astype(np.uint8)

    return largest_object