CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-scikit-image

Comprehensive image processing and computer vision library for Python with algorithms for filtering, morphology, segmentation, and feature detection

Pending
Overview
Eval results
Files

filtering.mddocs/

Filtering

Image filtering operations for noise reduction, edge detection, enhancement, and feature extraction. Includes linear filters, morphological filters, thresholding methods, and specialized filters for various image analysis tasks.

Capabilities

Gaussian and Smoothing Filters

Apply Gaussian and related smoothing filters for noise reduction and image preprocessing.

def gaussian(image, sigma=1, output=None, mode='nearest', cval=0.0, multichannel=None, preserve_range=False, truncate=4.0):
    """
    Apply Gaussian filter for smoothing and noise reduction.
    
    Parameters:
    image : array_like
        Input image
    sigma : scalar or sequence of scalars, optional
        Standard deviation for Gaussian kernel
    output : array, optional
        Output array for result
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
    multichannel : bool, optional
        Whether last axis is channels
    preserve_range : bool, optional
        Keep original data range
    truncate : float, optional
        Kernel truncation factor
        
    Returns:
    ndarray
        Filtered image
    """

def difference_of_gaussians(image, low_sigma, high_sigma=None, mode='nearest', cval=0.0, multichannel=False, truncate=4.0):
    """
    Apply Difference of Gaussians filter for edge detection.
    
    Parameters:
    image : array_like
        Input image
    low_sigma : scalar or sequence
        Standard deviation for low-pass filter
    high_sigma : scalar or sequence, optional
        Standard deviation for high-pass filter
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
    multichannel : bool, optional
        Whether last axis is channels
    truncate : float, optional
        Kernel truncation factor
        
    Returns:
    ndarray
        Filtered image showing edges
    """

Edge Detection Filters

Detect edges using various gradient-based operators including Sobel, Scharr, Prewitt, Roberts, and Farid filters.

def sobel(image, mask=None, axis=None, mode='reflect', cval=0.0):
    """
    Apply Sobel edge detection filter.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Mask to limit computation region
    axis : int, optional
        Axis for directional gradient
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    ndarray
        Edge magnitude image
    """

def sobel_h(image, mask=None):
    """
    Apply horizontal Sobel filter.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Mask to limit computation region
        
    Returns:
    ndarray
        Horizontal edge response
    """

def sobel_v(image, mask=None):
    """
    Apply vertical Sobel filter.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Mask to limit computation region
        
    Returns:
    ndarray
        Vertical edge response
    """

def scharr(image, mask=None, axis=None, mode='reflect', cval=0.0):
    """
    Apply Scharr edge detection filter.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Mask to limit computation region
    axis : int, optional
        Axis for directional gradient
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    ndarray
        Edge magnitude image
    """

def prewitt(image, mask=None, axis=None, mode='reflect', cval=0.0):
    """
    Apply Prewitt edge detection filter.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Mask to limit computation region
    axis : int, optional
        Axis for directional gradient
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    ndarray
        Edge magnitude image
    """

def roberts(image, mask=None):
    """
    Apply Roberts cross-gradient edge detection.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Mask to limit computation region
        
    Returns:
    ndarray
        Edge magnitude image
    """

def farid(image, mask=None, axis=None):
    """
    Apply Farid edge detection filter.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Mask to limit computation region
    axis : int, optional
        Axis for directional gradient
        
    Returns:
    ndarray
        Edge magnitude image
    """

def laplace(image, ksize=3, mask=None):
    """
    Apply Laplacian edge detection filter.
    
    Parameters:
    image : array_like
        Input image
    ksize : int, optional
        Kernel size (3, 5, etc.)
    mask : array_like, optional
        Mask to limit computation region
        
    Returns:
    ndarray
        Laplacian response
    """

Advanced Edge Detection

Apply Canny edge detection with non-maximum suppression and hysteresis thresholding.

def canny(image, sigma=1.0, low_threshold=None, high_threshold=None, mask=None, use_quantiles=False, mode='constant', cval=0.0):
    """
    Apply Canny edge detection algorithm.
    
    Parameters:
    image : array_like
        Input grayscale image
    sigma : float, optional
        Standard deviation of Gaussian filter
    low_threshold : float, optional
        Lower hysteresis threshold
    high_threshold : float, optional
        Upper hysteresis threshold
    mask : array_like, optional
        Mask to limit edge detection region
    use_quantiles : bool, optional
        Interpret thresholds as quantiles
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    ndarray
        Binary edge image
    """

Ridge and Vessel Detection

