“”“ watershed.py-分水岭算法 该模块实现了分水岭算法,可将像素分配到标记的盆地中。 该算法使用优先级队列来保存像素,优先级队列的度量标准是像素值,然后输入队列的时间-这将使关系更加紧密,有利于最接近的标记。 一些想法取自Soille,“使用数学形态从数字高程模型自动进行盆地划定”,信号处理20(1990)171-182。 该论文最重要的见解是,进入队列的时间解决了两个问题:应将像素分配给具有最大梯度的邻居,或者,如果没有梯度,则应将高原上的像素分配在相对侧的标记之间。 最初是CellProfiler的一部分,代码已获得GPL和BSD许可。 网址:http://www.cellprofiler.org 版权所有(c)2003-2009麻省理工学院 版权所有(c)2009-2011 Broad Institute 版权所有。 原作者:Lee Kamentsky
import numpy as np
from scipy import ndimage as ndi
from . import _watershed
from ..util import crop, regular_seeds
def _validate_inputs(image, markers, mask):
"""确保分水岭算法的所有输入都具有相同的形状和类型。
Parameters
----------
image : array
The input image.
markers : int or array of int
The marker image.
mask : array, or None
A boolean mask, True where we want to compute the watershed.
Returns
-------
image, markers, mask : arrays
The validated and formatted arrays. Image will have dtype float64,
markers int32, and mask int8. If ``None`` was given for the mask,
it is a volume of all 1s.
Raises
------
ValueError
If the shapes of the given arrays don't match.
"""
if not isinstance(markers, (np.ndarray, list, tuple)):
# not array-like, assume int
markers = regular_seeds(image.shape, markers)
elif markers.shape != image.shape:
raise ValueError("`markers` (shape {}) must have same shape "
"as `image` (shape {})".format(markers.shape, image.shape))
if mask is not None and mask.shape != image.shape:
raise ValueError("`mask` must have same shape as `image`")
if mask is None:
# Use a complete `True` mask if none is provided
mask = np.ones(image.shape, bool)
return (image.astype(np.float64),
markers.astype(np.int32),
mask.astype(np.int8))
def _validate_connectivity(image_dim, connectivity, offset):
"""Convert any valid connectivity to a structuring element and offset.
Parameters
----------
image_dim : int
The number of dimensions of the input image.
connectivity : int, array, or None
The neighborhood connectivity. An integer is interpreted as in
``scipy.ndimage.generate_binary_structure``, as the maximum number
of orthogonal steps to reach a neighbor. An array is directly
interpreted as a structuring element and its shape is validated against
the input image shape. ``None`` is interpreted as a connectivity of 1.
offset : tuple of int, or None
The coordinates of the center of the structuring element.
Returns
-------
c_connectivity : array of bool
The structuring element corresponding to the input `connectivity`.
offset : array of int
The offset corresponding to the center of the structuring element.
Raises
------
ValueError:
If the image dimension and the connectivity or offset dimensions don't
match.
"""
if connectivity is None:
connectivity = 1
if np.isscalar(connectivity):
c_connectivity = ndi.generate_binary_structure(image_dim, connectivity)
else:
c_connectivity = np.array(connectivity, bool)
if c_connectivity.ndim != image_dim:
raise ValueError("Connectivity dimension must be same as image")
if offset is None:
if any([x % 2 == 0 for x in c_connectivity.shape]):
raise ValueError("Connectivity array must have an unambiguous "
"center")
offset = np.array(c_connectivity.shape) // 2
return c_connectivity, offset
def _compute_neighbors(image, structure, offset):
"""Compute neighborhood as an array of linear offsets into the image.
These are sorted according to Euclidean distance from the center (given
by `offset`), ensuring that immediate neighbors are visited first.
"""
structure[tuple(offset)] = 0 # ignore the center; it's not a neighbor
locations = np.transpose(np.nonzero(structure))
sqdistances = np.sum((locations - offset)**2, axis=1)
neighborhood = (np.ravel_multi_index(locations.T, image.shape) -
np.ravel_multi_index(offset, image.shape)).astype(np.int32)
sorted_neighborhood = neighborhood[np.argsort(sqdistances)]
return sorted_neighborhood
def watershed(image, markers, connectivity=1, offset=None, mask=None,
compactness=0, watershed_line=False):
"""Find watershed basins in `image` flooded from given `markers`.
Parameters
----------
image: ndarray (2-D, 3-D, ...) of integers
Data array where the lowest value points are labeled first.
markers: int, or ndarray of int, same shape as `image`
The desired number of markers, or an array marking the basins with the
values to be assigned in the label matrix. Zero means not a marker.
connectivity: ndarray, optional
An array with the same number of dimensions as `image` whose
non-zero elements indicate neighbors for connection.
Following the scipy convention, default is a one-connected array of
the dimension of the image.
offset: array_like of shape image.ndim, optional
offset of the connectivity (one offset per dimension)
mask: ndarray of bools or 0s and 1s, optional
Array of same shape as `image`. Only points at which mask == True
will be labeled.
compactness : float, optional
Use compact watershed [3]_ with given compactness parameter.
Higher values result in more regularly-shaped watershed basins.
watershed_line : bool, optional
If watershed_line is True, a one-pixel wide line separates the regions
obtained by the watershed algorithm. The line has the label 0.
Returns
-------
out: ndarray
A labeled matrix of the same type and shape as markers
See also
--------
skimage.segmentation.random_walker: random walker segmentation
A segmentation algorithm based on anisotropic diffusion, usually
slower than the watershed but with good results on noisy data and
boundaries with holes.
Notes
-----
此函数实现了分水岭算法[1] _ [2] _,可将像素分配到标记的盆地中。 该算法使用优先级队列来保存
像素,优先级队列的度量标准是像素值,其次是输入队列的时间-这将使关系更加紧密,有利于最接近的
标记。
Some ideas taken from
Soille, "Automated Basin Delineation from Digital Elevation Models Using
Mathematical Morphology", Signal Processing 20 (1990) 171-182
该论文最重要的见解是,进入队列的时间解决了两个问题:应将像素分配给具有最大梯度的邻居,或者,如果没有梯度,则应将高原上的像素分配在相对侧的标记之间 。
This implementation converts all arguments to specific, lowest common
denominator types, then passes these to a C algorithm.
Markers can be determined manually, or automatically using for example
the local minima of the gradient of the image, or the local maxima of the
distance function to the background for separating overlapping objects
(see example).
References
----------
.. [1] http://en.wikipedia.org/wiki/Watershed_%28image_processing%29
.. [2] http://cmm.ensmp.fr/~beucher/wtshed.html
.. [3] Peer Neubert & Peter Protzel (2014). Compact Watershed and
Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation
Algorithms. ICPR 2014, pp 996-1001. DOI:10.1109/ICPR.2014.181
https://www.tu-chemnitz.de/etit/proaut/forschung/rsrc/cws_pSLIC_ICPR.pdf
Examples 分水岭算法可用于分离重叠的对象。 我们首先生成带有两个重叠圆的初始图像: >>> x, y = np.indices((80, 80)) >>> x1, y1, x2, y2 = 28, 28, 44, 52 >>> r1, r2 = 16, 20 >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2 >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2 >>> image = np.logical_or(mask_circle1, mask_circle2) 接下来,我们要将两个圆圈分开。 我们在距背景的最大距离处生成标记: >>> from scipy import ndimage as ndi >>> distance = ndi.distance_transform_edt(image) >>> from skimage.feature import peak_local_max >>> local_maxi = peak_local_max(distance, labels=image, ... footprint=np.ones((3, 3)), ... indices=False) >>> markers = ndi.label(local_maxi)[0] 最后,我们对图像和标记运行分水岭: >>> labels = watershed(-distance, markers, mask=image)
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。