You can download this code by clicking the button below.
This code is now available for download.
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