Detect ridge-like structures and vessels using specialized filters optimized for tubular structures.

def frangi(image, sigmas=range(1, 10, 2), scale_range=None, scale_step=None, alpha=0.5, beta=0.5, gamma=15, black_ridges=True, mode='reflect', cval=0):
    """
    Apply Frangi filter for ridge/vessel detection.
    
    Parameters:
    image : array_like
        Input image
    sigmas : iterable of floats, optional
        Sigmas used as scales of filter
    scale_range : 2-tuple of floats, optional
        Range of sigmas used
    scale_step : float, optional
        Step size between sigmas
    alpha : float, optional
        Frangi correction constant
    beta : float, optional
        Frangi correction constant
    gamma : float, optional
        Frangi correction constant
    black_ridges : bool, optional
        Detect black ridges on white background
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    ndarray
        Ridge-filtered image
    """

def hessian(image, sigmas=range(1, 10, 2), scale_range=None, scale_step=None, alpha=0.5, beta=0.5, gamma=15, black_ridges=True, mode='reflect', cval=0):
    """
    Apply Hessian-based ridge detection filter.
    
    Parameters:
    image : array_like
        Input image
    sigmas : iterable of floats, optional
        Sigmas used as scales of filter
    scale_range : 2-tuple of floats, optional
        Range of sigmas used
    scale_step : float, optional
        Step size between sigmas
    alpha : float, optional
        Hessian correction constant
    beta : float, optional
        Hessian correction constant
    gamma : float, optional
        Hessian correction constant
    black_ridges : bool, optional
        Detect black ridges on white background
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    ndarray
        Ridge-filtered image
    """

def sato(image, sigmas=range(1, 10, 2), black_ridges=True, mode='reflect', cval=0):
    """
    Apply Sato ridge detection filter.
    
    Parameters:
    image : array_like
        Input image
    sigmas : iterable of floats, optional
        Sigmas used as scales of filter
    black_ridges : bool, optional
        Detect black ridges on white background
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    ndarray
        Ridge-filtered image
    """

def meijering(image, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0):
    """
    Apply Meijering ridge detection filter.
    
    Parameters:
    image : array_like
        Input image
    sigmas : iterable of floats, optional
        Sigmas used as scales of filter
    alpha : float, optional
        Meijering correction constant
    black_ridges : bool, optional
        Detect black ridges on white background
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    ndarray
        Ridge-filtered image
    """

Thresholding Methods

Apply various automatic and adaptive thresholding methods for image binarization.

def threshold_otsu(image, nbins=256):
    """
    Calculate Otsu's threshold for automatic binarization.
    
    Parameters:
    image : array_like
        Input grayscale image
    nbins : int, optional
        Number of histogram bins
        
    Returns:
    float
        Threshold value
    """

def threshold_multiotsu(image, classes=3, nbins=256):
    """
    Calculate multi-class Otsu thresholds.
    
    Parameters:
    image : array_like
        Input grayscale image
    classes : int, optional
        Number of classes to threshold into
    nbins : int, optional
        Number of histogram bins
        
    Returns:
    ndarray
        Array of threshold values
    """

def threshold_yen(image, nbins=256):
    """
    Calculate Yen's threshold method.
    
    Parameters:
    image : array_like
        Input grayscale image
    nbins : int, optional
        Number of histogram bins
        
    Returns:
    float
        Threshold value
    """

def threshold_li(image, tolerance=None, initial_guess=None, iter_callback=None):
    """
    Calculate Li's minimum cross-entropy threshold.
    
    Parameters:
    image : array_like
        Input grayscale image
    tolerance : float, optional
        Convergence tolerance
    initial_guess : float, optional
        Initial threshold guess
    iter_callback : callable, optional
        Iteration callback function
        
    Returns:
    float
        Threshold value
    """

def threshold_triangle(image, nbins=256):
    """
    Calculate triangle threshold method.
    
    Parameters:
    image : array_like
        Input grayscale image
    nbins : int, optional
        Number of histogram bins
        
    Returns:
    float
        Threshold value
    """

def threshold_local(image, block_size, method='generic', mode='reflect', param=None, cval=0, offset=0):
    """
    Apply adaptive local thresholding.
    
    Parameters:
    image : array_like
        Input grayscale image
    block_size : int
        Odd size of pixel neighborhood
    method : str, optional
        Thresholding method ('generic', 'gaussian', 'mean', 'median')
    mode : str, optional
        Boundary condition mode
    param : float, optional
        Generic method parameter
    cval : float, optional
        Constant value for constant mode
    offset : float, optional
        Constant subtracted from weighted mean
        
    Returns:
    ndarray
        Threshold image
    """

