Automatic Image Thresholding Method Application

  • Share this:

Code introduction


This function applies automatic thresholding to an image by converting it to grayscale and then generating a binary image based on a specified threshold and method.


Technology Stack : scikit-image

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
def auto_threshold(image, threshold=128, method='otsu'):
    """
    This function applies an automatic thresholding method to an image.
    """
    from skimage import exposure
    from skimage.color import rgb2gray

    # Convert the image to grayscale
    gray_image = rgb2gray(image)
    
    # Apply the thresholding method
    if method == 'otsu':
        binary_image = exposure.threshold_otsu(gray_image) > threshold
    elif method == 'simple':
        binary_image = exposure.threshold_simple(gray_image) > threshold
    else:
        raise ValueError("Unsupported thresholding method. Use 'otsu' or 'simple'.")

    return binary_image                
              
Tags: