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

segmentation.mddocs/

Segmentation

Image segmentation algorithms for partitioning images into meaningful regions or objects. Includes watershed, region growing, active contours, superpixel methods, and boundary detection algorithms.

Capabilities

Watershed Segmentation

Apply watershed algorithm for segmenting touching objects and complex structures using gradient information and markers.

def watershed(image, markers=None, connectivity=1, offset=None, mask=None, compactness=0, watershed_line=False):
    """
    Apply watershed segmentation algorithm.
    
    Parameters:
    image : array_like
        Input grayscale image or gradient magnitude
    markers : array_like, optional
        Seed markers for watershed regions
    connectivity : int, optional
        Pixel connectivity (1, 2, or 3 for 2D; 1, 2, 3, or 26 for 3D)
    offset : array_like, optional
        Offset for connectivity
    mask : array_like, optional
        Mask limiting segmentation region
    compactness : float, optional
        Compactness factor for segments
    watershed_line : bool, optional
        Whether to compute watershed lines
        
    Returns:
    ndarray
        Labeled segmentation image
    """

Region Growing Segmentation

Segment images using region growing methods that expand from seed points based on similarity criteria.

def random_walker(data, labels, beta=130, mode='bf', tol=0.001, copy=True, multichannel=False, return_full_prob=False, spacing=None, prob_tol=0.001, channel_axis=None):
    """
    Apply random walker segmentation algorithm.
    
    Parameters:
    data : array_like
        Input image data
    labels : array_like
        Seed labels with marked regions
    beta : float, optional
        Edge weighting parameter
    mode : str, optional
        Algorithm mode ('bf' or 'cg')
    tol : float, optional
        Convergence tolerance
    copy : bool, optional
        Whether to copy input data
    multichannel : bool, optional
        Whether last axis is channels (deprecated)
    return_full_prob : bool, optional
        Return full probability maps
    spacing : array_like, optional
        Pixel spacing for each dimension
    prob_tol : float, optional
        Probability tolerance
    channel_axis : int, optional
        Axis for color channels
        
    Returns:
    ndarray or tuple
        Labeled segmentation and optionally probability maps
    """

Superpixel Algorithms

Generate superpixels for over-segmentation and preprocessing using SLIC, Felzenszwalb, and QuickShift methods.

def slic(image, n_segments=100, compactness=10, max_num_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=True, min_size_factor=0.5, max_size_factor=3, slic_zero=False, start_label=1, mask=None, channel_axis=-1):
    """
    Apply Simple Linear Iterative Clustering (SLIC) superpixel segmentation.
    
    Parameters:
    image : array_like
        Input image
    n_segments : int, optional
        Approximate number of superpixels
    compactness : float, optional
        Balance between color similarity and spatial proximity
    max_num_iter : int, optional
        Maximum number of iterations
    sigma : float, optional
        Gaussian smoothing parameter
    spacing : array_like, optional
        Pixel spacing for each dimension
    multichannel : bool, optional
        Whether last axis is channels (deprecated)
    convert2lab : bool, optional
        Convert to LAB color space
    enforce_connectivity : bool, optional
        Enforce superpixel connectivity
    min_size_factor : float, optional
        Minimum superpixel size factor
    max_size_factor : float, optional
        Maximum superpixel size factor
    slic_zero : bool, optional
        Use SLIC-zero algorithm
    start_label : int, optional
        Starting label value
    mask : array_like, optional
        Mask limiting segmentation region
    channel_axis : int, optional
        Axis for color channels
        
    Returns:
    ndarray
        Superpixel labeled image
    """

def felzenszwalb(image, scale=1, sigma=0.8, min_size=20, multichannel=True, channel_axis=-1):
    """
    Apply Felzenszwalb efficient graph-based segmentation.
    
    Parameters:
    image : array_like
        Input image
    scale : float, optional
        Scale parameter for segmentation
    sigma : float, optional
        Gaussian smoothing parameter
    min_size : int, optional
        Minimum segment size
    multichannel : bool, optional
        Whether last axis is channels (deprecated)
    channel_axis : int, optional
        Axis for color channels
        
    Returns:
    ndarray
        Segmented labeled image
    """

def quickshift(image, ratio=1.0, kernel_size=5, max_dist=10, return_tree=False, sigma=0, convert2lab=True, random_seed=42, channel_axis=-1):
    """
    Apply QuickShift clustering segmentation.
    
    Parameters:
    image : array_like
        Input image
    ratio : float, optional
        Balance between color and spatial proximity
    kernel_size : float, optional
        Size of Gaussian kernel for density estimation
    max_dist : float, optional
        Maximum distance between segments
    return_tree : bool, optional
        Whether to return parent tree
    sigma : float, optional
        Gaussian smoothing parameter
    convert2lab : bool, optional
        Convert to LAB color space
    random_seed : int, optional
        Random seed
    channel_axis : int, optional
        Axis for color channels
        
    Returns:
    ndarray or tuple
        Segmented image and optionally parent tree
    """

Active Contours

Apply active contour models (snakes) for object boundary detection and segmentation.

def active_contour(image, snake, alpha=0.01, beta=0.1, w_line=0, w_edge=1, gamma=0.01, max_px_move=1.0, max_num_iter=2500, convergence=0.1, boundary_condition='periodic', coordinates='rc'):
    """
    Apply active contour model for boundary detection.
    
    Parameters:
    image : array_like
        Input grayscale image
    snake : array_like
        Initial contour coordinates
    alpha : float, optional
        Snake length penalty parameter
    beta : float, optional
        Snake smoothness penalty parameter
    w_line : float, optional
        Line term weight
    w_edge : float, optional
        Edge term weight
    gamma : float, optional
        Explicit time stepping parameter
    max_px_move : float, optional
        Maximum pixel movement per iteration
    max_num_iter : int, optional
        Maximum number of iterations
    convergence : float, optional
        Convergence threshold
    boundary_condition : str, optional
        Boundary condition ('periodic', 'free', 'fixed')
    coordinates : str, optional
        Coordinate system ('rc' or 'xy')
        
    Returns:
    ndarray
        Final contour coordinates
    """

def chan_vese(image, mu=0.25, lambda1=1, lambda2=1, tol=1e-3, max_num_iter=500, dt=0.5, init_level_set='checkerboard', extended_output=False):
    """
    Apply Chan-Vese active contour segmentation.
    
    Parameters:
    image : array_like
        Input grayscale image
    mu : float, optional
        Smoothing parameter
    lambda1 : float, optional
        Weight for inside region
    lambda2 : float, optional
        Weight for outside region  
    tol : float, optional
        Convergence tolerance
    max_num_iter : int, optional
        Maximum number of iterations
    dt : float, optional
        Time step
    init_level_set : str or array_like, optional
        Initial level set ('checkerboard', 'disk', or array)
    extended_output : bool, optional
        Return additional outputs
        
    Returns:
    ndarray or tuple
        Segmentation and optionally additional information
    """

def morphological_chan_vese(image, num_iter, init_level_set='checkerboard', smoothing=1, lambda1=1, lambda2=1, iter_callback=None):
    """
    Apply morphological Chan-Vese segmentation.
    
    Parameters:
    image : array_like
        Input grayscale image
    num_iter : int
        Number of iterations
    init_level_set : str or array_like, optional
        Initial level set ('checkerboard', 'disk', or array)
    smoothing : int, optional
        Number of smoothing iterations
    lambda1 : float, optional
        Weight for inside region
    lambda2 : float, optional
        Weight for outside region
    iter_callback : callable, optional
        Callback function for each iteration
        
    Returns:
    ndarray
        Segmentation result
    """

def morphological_geodesic_active_contour(image, num_iter, init_level_set='checkerboard', smoothing=1, threshold='auto', balloon=0, iter_callback=None):
    """
    Apply morphological geodesic active contour.
    
    Parameters:
    image : array_like
        Input grayscale image or edge map
    num_iter : int
        Number of iterations
    init_level_set : str or array_like, optional
        Initial level set ('checkerboard', 'disk', or array)
    smoothing : int, optional
        Number of smoothing iterations
    threshold : str or float, optional
        Threshold for edge map ('auto' or value)
    balloon : float, optional
        Balloon force parameter
    iter_callback : callable, optional
        Callback function for each iteration
        
    Returns:
    ndarray
        Segmentation result
    """

Boundary Detection and Processing

Detect and manipulate region boundaries for visualization and analysis.

def find_boundaries(label_img, connectivity=1, mode='thick', background=0):
    """
    Find boundaries of labeled regions.
    
    Parameters:
    label_img : array_like
        Labeled input image
    connectivity : int, optional
        Pixel connectivity (1, 2, or 3 for 2D)
    mode : str, optional
        Boundary mode ('thick', 'inner', 'outer', 'subpixel')
    background : int, optional
        Background label value
        
    Returns:
    ndarray
        Boolean boundary image
    """

def mark_boundaries(image, label_img, color=(1, 1, 0), outline_color=None, mode='outer', background_label=0):
    """
    Mark boundaries of labeled regions on RGB image.
    
    Parameters:
    image : array_like
        Input RGB image
    label_img : array_like
        Labeled regions
    color : tuple, optional
        Boundary color (RGB)
    outline_color : tuple, optional
        Outline color for boundaries
    mode : str, optional
        Boundary mode ('inner', 'outer', 'thick', 'subpixel')
    background_label : int, optional
        Background label value
        
    Returns:
    ndarray
        RGB image with marked boundaries
    """

Segmentation Utilities

Utility functions for post-processing and manipulating segmentation results.

def clear_border(labels, buffer_size=0, bgval=0, in_place=False, mask=None):
    """
    Clear objects connected to image border.
    
    Parameters:
    labels : array_like
        Labeled input image
    buffer_size : int, optional
        Border buffer size
    bgval : int, optional
        Background value
    in_place : bool, optional
        Whether to modify input array
    mask : array_like, optional
        Mask limiting clearing region
        
    Returns:
    ndarray
        Cleared labeled image
    """

def expand_labels(label_image, distance=1):
    """
    Expand labeled regions by specified distance.
    
    Parameters:
    label_image : array_like
        Labeled input image
    distance : float, optional
        Expansion distance
        
    Returns:
    ndarray
        Expanded labeled image
    """

def join_segmentations(s1, s2):
    """
    Join two segmentation results.
    
    Parameters:
    s1 : array_like
        First segmentation
    s2 : array_like
        Second segmentation
        
    Returns:
    ndarray
        Combined segmentation
    """

def relabel_sequential(label_image, offset=1):
    """
    Relabel image with sequential labels starting from offset.
    
    Parameters:
    label_image : array_like
        Input labeled image
    offset : int, optional
        Starting label value
        
    Returns:
    tuple
        (relabeled_image, forward_map, inverse_map)
    """

Level Set Utilities

Utilities for level set initialization and processing in active contour methods.

def inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0):
    """
    Compute inverse Gaussian gradient for level set evolution.
    
    Parameters:
    image : array_like
        Input grayscale image
    alpha : float, optional
        Alpha parameter
    sigma : float, optional
        Gaussian smoothing parameter
        
    Returns:
    ndarray
        Inverse gradient image
    """

def disk_level_set(image_shape, center=None, radius=None):
    """
    Create disk-shaped initial level set.
    
    Parameters:
    image_shape : tuple
        Shape of output level set
    center : tuple, optional
        Center of disk
    radius : float, optional
        Radius of disk
        
    Returns:
    ndarray
        Disk-shaped level set
    """

def checkerboard_level_set(image_shape, square_size=5):
    """
    Create checkerboard initial level set.
    
    Parameters:
    image_shape : tuple
        Shape of output level set
    square_size : int, optional
        Size of checkerboard squares
        
    Returns:
    ndarray
        Checkerboard level set
    """

Usage Examples

