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

morphology.mddocs/

Morphology

Morphological image processing operations including erosion, dilation, opening, closing, skeletonization, and advanced morphological algorithms. Supports both binary and grayscale morphology with customizable structuring elements.

Capabilities

Basic Binary Morphology

Fundamental morphological operations on binary images using structuring elements to modify object shapes and connectivity.

def binary_erosion(image, footprint=None, out=None, border_value=0, brute_force=False):
    """
    Perform binary erosion of an image.
    
    Parameters:
    image : array_like
        Binary input image
    footprint : array_like, optional
        Structuring element used for erosion
    out : ndarray, optional
        Array for storing result
    border_value : int, optional
        Value at border
    brute_force : bool, optional
        Memory condition for border_value != 0
        
    Returns:
    ndarray
        Eroded binary image
    """

def binary_dilation(image, footprint=None, out=None, border_value=0, brute_force=False):
    """
    Perform binary dilation of an image.
    
    Parameters:
    image : array_like
        Binary input image
    footprint : array_like, optional
        Structuring element used for dilation
    out : ndarray, optional
        Array for storing result
    border_value : int, optional
        Value at border
    brute_force : bool, optional
        Memory condition for border_value != 0
        
    Returns:
    ndarray
        Dilated binary image
    """

def binary_opening(image, footprint=None, out=None, border_value=0, brute_force=False):
    """
    Perform binary opening (erosion followed by dilation).
    
    Parameters:
    image : array_like
        Binary input image
    footprint : array_like, optional
        Structuring element
    out : ndarray, optional
        Array for storing result
    border_value : int, optional
        Value at border
    brute_force : bool, optional
        Memory condition for border_value != 0
        
    Returns:
    ndarray
        Opened binary image
    """

def binary_closing(image, footprint=None, out=None, border_value=0, brute_force=False):
    """
    Perform binary closing (dilation followed by erosion).
    
    Parameters:
    image : array_like
        Binary input image
    footprint : array_like, optional
        Structuring element
    out : ndarray, optional
        Array for storing result
    border_value : int, optional
        Value at border
    brute_force : bool, optional
        Memory condition for border_value != 0
        
    Returns:
    ndarray
        Closed binary image
    """

Grayscale Morphology

Morphological operations on grayscale images that preserve intensity information while modifying image structure.

def erosion(image, footprint=None, out=None, shift_x=False, shift_y=False):
    """
    Perform grayscale erosion of an image.
    
    Parameters:
    image : array_like
        Input image
    footprint : array_like, optional
        Structuring element for erosion
    out : ndarray, optional
        Array for storing result
    shift_x : bool, optional
        Shift structuring element about center
    shift_y : bool, optional
        Shift structuring element about center
        
    Returns:
    ndarray
        Eroded image
    """

def dilation(image, footprint=None, out=None, shift_x=False, shift_y=False):
    """
    Perform grayscale dilation of an image.
    
    Parameters:
    image : array_like
        Input image
    footprint : array_like, optional
        Structuring element for dilation
    out : ndarray, optional
        Array for storing result
    shift_x : bool, optional
        Shift structuring element about center
    shift_y : bool, optional
        Shift structuring element about center
        
    Returns:
    ndarray
        Dilated image
    """

def opening(image, footprint=None, out=None):
    """
    Perform grayscale opening (erosion followed by dilation).
    
    Parameters:
    image : array_like
        Input image
    footprint : array_like, optional
        Structuring element
    out : ndarray, optional
        Array for storing result
        
    Returns:
    ndarray
        Opened image
    """

def closing(image, footprint=None, out=None):
    """
    Perform grayscale closing (dilation followed by erosion).
    
    Parameters:
    image : array_like
        Input image
    footprint : array_like, optional
        Structuring element
    out : ndarray, optional
        Array for storing result
        
    Returns:
    ndarray
        Closed image
    """

def white_tophat(image, footprint=None, out=None):
    """
    Perform white top-hat transform (image - opening).
    
    Parameters:
    image : array_like
        Input image
    footprint : array_like, optional
        Structuring element
    out : ndarray, optional
        Array for storing result
        
    Returns:
    ndarray
        White top-hat transformed image
    """

def black_tophat(image, footprint=None, out=None):
    """
    Perform black top-hat transform (closing - image).
    
    Parameters:
    image : array_like
        Input image
    footprint : array_like, optional
        Structuring element
    out : ndarray, optional
        Array for storing result
        
    Returns:
    ndarray
        Black top-hat transformed image
    """

Structuring Elements

Create various shaped structuring elements for morphological operations.

def disk(radius, dtype=np.uint8):
    """
    Generate a disk-shaped structuring element.
    
    Parameters:
    radius : int
        Radius of the disk
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        Disk-shaped structuring element
    """

def square(width, dtype=np.uint8):
    """
    Generate a square structuring element.
    
    Parameters:
    width : int
        Width and height of the square
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        Square structuring element
    """

def rectangle(width, height, dtype=np.uint8):
    """
    Generate a rectangular structuring element.
    
    Parameters:
    width : int
        Width of the rectangle
    height : int
        Height of the rectangle
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        Rectangular structuring element
    """

