ó
 ‰\c           @@  s  d  Z  d d l m Z d d l Z d d l m Z d d l m	 Z	 m
 Z
 m Z d d l m Z d d	 l m Z d d
 l m Z d d l m Z d „  Z d „  Z d d „ Z d d „ Z d „  Z d „  Z d „  Z d d e e d „ Z d d e e d „ Z d S(   s  extrema.py - local minima and maxima

This module provides functions to find local maxima and minima of an image.
Here, local maxima (minima) are defined as connected sets of pixels with equal
gray level which is strictly greater (smaller) than the gray level of all
pixels in direct neighborhood of the connected set. In addition, the module
provides the related functions h-maxima and h-minima.

Soille, P. (2003). Morphological Image Analysis: Principles and Applications
(2nd ed.), Chapter 6. Springer-Verlag New York, Inc.
i    (   t   absolute_importN(   t   ndimagei   (   t   dtype_limitst   invertt   crop(   t   warni   (   t   greyreconstruct(   t   _offsets_to_raveled_neighbors(   t   _local_maximac         C@  sY   t  |  d t ƒ\ } } | | | k r7 t d ƒ ‚ n  |  | } | | |  | | k <| S(   sI   Add constant to the image while handling overflow issues gracefully.
    t   clip_negatives=   The added constant is not compatiblewith the image data type.(   R   t   Falset
   ValueError(   t   imaget   const_valuet	   min_dtypet	   max_dtypet   result(    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   _add_constant_clip   s    
c         C@  sY   t  |  d t ƒ\ } } | | | k r7 t d ƒ ‚ n  |  | } | | |  | | k  <| S(   sB   Subtract constant from image while handling underflow issues.
    R	   sB   The subtracted constant is not compatiblewith the image data type.(   R   R
   R   (   R   R   R   R   R   (    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   _subtract_constant_clip'   s    
c   	      C@  sÍ   t  j |  j t  j ƒ ra d t  j |  j ƒ j } | | k  rF | } n  | | d } |  | } n t |  | ƒ } | } t j | |  d d d | ƒ} |  | } t  j	 |  j
 d t  j ƒ} d | | | k <| S(   s…  Determine all maxima of the image with height >= h.

    The local maxima are defined as connected sets of pixels with equal
    grey level strictly greater than the grey level of all pixels in direct
    neighborhood of the set.

    A local maximum M of height h is a local maximum for which
    there is at least one path joining M with a higher maximum on which the
    minimal value is f(M) - h (i.e. the values along the path are not
    decreasing by more than h with respect to the maximum's value) and no
    path for which the minimal value is greater.

    Parameters
    ----------
    image : ndarray
        The input image for which the maxima are to be calculated.
    h : unsigned integer
        The minimal height of all extracted maxima.
    selem : ndarray, optional
        The neighborhood expressed as an n-D array of 1's and 0's.
        Default is the ball of radius 1 according to the maximum norm
        (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.)

    Returns
    -------
    h_max : ndarray
       The maxima of height >= h. The result image is a binary image, where
       pixels belonging to the selected maxima take value 1, the others
       take value 0.

    See also
    --------
    skimage.morphology.extrema.h_minima
    skimage.morphology.extrema.local_maxima
    skimage.morphology.extrema.local_minima

    References
    ----------
    .. [1] Soille, P., "Morphological Image Analysis: Principles and
           Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883.

    Examples
    --------
    >>> import numpy as np
    >>> from skimage.morphology import extrema

    We create an image (quadratic function with a maximum in the center and
    4 additional constant maxima.
    The heights of the maxima are: 1, 21, 41, 61, 81, 101

    >>> w = 10
    >>> x, y = np.mgrid[0:w,0:w]
    >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2)
    >>> f[2:4,2:4] = 40; f[2:4,7:9] = 60; f[7:9,2:4] = 80; f[7:9,7:9] = 100
    >>> f = f.astype(np.int)

    We can calculate all maxima with a height of at least 40:

    >>> maxima = extrema.h_maxima(f, 40)

    The resulting image will contain 4 local maxima.
    i   g       @t   methodt   dilationt   selemt   dtypei   (   t   npt
   issubdtypeR   t   floatingt   finfot
   resolutionR   R   t   reconstructiont   zerost   shapet   uint8(	   R   t   hR   R   t   h_correctedt   shifted_imgt   rec_imgt   residue_imgt   h_max(    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   h_maxima5   s    ?	
c   	      C@  sÍ   t  j |  j t  j ƒ ra d t  j |  j ƒ j } | | k  rF | } n  | | d } |  | } n t |  | ƒ } | } t j | |  d d d | ƒ} | |  } t  j	 |  j
 d t  j ƒ} d | | | k <| S(   s‰  Determine all minima of the image with depth >= h.

    The local minima are defined as connected sets of pixels with equal
    grey level strictly smaller than the grey levels of all pixels in direct
    neighborhood of the set.

    A local minimum M of depth h is a local minimum for which
    there is at least one path joining M with a deeper minimum on which the
    maximal value is f(M) + h (i.e. the values along the path are not
    increasing by more than h with respect to the minimum's value) and no
    path for which the maximal value is smaller.

    Parameters
    ----------
    image : ndarray
        The input image for which the minima are to be calculated.
    h : unsigned integer
        The minimal depth of all extracted minima.
    selem : ndarray, optional
        The neighborhood expressed as an n-D array of 1's and 0's.
        Default is the ball of radius 1 according to the maximum norm
        (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.)

    Returns
    -------
    h_min : ndarray
       The minima of depth >= h. The result image is a binary image, where
       pixels belonging to the selected minima take value 1, the other pixels
       take value 0.

    See also
    --------
    skimage.morphology.extrema.h_maxima
    skimage.morphology.extrema.local_maxima
    skimage.morphology.extrema.local_minima

    References
    ----------
    .. [1] Soille, P., "Morphological Image Analysis: Principles and
           Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883.

    Examples
    --------
    >>> import numpy as np
    >>> from skimage.morphology import extrema

    We create an image (quadratic function with a minimum in the center and
    4 additional constant maxima.
    The depth of the minima are: 1, 21, 41, 61, 81, 101

    >>> w = 10
    >>> x, y = np.mgrid[0:w,0:w]
    >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2)
    >>> f[2:4,2:4] = 160; f[2:4,7:9] = 140; f[7:9,2:4] = 120; f[7:9,7:9] = 100
    >>> f = f.astype(np.int)

    We can calculate all minima with a depth of at least 40:

    >>> minima = extrema.h_minima(f, 40)

    The resulting image will contain 4 local minima.
    i   g       @R   t   erosionR   R   i   (   R   R   R   R   R   R   R   R   R   R   R   R   (	   R   R    R   R   R!   R"   R#   R$   t   h_min(    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   h_minima†   s    ?	
c         C@  s\   xU t  |  j ƒ D]D } t d ƒ g |  j } d | | <| |  | <d | | <| |  | <q Wd S(   sÙ  Set edge values along all axes to a constant value.

    Parameters
    ----------
    image : ndarray
        The array to modify inplace.
    value : scalar
        The value to use. Should be compatible with `image`'s dtype.

    Examples
    --------
    >>> image = np.zeros((4, 5), dtype=int)
    >>> _set_edge_values_inplace(image, 1)
    >>> image
    array([[1, 1, 1, 1, 1],
           [1, 0, 0, 0, 1],
           [1, 0, 0, 0, 1],
           [1, 1, 1, 1, 1]])
    i    iÿÿÿÿN(   t   ranget   ndimt   slicet   None(   R   t   valuet   axist   sl(    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   _set_edge_values_inplace×   s    


c         C@  sn   t  j |  j ƒ d } t  j | d |  j d d ƒ} t d „  t |  j ƒ Dƒ ƒ } |  | | <t | | ƒ | S(   së  Pad an array on all axes with one constant value.

    Parameters
    ----------
    image : ndarray
        Image to pad.
    value : scalar
         The value to use. Should be compatible with `image`'s dtype.

    Returns
    -------
    padded_image : ndarray
        The new image.

    Notes
    -----
    The output of this function is equivalent to::

        np.pad(image, mode="constant", constant_values=value)

    However this method needs to only allocate and copy once which can result
    in significant speed gains if `image` is large.

    Examples
    --------
    >>> _fast_pad(np.zeros((2, 3), dtype=int), 4)
    array([[4, 4, 4, 4, 4],
           [4, 0, 0, 0, 4],
           [4, 0, 0, 0, 4],
           [4, 4, 4, 4, 4]])
    i   R   t   ordert   Cc         s@  s   |  ] } t  d  d ƒ Vq d S(   i   iÿÿÿÿN(   R,   (   t   .0t   _(    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pys	   <genexpr>  s    (	   R   t   arrayR   t   emptyR   t   tupleR*   R+   R1   (   R   R.   t	   new_shapet	   new_imaget   original_slice(    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt	   _fast_padõ   s    !
c         C@  s•   |  d k r6 | d k r! | } n  t j | | ƒ }  n[ t j |  d t ƒ}  |  j | k ri t d ƒ ‚ n  t d „  |  j	 Dƒ ƒ r‘ t d ƒ ‚ n  |  S(   s  Validate or create structuring element for use in `local_maxima`.

    Depending on the values of `connectivity` and `selem` this function
    either creates a new structuring element (`selem` is None) using
    `connectivity` or validates the given structuring element (`selem` is not
    None).

    Parameters
    ----------
    selem : array-like or None
        The structuring element to validate. See same argument in
        `local_maxima`.
    connectivity : int or None
        A number used to determine the neighborhood of each evaluated pixel.
        See same argument in `local_maxima`.
    ndim : int
        Number of dimensions `selem` ought to have.

    Returns
    -------
    selem : ndarray
        Validated or new structuring element specifying the neighborhood.
    R   sE   structuring element and image must have the same number of dimensionsc         s@  s   |  ] } | d  k Vq d S(   i   N(    (   R4   t   s(    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pys	   <genexpr>H  s    s.   dimension size in structuring element is not 3N(
   R-   t   ndit   generate_binary_structureR   t   asarrayt   boolR+   R   t   anyR   (   R   t   connectivityR+   (    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   _resolve_neighborhood"  s    	c         C@  s—  t  j |  d d ƒ}  |  j d k rS | r7 t  j |  ƒ St  j |  j d t  j ƒSn  | rq t |  |  j ƒ  ƒ }  n  t  j |  j d t  j ƒ} t	 | d d ƒt
 d „  |  j Dƒ ƒ rÈ t d d	 d ƒnŒ t | | |  j ƒ } t |  j | d
 d |  j ƒ} y  t |  j ƒ  | j ƒ  | ƒ Wn5 t k
 rS|  j t  j k rMt d ƒ ‚ qT‚  n X| rlt | d ƒ } n t	 | d d ƒ| rt  j | ƒ S| Sd S(   s  Find local maxima of n-dimensional array.

    The local maxima are defined as connected sets of pixels with equal gray
    level (plateaus) strictly greater than the gray levels of all pixels in the
    neighborhood.

    Parameters
    ----------
    image : ndarray
        An n-dimensional array.
    selem : ndarray, optional
        A structuring element used to determine the neighborhood of each
        evaluated pixel. It must contain only 1's and 0's, have the same number
        of dimensions as `image`. If not given, all adjacent pixels are
        considered as part of the neighborhood.
    connectivity : int, optional
        A number used to determine the neighborhood of each evaluated pixel.
        Adjacent pixels whose squared distance from the center is larger or
        equal to `connectivity` are considered neighbors. Ignored if
        `selem` is not None.
    indices : bool, optional
        If True, the output will be a tuple of one-dimensional arrays
        representing the indices of local maxima in each dimension. If False,
        the output will be an array of 0's and 1's with the same shape as
        `image`.
    allow_borders : bool, optional
        If true, plateaus that touch the image border are valid maxima.

    Returns
    -------
    maxima : ndarray or tuple[ndarray]
        If `indices` is false, an array with the same shape as `image` is
        returned with 1's indicating the position of local maxima
        (0 otherwise). If `indices` is true, a tuple of one-dimensional arrays
        containing the coordinates (indices) of all found maxima.

    Warns
    -----
    UserWarning
        If `allow_borders` is false and any dimension of the given `image` is
        shorter than 3 samples, maxima can't exist and a warning is shown.

    See Also
    --------
    skimage.morphology.local_minima
    skimage.morphology.h_maxima
    skimage.morphology.h_minima

    Notes
    -----
    This function operates on the following ideas:

    1. Make a first pass over the image's last dimension and flag candidates
       for local maxima by comparing pixels in only one direction.
       If the pixels aren't connected in the last dimension all pixels are
       flagged as candidates instead.

    For each candidate:

    2. Perform a flood-fill to find all connected pixels that have the same
       gray value and are part of the plateau.
    3. Consider the connected neighborhood of a plateau: if no bordering sample
       has a higher gray level, mark the plateau as a definite local maximum.

    Examples
    --------
    >>> from skimage.morphology import local_maxima
    >>> image = np.zeros((4, 7), dtype=int)
    >>> image[1:3, 1:3] = 1
    >>> image[3, 0] = 1
    >>> image[1:3, 4:6] = 2
    >>> image[3, 6] = 3
    >>> image
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 1, 1, 0, 2, 2, 0],
           [0, 1, 1, 0, 2, 2, 0],
           [1, 0, 0, 0, 0, 0, 3]])

    Find local maxima by comparing to all neighboring pixels (maximal
    connectivity):

    >>> local_maxima(image)
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 1, 1, 0, 0, 0, 0],
           [0, 1, 1, 0, 0, 0, 0],
           [1, 0, 0, 0, 0, 0, 1]], dtype=uint8)
    >>> local_maxima(image, indices=True)
    (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6]))

    Find local maxima without comparing to diagonal pixels (connectivity 1):

    >>> local_maxima(image, connectivity=1)
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 1, 1, 0, 1, 1, 0],
           [0, 1, 1, 0, 1, 1, 0],
           [1, 0, 0, 0, 0, 0, 1]], dtype=uint8)

    and exclude maxima that border the image edge:

    >>> local_maxima(image, connectivity=1, allow_borders=False)
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 1, 1, 0, 1, 1, 0],
           [0, 1, 1, 0, 1, 1, 0],
           [0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
    R2   R3   i    R   R.   i   c         s@  s   |  ] } | d  k  Vq d S(   i   N(    (   R4   R=   (    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pys	   <genexpr>Ì  s    sV   maxima can't exist for an image with any dimension smaller 3 if borders aren't allowedt
   stacklevelt   centeri   sL   dtype of `image` is float16 which is not supported, try upcasting to float32N(   i   (   R   R@   t   sizet   nonzeroR   R   R   R<   t   minR1   RB   R   RD   R+   R   R   t   ravelt	   TypeErrorR   t   float16R   (   R   R   RC   t   indicest   allow_borderst   flagst   neighbor_offsets(    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   local_maximaN  s8    k
 c         C@  s+   t  d t |  ƒ d | d | d | d | ƒ S(   sv  Find local minima of n-dimensional array.

    The local minima are defined as connected sets of pixels with equal gray
    level (plateaus) strictly smaller than the gray levels of all pixels in the
    neighborhood.

    Parameters
    ----------
    image : ndarray
        An n-dimensional array.
    selem : ndarray, optional
        A structuring element used to determine the neighborhood of each
        evaluated pixel. It must contain only 1's and 0's, have the same number
        of dimensions as `image`. If not given, all adjacent pixels are
        considered as part of the neighborhood.
    connectivity : int, optional
        A number used to determine the neighborhood of each evaluated pixel.
        Adjacent pixels whose squared distance from the center is larger or
        equal to `connectivity` are considered neighbors. Ignored if
        `selem` is not None.
    indices : bool, optional
        If True, the output will be a tuple of one-dimensional arrays
        representing the indices of local minima in each dimension. If False,
        the output will be an array of 0's and 1's with the same shape as
        `image`.
    allow_borders : bool, optional
        If true, plateaus that touch the image border are valid minima.

    Returns
    -------
    minima : ndarray or tuple[ndarray]
        If `indices` is false, an array with the same shape as `image` is
        returned with 1's indicating the position of local minima
        (0 otherwise). If `indices` is true, a tuple of one-dimensional arrays
        containing the coordinates (indices) of all found minima.

    See Also
    --------
    skimage.morphology.local_maxima
    skimage.morphology.h_maxima
    skimage.morphology.h_minima

    Notes
    -----
    This function operates on the following ideas:

    1. Make a first pass over the image's last dimension and flag candidates
       for local minima by comparing pixels in only one direction.
       If the pixels aren't connected in the last dimension all pixels are
       flagged as candidates instead.

    For each candidate:

    2. Perform a flood-fill to find all connected pixels that have the same
       gray value and are part of the plateau.
    3. Consider the connected neighborhood of a plateau: if no bordering sample
       has a smaller gray level, mark the plateau as a definite local minimum.

    Examples
    --------
    >>> from skimage.morphology import local_minima
    >>> image = np.zeros((4, 7), dtype=int)
    >>> image[1:3, 1:3] = -1
    >>> image[3, 0] = -1
    >>> image[1:3, 4:6] = -2
    >>> image[3, 6] = -3
    >>> image
    array([[ 0,  0,  0,  0,  0,  0,  0],
           [ 0, -1, -1,  0, -2, -2,  0],
           [ 0, -1, -1,  0, -2, -2,  0],
           [-1,  0,  0,  0,  0,  0, -3]])

    Find local minima by comparing to all neighboring pixels (maximal
    connectivity):

    >>> local_minima(image)
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 1, 1, 0, 0, 0, 0],
           [0, 1, 1, 0, 0, 0, 0],
           [1, 0, 0, 0, 0, 0, 1]], dtype=uint8)
    >>> local_minima(image, indices=True)
    (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6]))

    Find local minima without comparing to diagonal pixels (connectivity 1):

    >>> local_minima(image, connectivity=1)
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 1, 1, 0, 1, 1, 0],
           [0, 1, 1, 0, 1, 1, 0],
           [1, 0, 0, 0, 0, 0, 1]], dtype=uint8)

    and exclude minima that border the image edge:

    >>> local_minima(image, connectivity=1, allow_borders=False)
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 1, 1, 0, 1, 1, 0],
           [0, 1, 1, 0, 1, 1, 0],
           [0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
    R   R   RC   RM   RN   (   RQ   R   (   R   R   RC   RM   RN   (    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   local_minimañ  s    e(    t   __doc__t
   __future__R    t   numpyR   t   scipyR   R>   t   utilR   R   R   t   _shared.utilsR   t    R   t	   watershedR   t   _extrema_cyR   R   R   R-   R&   R)   R1   R<   RD   R
   t   TrueRQ   RR   (    (    (    s9   lib/python2.7/site-packages/skimage/morphology/extrema.pyt   <module>   s&   		QQ		-	,	¢	