π¬ Advanced Python scikit-image Cheat Sheet #
A guide to advanced image processing and analysis with scikit-image, focusing on scientific applications and best practices.
βοΈ Core Concepts & Data Types #
- NumPy-centric:
scikit-imageoperates directly on NumPy arrays, making it seamless to integrate with the scientific Python ecosystem. - Data Type Conventions:
scikit-imagehas specific conventions for data types and ranges. It’s crucial to use the provided utility functions for conversions to avoid unexpected results.uint8: 0 to 255float: -1 to 1 (or 0 to 1 for some functions). Useskimage.img_as_float()andskimage.img_as_ubyte().
import skimage
from skimage import data, io
from skimage.util import img_as_float, img_as_ubyte
# Load a sample image (returns a NumPy array)
image = data.camera()
# Convert to float for processing
image_float = img_as_float(image)
print(f'Original dtype: {image.dtype}, Range: ({image.min()}, {image.max()})')
print(f'Float dtype: {image_float.dtype}, Range: ({image_float.min():.2f}, {image_float.max():.2f})')
- Colorspaces: Use the
skimage.colormodule for robust colorspace conversions (e.g.,rgb2gray,rgb2hsv).
from skimage.color import rgb2gray, rgb2hsv
# Load a color image
color_image = data.astronaut()
# Convert to grayscale
gray_image = rgb2gray(color_image)
# Convert to HSV
hsv_image = rgb2hsv(color_image)
π§Ό Image Filtering & Preprocessing #
Local & Non-Local Filters #
- Local Filters: Operate on a neighborhood of pixels.
filters.gaussian(): For smoothing and noise reduction.filters.sobel(): For edge detection (gradient magnitude).filters.median(): Excellent for salt-and-pepper noise.
- Non-Local Filters: Use a larger portion of the image.
restoration.denoise_nl_means(): Non-local means denoising, great for preserving texture.restoration.denoise_tv_chambolle(): Total variation denoising, good for piecewise-constant images.
from skimage import filters
from skimage import restoration
# Gaussian filter
smoothed_image = filters.gaussian(image_float, sigma=1.0)
# Sobel edge detection
edges = filters.sobel(image_float)
# Total Variation Denoising
denoised_image = restoration.denoise_tv_chambolle(image_float, weight=0.1)
Mathematical Morphology #
Used for probing and shaping images, typically on binary (boolean) images.
from skimage import morphology
# Create a binary image first (e.g., via thresholding)
threshold = filters.threshold_otsu(image)
binary_image = image > threshold
# Define a structuring element (shape to probe with)
selem = morphology.disk(6)
# Erosion: Shrinks bright regions
eroded_image = morphology.binary_erosion(binary_image, selem)
# Dilation: Expands bright regions
dilated_image = morphology.binary_dilation(binary_image, selem)
# Opening: Erosion then Dilation (removes small bright spots)
opened_image = morphology.binary_opening(binary_image, selem)
# Closing: Dilation then Erosion (fills small dark holes)
closed_image = morphology.binary_closing(binary_image, selem)
π¬ Image Segmentation #
Partitioning an image into multiple segments or objects.
Thresholding-based #
filters.threshold_otsu(): Finds an optimal threshold to separate foreground and background based on histogram variance.filters.threshold_local(): Adaptive thresholding for images with varying illumination.
Marker-based (Advanced) #
- Watershed Algorithm: Treats the image as a topographic map. Good for separating touching objects.
- Random Walker: A probabilistic method where labels diffuse from initial seeds.
from scipy import ndimage as ndi
from skimage.feature import peak_local_max
# Watershed example for separating touching objects
distance = ndi.distance_transform_edt(binary_image)
local_maxi = peak_local_max(distance, indices=False, footprint=np.ones((3, 3)),
labels=binary_image)
markers = morphology.label(local_maxi)
labels = morphology.watershed(-distance, markers, mask=binary_image)
π Feature Detection & Measurement #
Feature Detection #
feature.canny(): Popular and effective edge detector.feature.corner_harris()&feature.corner_peaks(): For detecting corners.feature.blob_dog(),feature.blob_log(),feature.blob_doh(): For detecting blobs of different sizes.
from skimage import feature
# Canny edge detection
canny_edges = feature.canny(image_float, sigma=1.5)
# Detect corners
corners = feature.corner_peaks(feature.corner_harris(image_float), min_distance=5)
# Detect blobs using Difference of Gaussian
blobs_dog = feature.blob_dog(image_float, max_sigma=30, threshold=.1)
Measuring Region Properties #
After segmentation, measure.regionprops() is incredibly powerful for quantifying the properties of labeled regions.
from skimage import measure
# `labels` is an image where each object has a unique integer label
props = measure.regionprops(labels)
# Iterate through properties of each detected object
for prop in props:
print(f'Label: {prop.label} Area: {prop.area} Centroid: {prop.centroid}')
# Other properties: eccentricity, perimeter, bounding_box, etc.
# Create a table of properties
props_table = measure.regionprops_table(labels, properties=('label', 'area', 'perimeter'))
import pandas as pd
df = pd.DataFrame(props_table)
print(df.head())
πΌοΈ Transformations #
Geometric transformations of images.
from skimage import transform
# Rescale image
rescaled_image = transform.rescale(image_float, 0.5, anti_aliasing=True)
# Rotate image
rotated_image = transform.rotate(image_float, angle=30)
# Affine transform
tform = transform.AffineTransform(scale=(1.2, 1.2), rotation=1, shear=0.1)
warped_image = transform.warp(image_float, tform)