def threshold_niblack(image, window_size=15, k=0.2):
    """
    Apply Niblack local thresholding.
    
    Parameters:
    image : array_like
        Input grayscale image
    window_size : int, optional
        Window size for local statistics
    k : float, optional
        Value of parameter k in threshold formula
        
    Returns:
    ndarray
        Threshold image
    """

def threshold_sauvola(image, window_size=15, k=0.2, r=None):
    """
    Apply Sauvola local thresholding.
    
    Parameters:
    image : array_like
        Input grayscale image
    window_size : int, optional
        Window size for local statistics
    k : float, optional
        Value of parameter k in threshold formula
    r : float, optional
        Dynamic range of standard deviation
        
    Returns:
    ndarray
        Threshold image
    """

def apply_hysteresis_threshold(image, low, high):
    """
    Apply hysteresis thresholding.
    
    Parameters:
    image : array_like
        Input image
    low : float
        Lower threshold
    high : float
        Upper threshold
        
    Returns:
    ndarray
        Binary thresholded image
    """

Noise Reduction Filters

Apply various filters for noise reduction including median filtering and other morphological filters.

def median(image, footprint=None, out=None, mode='nearest', cval=0.0, behavior='ndimage'):
    """
    Apply median filter for noise reduction.
    
    Parameters:
    image : array_like
        Input image
    footprint : array_like, optional
        Footprint defining filter shape
    out : array, optional
        Output array
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
    behavior : str, optional
        Algorithm behavior ('ndimage' or 'rank')
        
    Returns:
    ndarray
        Median filtered image
    """

def unsharp_mask(image, radius=1.0, amount=1.0, multichannel=False, preserve_range=False):
    """
    Apply unsharp masking for image sharpening.
    
    Parameters:
    image : array_like
        Input image
    radius : scalar, optional
        Standard deviation of Gaussian blur
    amount : scalar, optional
        Strength of sharpening
    multichannel : bool, optional
        Whether last axis is channels
    preserve_range : bool, optional
        Keep original data range
        
    Returns:
    ndarray
        Sharpened image
    """

Gabor Filters

Apply Gabor filters for texture analysis and feature extraction.

def gabor(image, frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, mode='reflect', cval=0):
    """
    Apply Gabor filter for texture analysis.
    
    Parameters:
    image : array_like
        Input image
    frequency : float
        Spatial frequency of harmonic function
    theta : float, optional
        Orientation of normal to parallel stripes
    bandwidth : float, optional
        Bandwidth of filter
    sigma_x : float, optional
        Standard deviation in x direction
    sigma_y : float, optional
        Standard deviation in y direction
    n_stds : scalar, optional
        Number of standard deviations
    offset : float, optional
        Phase offset
    mode : str, optional
        Boundary condition mode
    cval : scalar, optional
        Value for constant mode
        
    Returns:
    tuple of ndarrays
        Real and imaginary responses
    """

def gabor_kernel(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0):
    """
    Generate Gabor kernel.
    
    Parameters:
    frequency : float
        Spatial frequency of harmonic function
    theta : float, optional
        Orientation of normal to parallel stripes
    bandwidth : float, optional
        Bandwidth of filter
    sigma_x : float, optional
        Standard deviation in x direction
    sigma_y : float, optional
        Standard deviation in y direction
    n_stds : scalar, optional
        Number of standard deviations
    offset : float, optional
        Phase offset
        
    Returns:
    tuple of ndarrays
        Real and imaginary parts of kernel
    """

Usage Examples

Basic Edge Detection

from skimage import data, filters
import matplotlib.pyplot as plt

# Load image
image = data.camera()

# Apply different edge detection filters
sobel_edges = filters.sobel(image)
canny_edges = filters.canny(image, sigma=1.0, low_threshold=0.1, high_threshold=0.2)
prewitt_edges = filters.prewitt(image)

# Display results
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes[0, 0].imshow(image, cmap='gray')
axes[0, 0].set_title('Original')
axes[0, 1].imshow(sobel_edges, cmap='gray')
axes[0, 1].set_title('Sobel')
axes[1, 0].imshow(canny_edges, cmap='gray')
axes[1, 0].set_title('Canny')
axes[1, 1].imshow(prewitt_edges, cmap='gray')
axes[1, 1].set_title('Prewitt')
plt.show()

Noise Reduction and Enhancement

from skimage import data, filters, util
import numpy as np

# Load image and add noise
image = data.camera()
noisy = util.random_noise(image, mode='gaussian', var=0.01)

