ó
 ‰\c           @   s   d  Z  d d l Z d d l m Z d d l m Z d d l m	 Z	 m
 Z
 d „  Z d	 „  Z d
 „  Z d d d d e d „ Z d S(   s  watershed.py - watershed algorithm

This module implements a watershed algorithm that apportions pixels into
marked basins. The algorithm uses a priority queue to hold the pixels
with the metric for the priority queue being pixel value, then the time
of entry into the queue - this settles ties in favor of the closest marker.

Some ideas taken from
Soille, "Automated Basin Delineation from Digital Elevation Models Using
Mathematical Morphology", Signal Processing 20 (1990) 171-182.

The most important insight in the paper is that entry time onto the queue
solves two problems: a pixel should be assigned to the neighbor with the
largest gradient or, if there is no gradient, pixels on a plateau should
be split between markers on opposite sides.

Originally part of CellProfiler, code licensed under both GPL and BSD licenses.
Website: http://www.cellprofiler.org

Copyright (c) 2003-2009 Massachusetts Institute of Technology
Copyright (c) 2009-2011 Broad Institute
All rights reserved.

Original author: Lee Kamentsky
iÿÿÿÿN(   t   ndimagei   (   t
   _watershedi   (   t   cropt   regular_seedsc         C   så   t  | t j t t f ƒ s0 t |  j | ƒ } n3 | j |  j k rc t d j | j |  j ƒ ƒ ‚ n  | d k	 r | j |  j k r t d ƒ ‚ n  | d k r´ t j
 |  j t ƒ } n  |  j t j ƒ | j t j ƒ | j t j ƒ f S(   s|  Ensure that all inputs to watershed have matching shapes and types.

    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.
    s?   `markers` (shape {}) must have same shape as `image` (shape {})s&   `mask` must have same shape as `image`N(   t
   isinstancet   npt   ndarrayt   listt   tupleR   t   shapet
   ValueErrort   formatt   Nonet   onest   boolt   astypet   float64t   int32t   int8(   t   imaget   markerst   mask(    (    s;   lib/python2.7/site-packages/skimage/morphology/watershed.pyt   _validate_inputs"   s    	c         C   sÓ   | d k r d } n  t j | ƒ r9 t j |  | ƒ } n0 t j | t ƒ } | j |  k ri t d ƒ ‚ n  | d k rÉ t	 g  | j
 D] } | d d k ^ q‚ ƒ r° t d ƒ ‚ n  t j | j
 ƒ d } n  | | f S(   s$  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.
    i   s,   Connectivity dimension must be same as imagei   i    s2   Connectivity array must have an unambiguous centerN(   R   R   t   isscalart   ndit   generate_binary_structuret   arrayR   t   ndimR
   t   anyR	   (   t	   image_dimt   connectivityt   offsett   c_connectivityt   x(    (    s;   lib/python2.7/site-packages/skimage/morphology/watershed.pyt   _validate_connectivityJ   s    	,c         C   s‡   | j  ƒ  } d | t | ƒ <t j t j | ƒ ƒ } t j | j |  ƒ t j | |  ƒ } t j | | d d d ƒ} | t j | ƒ S(   sã  Compute offsets to a samples neighbors if the image would be raveled.

    Parameters
    ----------
    image_shape : tuple
        The shape of the image for which the offsets are computed.
    structure : ndarray
        A structuring element determining the neighborhood expressed as an
        n-D array of 1's and 0's.
    center : sequence
        Tuple of indices specifying the center of `selem`.

    Returns
    -------
    offsets : ndarray
        Linear offsets to a samples neighbors in the raveled image, sorted by
        their Euclidean distance from the center.

    Examples
    --------
    >>> _offsets_to_raveled_neighbors((4, 5), np.ones((4, 3)), (1, 1))
    array([-5, -1,  1,  5, -6, -4,  4,  6, 10,  9, 11])
    i    i   t   axisi   (	   t   copyR   R   t	   transposet   nonzerot   ravel_multi_indext   Tt   sumt   argsort(   t   image_shapet	   structuret   centert   connection_indicest   offsetst   squared_distances(    (    s;   lib/python2.7/site-packages/skimage/morphology/watershed.pyt   _offsets_to_raveled_neighbors{   s    i    c      	   C   s3  t  |  | | ƒ \ }  } } t |  j | | ƒ \ } } g  | D] } | | f ^ q= } t j |  | d d ƒ}  t j | | d d ƒj ƒ  } t j | | d d ƒ}	 t |  j | d | ƒ}
 t j |	 ƒ } t j	 |  j
 d t j ƒ|  j } t j |  j ƒ  | |
 | | | |	 j ƒ  | ƒ t |	 | d t ƒ}	 |	 S(   s™  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
    -----
    This function implements a watershed algorithm [1]_ [2]_ that apportions
    pixels into marked basins. The algorithm uses a priority queue to hold
    the pixels with the metric for the priority queue being pixel value, then
    the time of entry into the queue - this settles ties in favor of the
    closest marker.

    Some ideas taken from
    Soille, "Automated Basin Delineation from Digital Elevation Models Using
    Mathematical Morphology", Signal Processing 20 (1990) 171-182

    The most important insight in the paper is that entry time onto the queue
    solves two problems: a pixel should be assigned to the neighbor with the
    largest gradient or, if there is no gradient, pixels on a plateau should
    be split between markers on opposite sides.

    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
    --------
    The watershed algorithm is useful to separate overlapping objects.

    We first generate an initial image with two overlapping circles:

    >>> 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)

    Next, we want to separate the two circles. We generate markers at the
    maxima of the distance to the background:

    >>> 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]

    Finally, we run the watershed on the image and markers:

    >>> labels = watershed(-distance, markers, mask=image)

    The algorithm works also for 3-D images, and can be used for example to
    separate overlapping spheres.
    t   modet   constantR-   t   dtypeR$   (   R   R"   R   R   t   padt   ravelR1   R	   t   flatnonzeroR   t   stridest   intpt   itemsizeR   t   watershed_raveledR   t   True(   R   R   R   R   R   t   compactnesst   watershed_linet   pt	   pad_widtht   outputt   flat_neighborhoodt   marker_locationst   image_strides(    (    s;   lib/python2.7/site-packages/skimage/morphology/watershed.pyt	   watershedœ   s$    k"		(   t   __doc__t   numpyR   t   scipyR    R   t    R   t   utilR   R   R   R"   R1   R   t   FalseRE   (    (    (    s;   lib/python2.7/site-packages/skimage/morphology/watershed.pyt   <module>   s   	(	1	!	