def diamond(radius, dtype=np.uint8):
    """
    Generate a diamond-shaped structuring element.
    
    Parameters:
    radius : int
        Radius of the diamond
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        Diamond-shaped structuring element
    """

def star(a, dtype=np.uint8):
    """
    Generate a star-shaped structuring element.
    
    Parameters:
    a : int
        Parameter for star shape
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        Star-shaped structuring element
    """

def ellipse(width, height, dtype=np.uint8):
    """
    Generate an elliptical structuring element.
    
    Parameters:
    width : int
        Width of the ellipse
    height : int
        Height of the ellipse
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        Elliptical structuring element
    """

def octagon(m, n, dtype=np.uint8):
    """
    Generate an octagonal structuring element.
    
    Parameters:
    m : int
        First parameter for octagon shape
    n : int
        Second parameter for octagon shape
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        Octagonal structuring element
    """

3D Structuring Elements

Create three-dimensional structuring elements for volumetric morphological operations.

def ball(radius, dtype=np.uint8):
    """
    Generate a 3D ball-shaped structuring element.
    
    Parameters:
    radius : int
        Radius of the ball
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        3D ball-shaped structuring element
    """

def cube(width, dtype=np.uint8):
    """
    Generate a 3D cube structuring element.
    
    Parameters:
    width : int
        Width, height, and depth of the cube
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        3D cube structuring element
    """

def octahedron(radius, dtype=np.uint8):
    """
    Generate a 3D octahedral structuring element.
    
    Parameters:
    radius : int
        Radius of the octahedron
    dtype : data-type, optional
        Data type of structuring element
        
    Returns:
    ndarray
        3D octahedral structuring element
    """

Skeletonization and Thinning

Extract skeleton and perform morphological thinning operations for shape analysis.

def skeletonize(image, method='lee'):
    """
    Compute skeleton of a binary image.
    
    Parameters:
    image : array_like
        Input binary image
    method : str, optional
        Algorithm to use ('lee' or 'zhang')
        
    Returns:
    ndarray
        Skeleton of the input image
    """

def medial_axis(image, mask=None, return_distance=False):
    """
    Compute medial axis transform of a binary image.
    
    Parameters:
    image : array_like
        Input binary image
    mask : array_like, optional
        Mask to limit computation region
    return_distance : bool, optional
        Whether to return distance transform
        
    Returns:
    ndarray or tuple of ndarrays
        Medial axis and optionally distance transform
    """

def thin(image, max_num_iter=None):
    """
    Perform morphological thinning of a binary image.
    
    Parameters:
    image : array_like
        Input binary image
    max_num_iter : int, optional
        Maximum number of iterations
        
    Returns:
    ndarray
        Thinned binary image
    """

Object Removal and Cleaning

Remove unwanted objects and clean binary images based on size and connectivity criteria.

def remove_small_objects(ar, min_size=64, connectivity=1, in_place=False):
    """
    Remove objects smaller than specified size.
    
    Parameters:
    ar : array_like
        Input labeled or binary image
    min_size : int, optional
        Minimum size of objects to keep
    connectivity : int, optional
        Pixel connectivity (1, 2, or 3 for 2D; 1, 2, 3, or 26 for 3D)
    in_place : bool, optional
        Whether to modify input array
        
    Returns:
    ndarray
        Cleaned image with small objects removed
    """

def remove_small_holes(ar, area_threshold=64, connectivity=1, in_place=False):
    """
    Remove small holes in binary objects.
    
    Parameters:
    ar : array_like
        Input binary image
    area_threshold : int, optional
        Maximum size of holes to fill
    connectivity : int, optional
        Pixel connectivity
    in_place : bool, optional
        Whether to modify input array
        
    Returns:
    ndarray
        Binary image with small holes filled
    """

Convex Hull Operations

Compute convex hull of binary objects for shape analysis and object completion.

def convex_hull_image(image, offset_coordinates=True, tolerance=1e-10):
    """
    Compute convex hull image of a binary image.
    
    Parameters:
    image : array_like
        Input binary image
    offset_coordinates : bool, optional
        Whether to use offset coordinates
    tolerance : float, optional
        Tolerance for geometric calculations
        
    Returns:
    ndarray
        Binary image with convex hull filled
    """

def convex_hull_object(image, neighbors=8):
    """
    Compute convex hull of all objects in a binary image.
    
    Parameters:
    image : array_like
        Input binary image
    neighbors : int, optional
        Connectivity for object identification
        
    Returns:
    ndarray
        Binary image with convex hulls of all objects
    """

Morphological Reconstruction

Perform morphological reconstruction operations for selective object enhancement and noise removal.

def reconstruction(seed, mask, method='dilation', footprint=None, offset=None):
    """
    Perform morphological reconstruction.
    
    Parameters:
    seed : array_like
        Seed image for reconstruction
    mask : array_like
        Mask image that limits reconstruction
    method : str, optional
        Type of reconstruction ('dilation' or 'erosion')
    footprint : array_like, optional
        Structuring element
    offset : array_like, optional
        Offset for structuring element
        
    Returns:
    ndarray
        Reconstructed image
    """