# Apply different filters
gaussian_filtered = filters.gaussian(noisy, sigma=1.0)
median_filtered = filters.median(noisy, disk(2))
unsharp_filtered = filters.unsharp_mask(image, radius=1.0, amount=2.0)

# Compare results
print(f"Original PSNR: {util.compare_psnr(image, noisy):.2f}")
print(f"Gaussian PSNR: {util.compare_psnr(image, gaussian_filtered):.2f}")
print(f"Median PSNR: {util.compare_psnr(image, median_filtered):.2f}")

Automatic Thresholding

from skimage import data, filters
import numpy as np

# Load grayscale image
image = data.coins()

# Apply different thresholding methods
otsu_thresh = filters.threshold_otsu(image)
yen_thresh = filters.threshold_yen(image)
li_thresh = filters.threshold_li(image)

# Create binary images
otsu_binary = image > otsu_thresh
yen_binary = image > yen_thresh
li_binary = image > li_thresh

print(f"Otsu threshold: {otsu_thresh:.2f}")
print(f"Yen threshold: {yen_thresh:.2f}")
print(f"Li threshold: {li_thresh:.2f}")

Types

from typing import Union, Optional, Tuple, Sequence, Callable
from numpy.typing import NDArray
import numpy as np

# Filter parameters
Sigma = Union[float, Sequence[float]]
Footprint = Optional[NDArray[np.bool_]]
BoundaryMode = str
ThresholdMethod = str
FilterResponse = Union[NDArray[np.floating], Tuple[NDArray[np.floating], NDArray[np.floating]]]

Advanced Edge Detection

Extended edge detection operators with directional variants.

def farid_h(image, *, mask=None):
    """
    Find horizontal edges using the Farid transform.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Binary mask for selective filtering
        
    Returns:
    ndarray
        Horizontal edges response
    """

def farid_v(image, *, mask=None):
    """
    Find vertical edges using the Farid transform.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Binary mask for selective filtering
        
    Returns:
    ndarray
        Vertical edges response
    """

def prewitt_h(image, *, mask=None):
    """
    Find horizontal edges using the Prewitt operator.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Binary mask for selective filtering
        
    Returns:
    ndarray  
        Horizontal edges response
    """

def prewitt_v(image, *, mask=None):
    """
    Find vertical edges using the Prewitt operator.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Binary mask for selective filtering
        
    Returns:
    ndarray
        Vertical edges response
    """

def scharr_h(image, *, mask=None):
    """
    Find horizontal edges using the Scharr operator.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Binary mask for selective filtering
        
    Returns:
    ndarray
        Horizontal edges response
    """

def scharr_v(image, *, mask=None):
    """
    Find vertical edges using the Scharr operator.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Binary mask for selective filtering
        
    Returns:
    ndarray
        Vertical edges response
    """

def roberts_pos_diag(image, *, mask=None):
    """
    Find edges using the Roberts cross-gradient positive diagonal operator.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Binary mask for selective filtering
        
    Returns:
    ndarray
        Positive diagonal edges response
    """

def roberts_neg_diag(image, *, mask=None):
    """
    Find edges using the Roberts cross-gradient negative diagonal operator.
    
    Parameters:
    image : array_like
        Input image
    mask : array_like, optional
        Binary mask for selective filtering
        
    Returns:
    ndarray
        Negative diagonal edges response
    """

Frequency Domain Filters

Frequency domain filtering operations and signal processing filters.

def butterworth(image, cutoff_frequency_ratio=0.005, high_pass=True, order=2.0, channel_axis=None, *, squared_butterworth=True, npad=0):
    """
    Apply a Butterworth filter to enhance high or low frequency features.
    
    Parameters:
    image : array_like
        Input image
    cutoff_frequency_ratio : float, optional
        Cutoff frequency ratio relative to Nyquist frequency
    high_pass : bool, optional
        Whether to apply high-pass (True) or low-pass (False) filter
    order : float, optional
        Filter order parameter
    channel_axis : int, optional
        Axis of color channels
    squared_butterworth : bool, optional
        Whether to use squared Butterworth filter
    npad : int, optional
        Padding size for boundary effects
        
    Returns:
    ndarray
        Filtered image
    """

def wiener(data, impulse_response=None, filter_params=None, K=0.25, predefined_filter=None):
    """
    Minimum Mean Square Error (Wiener) inverse filter.
    
    Parameters:
    data : array_like
        Input data to be filtered
    impulse_response : callable, optional
        Function defining the impulse response
    filter_params : dict, optional
        Parameters for the impulse response function
    K : float or array_like, optional
        Ratio between power spectrum of noise and undegraded signal
    predefined_filter : str, optional
        Name of predefined filter to use
        
    Returns:
    ndarray
        Filtered data
    """

