Thresholding Image with Binary and Otsu#s Method

  • Share this:

Code introduction


This function takes an input grayscale or color image and applies a threshold operation to create a binary image. It supports two thresholding modes: binary thresholding and Otsu's method. Binary thresholding uses a fixed threshold value, while Otsu's method automatically determines the optimal threshold.


Technology Stack : scikit-image

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
def threshold_image(image, threshold=128, mode='binary'):
    """
    Apply a threshold to the input image and return the thresholded image.
    
    Args:
        image (ndarray): Input grayscale image.
        threshold (int): Threshold value. Default is 128.
        mode (str): Thresholding mode. 'binary' for binary thresholding, 'otsu' for Otsu's method.
    
    Returns:
        ndarray: Thresholded image.
    """
    from skimage import exposure, color
    # Convert the image to grayscale if it is not already
    if len(image.shape) > 2:
        image = color.rgb2gray(image)
    # Apply thresholding
    if mode == 'binary':
        thresholded = exposure.threshold_binary_image(image, threshold)
    elif mode == 'otsu':
        thresholded = exposure.threshold_otsu(image)
    else:
        raise ValueError("Invalid mode. Use 'binary' or 'otsu'.")
    return thresholded                
              
Tags: