Scikit Image − Local Thresholding



Local thresholding, also known as adaptive thresholding or dynamic thresholding, is an image processing technique used to segment an image into foreground and background regions when there is a significant variation in the background intensity. Unlike global thresholding, where a single threshold is applied to the entire image, local thresholding calculates individual thresholds for different regions of the image. These regions are defined by local neighborhoods.

Scikit-image offers a few of functions within its filter module for applying local thresholding to images. These functions are threshold_local() and rank.otsu().

Using the skimage.filters.threshold_local() function

The filters.threshold_local() function is used to compute a threshold mask image based on the local pixel neighborhood of an input grayscale image. This process is commonly known as adaptive or dynamic thresholding.

The threshold value is calculated by taking the weighted mean of the pixel values within the local neighborhood of a specific pixel and then subtracting it by a constant. Alternatively, the threshold can be determined dynamically using a user-defined function when using the 'generic' method.

Syntax

Following is the syntax of this function −

skimage.filters.threshold_local(image, block_size=3, method='gaussian', offset=0, mode='reflect', param=None, cval=0)

Parameters

The function accepts the following parameters −

  • image (N, M[, …, P]) ndarray: This is the input grayscale image on which the local thresholding will be applied.
  • block_size (int or sequence of int): This parameter specifies the size of the pixel neighborhood used to calculate the threshold value. It should be an odd integer, such as 3, 5, 7, and so on.
  • method (str, optional): This parameter determines the method used to compute the adaptive threshold for the local neighborhood in a weighted mean image. It supports the following options:
    • 'generic': Custom function specified by the param parameter.
    • 'gaussian': Gaussian filter with a custom sigma specified by the param parameter.
    • 'mean': Arithmetic mean filter.
    • 'median': Median rank filter.
  • By default, the 'gaussian' method is used.

  • offset (float, optional): This is a constant value subtracted from the weighted mean of the local neighborhood to calculate the local threshold value. The default offset is 0.
  • mode (str, optional): The mode parameter determines how the borders of the input array are handled. Options include 'reflect', 'constant', 'nearest', 'mirror', and 'wrap'. where cval is the value if the mode is set to 'constant'. The default mode is 'reflect'.
  • param (int or function, optional): This parameter is either an integer (sigma value for the 'gaussian' method) or a function object (for the 'generic' method). The function object takes the flat array of the local neighborhood as a single argument and returns the calculated threshold for the center pixel.
  • cval (float, optional): This parameter is the value used to fill past the edges of the input image if the mode is set to 'constant'.

Return value

The function returns the threshold image as a ndarray(N, M[, …, P]), where all pixels in the input image that are higher than the corresponding pixel in the threshold image are considered foreground.

Examle

Here's an example that compares global thresholding using the threshold_otsu() function and local thresholding using the threshold_local() function −

from skimage.filters import threshold_otsu, threshold_local
import matplotlib.pyplot as plt
from skimage import io, color

# Load an input image
image = color.rgb2gray(io.imread('Images/Tajmahal_2.jpg'))

# Apply global thresholding using Otsu's method
global_thresh = threshold_otsu(image)
binary_global = image > global_thresh

# Define the block size and apply local thresholding
block_size = 33
local_thresh = threshold_local(image, block_size, offset=0.05)
binary_local = image > local_thresh

# Create subplots for the original image, global, and local thresholding
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
ax = axes.ravel()
plt.gray()

# Display the original image
ax[0].imshow(image)
ax[0].set_title('Original')
ax[0].axis('off')

# Display the result of global thresholding
ax[1].imshow(binary_global)
ax[1].set_title('Global thresholding')
ax[1].axis('off')

# Display the result of local thresholding
ax[2].imshow(binary_local)
ax[2].set_title('Local thresholding')
ax[2].axis('off')
    
plt.show()

Output

Local Threshold

Applying the local threshold using the Otsu thresholding method

The Otsu thresholding method, originally designed for global thresholding, but this can also be applied locally to an image by considering the local gray-level distribution.

The skimage.filters.rank.otsu() function calculates the local Otsu's threshold value for each pixel in an input image based on a specified neighborhood (footprint).

Syntax

Following is the syntax of this function −

skimage.filters.rank.otsu(image, footprint, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)

Parameters

Here are the details of the parameters −

  • image (([P,] M, N) ndarray (uint8, uint16)): The input image on which local Otsu's thresholding will be applied. It can be a 2D image or a 3D image with optional channels (P).
  • footprint (ndarray): The neighborhood expressed as an ndarray of 1's and 0's. This parameter defines the shape and size of the local region around each pixel used for threshold calculation.
  • out (([P,] M, N) array (same dtype as input)): If provided, this parameter specifies the output array where the result will be stored. If set to None, a new array is allocated for the output.
  • mask ((integer or float) ndarray, optional): This is an optional mask array that defines an area of the image (values greater than 0) included in the local neighborhood. If not provided (set to None), the complete image is used as the neighborhood.
  • shift_x, shift_y, shift_z (int): These parameters allow you to specify an offset added to the center point of the footprint. The shift is bounded to the footprint sizes, meaning that the center must remain inside the given footprint. The function returns an Output image (([P,] M, N) ndarray) containing the local Otsu's threshold values. This image has the same data type as the input image.

Example

The following example demonstrates the difference between global and local Otsu thresholding methods using the rank.otsu() and threshold_otsu functions respectively −

import matplotlib.pyplot as plt
from skimage.morphology import disk
from skimage.filters import threshold_otsu, rank
from skimage.util import img_as_ubyte
from skimage import io

# Load an image and convert it to 8-bit unsigned integer format
img = img_as_ubyte(io.imread('Images/car.jpg', as_gray=True))

# Define the radius for the local neighborhood
radius = 15
footprint = disk(radius)

# Apply local Otsu thresholding using the disk footprint
local_otsu = rank.otsu(img, footprint)

# Compute the global Otsu threshold for the entire image
threshold_global_otsu = threshold_otsu(img)

# Binarize the image using the global Otsu threshold
global_otsu = img >= threshold_global_otsu

# Create a subplot for visualization
fig, axes = plt.subplots(2, 2, figsize=(10, 5), sharex=True, sharey=True)
ax = axes.ravel()
plt.tight_layout()

# Display the original image
fig.colorbar(ax[0].imshow(img, cmap=plt.cm.gray),
             ax=ax[0], orientation='horizontal')
ax[0].set_title('Original')
ax[0].axis('off')

# Display the local Otsu thresholded image
fig.colorbar(ax[1].imshow(local_otsu, cmap=plt.cm.gray),
             ax=ax[1], orientation='horizontal')
ax[1].set_title(f'Local Otsu (radius={radius})')
ax[1].axis('off')

# Display the binary image obtained by applying the local Otsu threshold to the original image
ax[2].imshow(img >= local_otsu, cmap=plt.cm.gray)
ax[2].set_title('Original >= Local Otsu')
ax[2].axis('off')

# Display the global Otsu thresholded image
ax[3].imshow(global_otsu, cmap=plt.cm.gray)
ax[3].set_title(f'Global Otsu (threshold = {threshold_global_otsu})')
ax[3].axis('off')

plt.show()

Output

Local Threshold
Advertisements