class LPIFilter2D:
    """
    Linear Position-Invariant Filter (2-dimensional).
    
    A class implementing 2D linear position-invariant filtering operations
    using impulse response functions.
    """
    
    def __init__(self, impulse_response, **filter_params):
        """
        Initialize the LPI filter.
        
        Parameters:
        impulse_response : callable
            Function that yields the impulse response
        **filter_params : keyword arguments
            Additional parameters for the impulse response function
        """

def filter_forward(data, impulse_response=None, filter_params=None, predefined_filter=None):
    """
    Apply a linear filter with a predefined or custom impulse response.
    
    Parameters:
    data : array_like
        Input data
    impulse_response : callable, optional
        Custom impulse response function
    filter_params : dict, optional
        Parameters for impulse response function
    predefined_filter : str, optional
        Name of predefined filter
        
    Returns:
    ndarray
        Filtered data
    """

def filter_inverse(data, impulse_response=None, filter_params=None, predefined_filter=None, max_gain=2):
    """
    Apply an inverse filter with a predefined or custom impulse response.
    
    Parameters:
    data : array_like
        Input data  
    impulse_response : callable, optional
        Custom impulse response function
    filter_params : dict, optional
        Parameters for impulse response function
    predefined_filter : str, optional
        Name of predefined filter
    max_gain : float, optional
        Maximum gain to prevent amplification of noise
        
    Returns:
    ndarray
        Inverse filtered data
    """

def window(name, shape):
    """
    Generate a window function for filtering applications.
    
    Parameters:
    name : str
        Name of the window function (e.g., 'hann', 'hamming', 'blackman')
    shape : tuple
        Shape of the output window
        
    Returns:
    ndarray
        Window function array
    """

Rank and Statistical Filters

Rank-based filtering operations and statistical analysis functions.

def rank(image, footprint, rank):
    """
    Return the rank-th value from the neighborhood defined by the footprint.
    
    Parameters:
    image : array_like
        Input image
    footprint : array_like
        The neighborhood expressed as a 2-D array of 1's and 0's
    rank : int
        The rank of the value to return (0-based indexing)
        
    Returns:
    ndarray
        Filtered image
    """

def rank_order(image):
    """
    Return an image of rank-order values for each pixel.
    
    Parameters:
    image : array_like
        Input image
        
    Returns:
    ndarray
        Rank-order image where each pixel value represents the rank
        of the original pixel value within the image
    """

def correlate_sparse(image, kernel, mode='reflect'):
    """
    Compute the correlation of a sparse kernel with an image.
    
    Parameters:
    image : array_like
        Input image
    kernel : sparse matrix
        Sparse correlation kernel
    mode : str, optional
        Boundary mode for correlation
        
    Returns:
    ndarray
        Correlated image
    """

Additional Thresholding Methods

Extended thresholding algorithms for different image characteristics.

def threshold_isodata(image, nbins=256):
    """
    Return threshold value based on ISODATA method.
    
    Parameters:
    image : array_like
        Input image
    nbins : int, optional
        Number of bins used to calculate histogram
        
    Returns:
    float
        Threshold value
    """

def threshold_mean(image):
    """
    Return threshold value based on the mean of image intensities.
    
    Parameters:
    image : array_like
        Input image
        
    Returns:
    float
        Threshold value (mean of image)
    """

def threshold_minimum(image, nbins=256, max_num_iter=10000):
    """
    Return threshold value based on minimum method.
    
    Parameters:
    image : array_like
        Input image
    nbins : int, optional
        Number of bins used to calculate histogram
    max_num_iter : int, optional
        Maximum number of iterations
        
    Returns:
    float
        Threshold value
    """

def try_all_threshold(image, figsize=(8, 5), verbose=True):
    """
    Compare results of different threshold methods on the same image.
    
    Parameters:
    image : array_like
        Input image
    figsize : tuple, optional
        Figure size for the comparison plot
    verbose : bool, optional
        Whether to print threshold values
        
    Returns:
    dict
        Dictionary containing threshold values for each method
    """

Install with Tessl CLI

npx tessl i tessl/pypi-scikit-image

docs

color.md

data.md

drawing.md

exposure.md

features.md

filtering.md

index.md

io.md

measurement.md

morphology.md

restoration.md

segmentation.md

transform.md

utilities.md

tile.json