Watershed Segmentation

from skimage import data, segmentation, feature, filters
from scipy import ndimage as ndi
import matplotlib.pyplot as plt

# Load image
image = data.coins()

# Create markers for watershed
distance = ndi.distance_transform_edt(image > filters.threshold_otsu(image))
local_maxima = feature.peak_local_maxima(distance, min_distance=20, threshold_abs=0.3*distance.max())
markers = np.zeros_like(image, dtype=bool)
markers[tuple(local_maxima.T)] = True
markers = ndi.label(markers)[0]

# Apply watershed
labels = segmentation.watershed(-distance, markers, mask=image > filters.threshold_otsu(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(distance, cmap='gray')
axes[0, 1].set_title('Distance Transform')
axes[1, 0].imshow(markers, cmap='nipy_spectral')
axes[1, 0].set_title('Markers')
axes[1, 1].imshow(labels, cmap='nipy_spectral')
axes[1, 1].set_title('Watershed Segmentation')
plt.show()

Superpixel Generation

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

# Load image
image = data.astronaut()

# Apply different superpixel methods
slic_segments = segmentation.slic(image, n_segments=300, compactness=10)
felzenszwalb_segments = segmentation.felzenszwalb(image, scale=100, sigma=0.5, min_size=50)
quickshift_segments = segmentation.quickshift(image, kernel_size=3, max_dist=6, ratio=0.5)

# Mark boundaries
slic_boundaries = segmentation.mark_boundaries(image, slic_segments)
felz_boundaries = segmentation.mark_boundaries(image, felzenszwalb_segments)
quick_boundaries = segmentation.mark_boundaries(image, quickshift_segments)

# Display results
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
axes[0, 0].imshow(image)
axes[0, 0].set_title('Original')
axes[0, 1].imshow(slic_boundaries)
axes[0, 1].set_title('SLIC')
axes[1, 0].imshow(felz_boundaries)
axes[1, 0].set_title('Felzenszwalb')
axes[1, 1].imshow(quick_boundaries)
axes[1, 1].set_title('QuickShift')
plt.show()

Active Contour Segmentation

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

# Load and preprocess image
image = data.astronaut()
gray = rgb2gray(image)

# Initialize contour as circle
s = np.linspace(0, 2*np.pi, 400)
r, c = 220 + 100*np.cos(s), 100 + 120*np.sin(s)
init = np.array([r, c]).T

# Apply active contour
snake = segmentation.active_contour(gray, init, alpha=0.015, beta=10, gamma=0.001)

# Apply Chan-Vese
chan_vese_result = segmentation.chan_vese(gray, mu=0.25, lambda1=1, lambda2=1, 
                                         tol=1e-3, max_num_iter=200)

print(f"Active contour converged with {len(snake)} points")
print(f"Chan-Vese segmentation completed")

Region Growing

from skimage import data, segmentation
import numpy as np

# Load image
image = data.camera()

# Create seed labels for random walker
labels = np.zeros_like(image, dtype=np.int32)
labels[image < 50] = 1  # Dark regions
labels[image > 150] = 2  # Bright regions

# Apply random walker
rw_result = segmentation.random_walker(image, labels, beta=10, mode='bf')

# Display statistics
unique_labels = np.unique(rw_result)
for label in unique_labels:
    area = np.sum(rw_result == label)
    print(f"Region {label}: {area} pixels ({100*area/image.size:.1f}%)")

Types

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

# Segmentation results
LabeledImage = NDArray[np.integer]
BinaryImage = NDArray[np.bool_]
ProbabilityMap = NDArray[np.floating]

# Contour types
Contour = NDArray[np.floating]
LevelSet = NDArray[np.floating]

# Segmentation parameters
Connectivity = int
SegmentationMode = str
BoundaryMode = str

# Algorithm-specific types
SuperpixelResult = LabeledImage
WatershedResult = LabeledImage
ActiveContourResult = Contour
RegionGrowingResult = Union[LabeledImage, Tuple[LabeledImage, ProbabilityMap]]

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