Comprehensive image processing and computer vision library for Python with algorithms for filtering, morphology, segmentation, and feature detection
—
Image measurement and analysis functions for extracting quantitative information from images. Includes region properties, geometric measurements, image moments, contour analysis, and statistical measures.
Measure properties of labeled regions in images including geometric, intensity, and shape characteristics.
def regionprops(label_image, intensity_image=None, cache=True, coordinates=None, separator='-', extra_properties=None):
"""
Measure properties of labeled image regions.
Parameters:
label_image : array_like
Labeled input image
intensity_image : array_like, optional
Intensity image for intensity measurements
cache : bool, optional
Cache computed properties
coordinates : str, optional
Coordinate system ('rc' or 'xy')
separator : str, optional
Separator for property names
extra_properties : iterable, optional
Additional property functions
Returns:
list
List of RegionProperties objects
"""
def regionprops_table(label_image, intensity_image=None, properties=('label', 'bbox'), cache=True, separator='-', extra_properties=None):
"""
Compute region properties and return as table.
Parameters:
label_image : array_like
Labeled input image
intensity_image : array_like, optional
Intensity image for intensity measurements
properties : tuple, optional
Properties to compute
cache : bool, optional
Cache computed properties
separator : str, optional
Separator for property names
extra_properties : iterable, optional
Additional property functions
Returns:
dict
Dictionary of property arrays
"""
def label(image, background=None, return_num=False, connectivity=None):
"""
Label connected components in binary image.
Parameters:
image : array_like
Binary input image
background : int, optional
Background value
return_num : bool, optional
Return number of labels
connectivity : int, optional
Pixel connectivity
Returns:
ndarray or tuple
Labeled image and optionally number of labels
"""Find and analyze image contours for shape analysis and boundary detection.
def find_contours(image, level=0.5, fully_connected='low', positive_orientation='low', mask=None):
"""
Find iso-valued contours in a 2D array.
Parameters:
image : array_like
2D input array
level : float, optional
Value along which to find contours
fully_connected : str, optional
Connectivity mode ('low' or 'high')
positive_orientation : str, optional
Orientation mode ('low' or 'high')
mask : array_like, optional
Mask limiting contour detection
Returns:
list
List of contour coordinate arrays
"""
def approximate_polygon(coords, tolerance):
"""
Approximate polygon using Douglas-Peucker algorithm.
Parameters:
coords : array_like
Polygon coordinates
tolerance : float
Maximum distance from original polygon
Returns:
ndarray
Approximated polygon coordinates
"""
def subdivide_polygon(coords, degree=2, preserve_ends=False):
"""
Subdivide polygon by inserting new vertices.
Parameters:
coords : array_like
Polygon coordinates
degree : int, optional
Degree of B-spline used for subdivision
preserve_ends : bool, optional
Whether to preserve end points
Returns:
ndarray
Subdivided polygon coordinates
"""Measure basic geometric properties of image regions and objects.
def perimeter(image, neighbourhood=4):
"""
Calculate perimeter of objects in binary image.
Parameters:
image : array_like
Binary input image
neighbourhood : int, optional
Connectivity (4 or 8 for 2D)
Returns:
float
Perimeter length
"""
def perimeter_crofton(image, directions=4):
"""
Calculate perimeter using Crofton formula.
Parameters:
image : array_like
Binary input image
directions : int, optional
Number of directions for line integral
Returns:
float
Perimeter estimate
"""
def euler_number(image, connectivity=None):
"""
Calculate Euler number (topological invariant).
Parameters:
image : array_like
Binary input image
connectivity : int, optional
Pixel connectivity
Returns:
int
Euler number
"""
def centroid(image):
"""
Calculate centroid of binary image.
Parameters:
image : array_like
Binary input image
Returns:
tuple
Centroid coordinates
"""Compute various types of image moments for shape analysis and recognition.
def moments(image, order=3):
"""
Calculate raw image moments.
Parameters:
image : array_like
Input image
order : int, optional
Maximum moment order
Returns:
ndarray
Raw moments array
"""
def moments_central(image, center=None, order=3):
"""
Calculate central moments.
Parameters:
image : array_like
Input image
center : tuple, optional
Center point for moments
order : int, optional
Maximum moment order
Returns:
ndarray
Central moments array
"""
def moments_normalized(mu, order=3):
"""
Calculate normalized central moments.
Parameters:
mu : array_like
Central moments array
order : int, optional
Maximum moment order
Returns:
ndarray
Normalized moments array
"""
def moments_hu(nu):
"""
Calculate Hu moment invariants.
Parameters:
nu : array_like
Normalized central moments
Returns:
ndarray
Hu moment invariants
"""
def moments_coords(coords, order=3):
"""
Calculate moments from coordinate list.
Parameters:
coords : array_like
Coordinate array
order : int, optional
Maximum moment order
Returns:
ndarray
Raw moments array
"""
def moments_coords_central(coords, center=None, order=3):
"""
Calculate central moments from coordinates.
Parameters:
coords : array_like
Coordinate array
center : tuple, optional
Center point for moments
order : int, optional
Maximum moment order
Returns:
ndarray
Central moments array
"""Compute inertia tensors and principal axes for shape orientation analysis.
def inertia_tensor(image, mu=None):
"""
Compute inertia tensor of image.
Parameters:
image : array_like
Input binary image
mu : array_like, optional
Central moments array
Returns:
ndarray
Inertia tensor matrix
"""
def inertia_tensor_eigvals(image, mu=None, T=None):
"""
Compute eigenvalues of inertia tensor.
Parameters:
image : array_like
Input binary image
mu : array_like, optional
Central moments array
T : array_like, optional
Inertia tensor matrix
Returns:
ndarray
Eigenvalues of inertia tensor
"""Analyze three-dimensional image data including surface extraction and volume measurements.
def marching_cubes(volume, level=None, spacing=(1.0, 1.0, 1.0), gradient_direction='descent', step_size=1, allow_degenerate=True, mask=None, method='lewiner'):
"""
Generate mesh from 3D volume using marching cubes.
Parameters:
volume : array_like
Input 3D volume
level : float, optional
Contour value for surface extraction
spacing : tuple, optional
Voxel spacing
gradient_direction : str, optional
Direction of gradient ('descent' or 'ascent')
step_size : int, optional
Step size for sampling
allow_degenerate : bool, optional
Allow degenerate triangles
mask : array_like, optional
Mask limiting extraction region
method : str, optional
Algorithm variant ('lewiner' or 'classic')
Returns:
tuple
(vertices, faces, normals, values)
"""
def mesh_surface_area(verts, faces):
"""
Calculate surface area of triangular mesh.
Parameters:
verts : array_like
Vertex coordinates
faces : array_like
Face connectivity
Returns:
float
Total surface area
"""Extract intensity profiles along lines and curves for quantitative analysis.
def profile_line(image, src, dst, linewidth=1, order=None, mode='constant', cval=0.0, reduce_func=None):
"""
Extract intensity profile along line.
Parameters:
image : array_like
Input image
src : tuple
Start point coordinates
dst : tuple
End point coordinates
linewidth : int, optional
Width of profile line
order : int, optional
Interpolation order
mode : str, optional
Boundary condition mode
cval : float, optional
Constant value for boundaries
reduce_func : callable, optional
Function to reduce values across line width
Returns:
ndarray
Intensity profile array
"""Fit geometric models to point data using robust estimation methods.
class LineModelND:
"""
N-dimensional line model for RANSAC fitting.
"""
def estimate(self, data):
"""Estimate line from data points."""
pass
def residuals(self, data):
"""Calculate residuals for data points."""
pass
class CircleModel:
"""
Circle model for RANSAC fitting.
"""
def estimate(self, data):
"""Estimate circle from data points."""
pass
def residuals(self, data):
"""Calculate residuals for data points."""
pass
class EllipseModel:
"""
Ellipse model for RANSAC fitting.
"""
def estimate(self, data):
"""Estimate ellipse from data points."""
pass
def residuals(self, data):
"""Calculate residuals for data points."""
pass
def ransac(data, model_class, min_samples, residual_threshold, is_data_valid=None, is_model_valid=None, max_trials=100, stop_sample_num=np.inf, stop_residuals_sum=0, stop_probability=0.99, random_state=None, initial_inliers=None):
"""
Fit model to data using RANSAC algorithm.
Parameters:
data : array_like
Input data points
model_class : class
Model class to fit
min_samples : int
Minimum samples needed to fit model
residual_threshold : float
Maximum residual for inliers
is_data_valid : callable, optional
Function to check data validity
is_model_valid : callable, optional
Function to check model validity
max_trials : int, optional
Maximum number of iterations
stop_sample_num : int, optional
Stop when this many inliers found
stop_residuals_sum : float, optional
Stop when residuals sum below this
stop_probability : float, optional
Stop probability
random_state : RandomState, optional
Random number generator
initial_inliers : array_like, optional
Initial inlier indices
Returns:
tuple
(model, inliers)
"""from skimage import data, measure, segmentation
import matplotlib.pyplot as plt
# Load and segment image
image = data.coins()
thresh = image > filters.threshold_otsu(image)
labeled = measure.label(thresh)
# Measure region properties
props = measure.regionprops(labeled, intensity_image=image)
# Display results
fig, ax = plt.subplots()
ax.imshow(image, cmap='gray')
for prop in props:
y0, x0 = prop.centroid
orientation = prop.orientation
x1 = x0 + np.cos(orientation) * 0.5 * prop.axis_minor_length
y1 = y0 - np.sin(orientation) * 0.5 * prop.axis_minor_length
x2 = x0 - np.sin(orientation) * 0.5 * prop.axis_major_length
y2 = y0 - np.cos(orientation) * 0.5 * prop.axis_major_length
ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5)
ax.plot((x0, x2), (y0, y2), '-b', linewidth=2.5)
ax.plot(x0, y0, '.g', markersize=15)
print(f"Found {len(props)} objects")
print(f"Mean area: {np.mean([p.area for p in props]):.1f}")from skimage import data, measure
import matplotlib.pyplot as plt
# Load image
image = data.camera()
# Find contours at different levels
contours_low = measure.find_contours(image, 0.3)
contours_high = measure.find_contours(image, 0.7)
# Display contours
fig, ax = plt.subplots()
ax.imshow(image, cmap='gray')
for contour in contours_low:
ax.plot(contour[:, 1], contour[:, 0], linewidth=2, color='red')
for contour in contours_high:
ax.plot(contour[:, 1], contour[:, 0], linewidth=2, color='blue')
print(f"Low level contours: {len(contours_low)}")
print(f"High level contours: {len(contours_high)}")from typing import List, Tuple, Optional, Union, Callable
from numpy.typing import NDArray
import numpy as np
# Region properties
RegionProperties = object
PropertiesTable = dict
# Contours and shapes
Contour = NDArray[np.floating]
ContourList = List[Contour]
Polygon = NDArray[np.floating]
# Moments and measurements
MomentArray = NDArray[np.floating]
InertiaTensor = NDArray[np.floating]
GeometricMeasurement = Union[float, int, Tuple[float, ...]]
# 3D analysis
MeshVertices = NDArray[np.floating]
MeshFaces = NDArray[np.integer]
MeshNormals = NDArray[np.floating]
MeshData = Tuple[MeshVertices, MeshFaces, MeshNormals, NDArray[np.floating]]
# Model fitting
GeometricModel = Union[LineModelND, CircleModel, EllipseModel]
RANSACResult = Tuple[GeometricModel, NDArray[np.bool_]]Install with Tessl CLI
npx tessl i tessl/pypi-scikit-image