Extrema Detection

Detect local maxima and minima using morphological operations.

def local_maxima(image, min_distance=1, threshold_abs=None, threshold_rel=None, exclude_border=True, num_peaks=np.inf, footprint=None, labels=None, num_peaks_per_label=np.inf, p_norm=np.inf):
    """
    Find local maxima in an image.
    
    Parameters:
    image : array_like
        Input image
    min_distance : int, optional
        Minimum distance between peaks
    threshold_abs : float, optional
        Minimum absolute intensity
    threshold_rel : float, optional
        Minimum relative intensity
    exclude_border : bool, optional
        Whether to exclude border
    num_peaks : int, optional
        Maximum number of peaks
    footprint : array_like, optional
        Footprint for peak detection
    labels : array_like, optional
        Labeled regions
    num_peaks_per_label : int, optional
        Maximum peaks per label
    p_norm : float, optional
        P-norm for distance calculation
        
    Returns:
    ndarray
        Binary image with local maxima
    """

def local_minima(image, min_distance=1, threshold_abs=None, threshold_rel=None, exclude_border=True, num_peaks=np.inf, footprint=None, labels=None, num_peaks_per_label=np.inf, p_norm=np.inf):
    """
    Find local minima in an image.
    
    Parameters:
    image : array_like
        Input image
    min_distance : int, optional
        Minimum distance between peaks
    threshold_abs : float, optional
        Maximum absolute intensity
    threshold_rel : float, optional
        Maximum relative intensity
    exclude_border : bool, optional
        Whether to exclude border
    num_peaks : int, optional
        Maximum number of peaks
    footprint : array_like, optional
        Footprint for peak detection
    labels : array_like, optional
        Labeled regions
    num_peaks_per_label : int, optional
        Maximum peaks per label
    p_norm : float, optional
        P-norm for distance calculation
        
    Returns:
    ndarray
        Binary image with local minima
    """

def h_maxima(image, h, footprint=None):
    """
    Determine h-maxima of an image.
    
    Parameters:
    image : array_like
        Input image
    h : float
        Height threshold for maxima
    footprint : array_like, optional
        Structuring element
        
    Returns:
    ndarray
        Binary image with h-maxima
    """

def h_minima(image, h, footprint=None):
    """
    Determine h-minima of an image.
    
    Parameters:
    image : array_like
        Input image
    h : float
        Height threshold for minima
    footprint : array_like, optional
        Structuring element
        
    Returns:
    ndarray
        Binary image with h-minima
    """

Usage Examples

Basic Morphological Operations

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

# Load binary image
image = data.horse()

# Create structuring element
footprint = morphology.disk(5)

# Apply basic operations
eroded = morphology.erosion(image, footprint)
dilated = morphology.dilation(image, footprint)
opened = morphology.opening(image, footprint)
closed = morphology.closing(image, footprint)

# Display results
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
axes[0, 0].imshow(image, cmap='gray')
axes[0, 0].set_title('Original')
axes[0, 1].imshow(eroded, cmap='gray')
axes[0, 1].set_title('Erosion')
axes[0, 2].imshow(dilated, cmap='gray')
axes[0, 2].set_title('Dilation')
axes[1, 0].imshow(opened, cmap='gray')
axes[1, 0].set_title('Opening')
axes[1, 1].imshow(closed, cmap='gray')
axes[1, 1].set_title('Closing')
plt.show()

Object Cleaning and Analysis

from skimage import data, morphology, measure
import numpy as np

# Create noisy binary image
image = data.binary_blobs(length=256, blob_size_fraction=0.1)

# Add noise
noisy = image.copy()
noise = np.random.random(image.shape) < 0.05
noisy[noise] = ~noisy[noise]

# Clean image
cleaned = morphology.remove_small_objects(noisy, min_size=50)
filled = morphology.remove_small_holes(cleaned, area_threshold=20)

# Label and analyze objects
labeled = measure.label(filled)
props = measure.regionprops(labeled)

print(f"Original objects: {len(np.unique(measure.label(image))) - 1}")
print(f"Noisy objects: {len(np.unique(measure.label(noisy))) - 1}")
print(f"Cleaned objects: {len(props)}")

Skeletonization and Shape Analysis

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

# Load and skeletonize
image = data.horse()
skeleton = morphology.skeletonize(image)
medial_axis, distance = morphology.medial_axis(image, return_distance=True)

# Compare methods
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original')
axes[1].imshow(skeleton, cmap='gray')
axes[1].set_title('Skeleton')
axes[2].imshow(distance * medial_axis, cmap='hot')
axes[2].set_title('Medial Axis with Distance')
plt.show()

Types

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

# Morphological structures
Footprint = Optional[NDArray[np.bool_]]
StructuringElement = NDArray[np.bool_]

# Morphological parameters
BorderValue = int
Connectivity = int
MorphMethod = str

# Results
BinaryImage = NDArray[np.bool_]
GrayscaleImage = NDArray[np.number]
SkeletonResult = Union[NDArray[np.bool_], Tuple[NDArray[np.bool_], NDArray[np.floating]]]

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