
    0-PhPQ                     ~    d Z ddlZddlmZ ddlmZmZmZ ddl	m
Z
mZ ddlmZ d	 Zd
 ZddZddZ	 ddZ	 ddZdS )a  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.
    N   )warn)dtype_limitsinvertcrop   )grayreconstruct_util)_local_maximac                     t          | d          \  }}|||z
  k    rt          d          | |z   }||| ||z
  k    <   |S )zDAdd constant to the image while handling overflow issues gracefully.Fclip_negativez=The added constant is not compatiblewith the image data type.r   
ValueErrorimageconst_value	min_dtype	max_dtyperesults        Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/morphology/extrema.py_add_constant_clipr      sc    'UCCCIyi)+,,N
 
 	
 [ F.7F59{**+M    c                     t          | d          \  }}|||z
  k    rt          d          | |z
  }||| ||z   k     <   |S )z=Subtract constant from image while handling underflow issues.Fr   zBThe subtracted constant is not compatiblewith the image data type.r   r   s        r   _subtract_constant_clipr   #   sc    'UCCCIyi)+,,S
 
 	
 [ F09F5K)+,-Mr   c                 J   |t          j        |           k    r%t          j        | j        t           j                  S t          j        t          |          t           j                  rst          j        | j        t           j	                  rO|dz  dk    r,t          dd           |                     t                    } n| j                            |          }|dk    rt          d          t          j        | j        t           j                  r?dt          j        | j                  j        z  t          j        |           z  }| |z
  |z
  }nt#          | |          }t%          j        || d|	          }| |z
  }||k                        t           j                  S )
a
	  Determine all maxima of the image with height >= h.

    The local maxima are defined as connected sets of pixels with equal
    gray level strictly greater than the gray 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 an equal or higher local 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 to an equal or higher local maximum for which the minimal
    value is greater.

    The global maxima of the image are also found by this function.

    Parameters
    ----------
    image : ndarray
        The input image for which the maxima are to be calculated.
    h : unsigned integer
        The minimal height of all extracted maxima.
    footprint : 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 local maxima of height >= h and the global maxima.
        The resulting image is a binary image, where pixels belonging to
        the determined maxima take value 1, the others take value 0.

    See Also
    --------
    skimage.morphology.h_minima
    skimage.morphology.local_maxima
    skimage.morphology.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

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

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

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

    The resulting image will contain 3 local maxima.
    dtyper   r   |possible precision loss converting image to floating point. To silence this warning, ensure image and h have same data type.r   
stacklevelz/h = 0 is ambiguous, use local_maxima() instead?dilationmethod	footprint)npptpzerosshapeuint8
issubdtypetypefloatingr   integerr   astypefloatr   finfo
resolutionabsr   r	   reconstructionr   hr%   r2   shifted_imgrec_imgresidue_imgs          r   h_maximar:   1   s{   J 	26%==x284444$ 
}T!WWbk** 
$r}U["*/U/U 
$Ea<<: 	    LL''EE  ##AAvvMNNN	}U["+.. 8 %+..99BF5MMI
ai*,-eQ77,U:  G '/K1$$RX...r   c                 J   |t          j        |           k    r%t          j        | j        t           j                  S t          j        t          |          t           j                  rst          j        | j        t           j	                  rO|dz  dk    r,t          dd           |                     t                    } n| j                            |          }|dk    rt          d          t          j        | j        t           j                  r?dt          j        | j                  j        z  t          j        |           z  }| |z   |z   }nt#          | |          }t%          j        || d|	          }|| z
  }||k                        t           j                  S )
a	  Determine all minima of the image with depth >= h.

    The local minima are defined as connected sets of pixels with equal
    gray level strictly smaller than the gray 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 an equal or lower local 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 to an equal or lower local minimum for which the maximal
    value is smaller.

    The global minima of the image are also found by this function.

    Parameters
    ----------
    image : ndarray
        The input image for which the minima are to be calculated.
    h : unsigned integer
        The minimal depth of all extracted minima.
    footprint : 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 local minima of depth >= h and the global minima.
        The resulting image is a binary image, where pixels belonging to
        the determined minima take value 1, the others take value 0.

    See Also
    --------
    skimage.morphology.h_maxima
    skimage.morphology.local_maxima
    skimage.morphology.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

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

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

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

    The resulting image will contain 3 local minima.
    r   r   r   r   r   r    z/h = 0 is ambiguous, use local_minima() instead?erosionr#   )r&   r'   r(   r)   r*   r+   r,   r-   r   r.   r   r/   r0   r   r1   r2   r3   r   r	   r4   r5   s          r   h_minimar=      sw   D 	26%==x284444	}T!WWbk** 
$r}U["*/U/U 
$Ea<<: 	    LL''EE  ##AAvvMNNN	}U["+.. 3%+..99BF5MMI
ai*,(22,U9	  G E/K1$$RX...r   FTc                    t          j        | d          } | j        dk    r6|rt          j        |           S t          j        | j        t                    S |r*t          j        | dd|                                           } t          j        | j        t           j	                  }t          j        |d	           t          d
 | j        D                       rt          dd           nt          j        ||| j                  }t          j        | j        |d| j        z            }	 t#          |                                 |                                |           n3# t&          $ r& | j        t           j        k    rt'          d           w xY w|rt-          |d          }nt          j        |d	           |rt          j        |          S |                    t                    S )a  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.
    footprint : ndarray, optional
        The footprint (structuring element) used to determine the neighborhood
        of each evaluated pixel (``True`` denotes a connected pixel). It must
        be a boolean array and have the same number of dimensions as `image`.
        If neither `footprint` nor `connectivity` are 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 less than or
        equal to `connectivity` are considered neighbors. Ignored if
        `footprint` 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 a boolean array 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, a boolean array with the same shape as `image`
        is returned with ``True`` indicating the position of local maxima
        (``False`` 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([[False, False, False, False, False, False, False],
           [False,  True,  True, False, False, False, False],
           [False,  True,  True, False, False, False, False],
           [ True, False, False, False, False, False,  True]])
    >>> 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([[False, False, False, False, False, False, False],
           [False,  True,  True, False,  True,  True, False],
           [False,  True,  True, False,  True,  True, False],
           [ True, False, False, False, False, False,  True]])

    and exclude maxima that border the image edge:

    >>> local_maxima(image, connectivity=1, allow_borders=False)
    array([[False, False, False, False, False, False, False],
           [False,  True,  True, False,  True,  True, False],
           [False,  True,  True, False,  True,  True, False],
           [False, False, False, False, False, False, False]])
    C)orderr   r   r   constant)modeconstant_values   )valuec              3   "   K   | ]
}|d k     V  dS )rD   N ).0ss     r   	<genexpr>zlocal_maxima.<locals>.<genexpr>  s&      
&
&Q1q5
&
&
&
&
&
&r   zVmaxima can't exist for an image with any dimension smaller 3 if borders aren't allowedr    )r   )centerzLdtype of `image` is float16 which is not supported, try upcasting to float32)r&   asarraysizenonzeror(   r)   boolpadminr*   r
   _set_border_valuesanyr   _resolve_neighborhoodndim_offsets_to_raveled_neighborsr   ravel	TypeErrorr   float16r   view)r   r%   connectivityindicesallow_bordersflagsneighbor_offsetss          r   local_maximar`     s   X JuC(((EzQ 	5:e$$$8EKt4444 O uaj%))++NNN HU[111E	U!,,,,

&
&%+
&
&
&&&  	(	
 	
 	
 	
 	
 /	<TT	 >KD5:,=
 
 

	%++--8HIIII 	 	 	{bj((:  
 	  1UA 	 a0000  z%   zz$s   /5E% %0Fc                 H    t          t          | d          ||||          S )a  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.
    footprint : ndarray, optional
        The footprint (structuring element) used to determine the neighborhood
        of each evaluated pixel (``True`` denotes a connected pixel). It must
        be a boolean array and have the same number of dimensions as `image`.
        If neither `footprint` nor `connectivity` are 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 less than or
        equal to `connectivity` are considered neighbors. Ignored if
        `footprint` 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 a boolean array 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, a boolean array with the same shape as `image`
        is returned with ``True`` indicating the position of local minima
        (``False`` 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([[False, False, False, False, False, False, False],
           [False,  True,  True, False, False, False, False],
           [False,  True,  True, False, False, False, False],
           [ True, False, False, False, False, False,  True]])
    >>> 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([[False, False, False, False, False, False, False],
           [False,  True,  True, False,  True,  True, False],
           [False,  True,  True, False,  True,  True, False],
           [ True, False, False, False, False, False,  True]])

    and exclude minima that border the image edge:

    >>> local_minima(image, connectivity=1, allow_borders=False)
    array([[False, False, False, False, False, False, False],
           [False,  True,  True, False,  True,  True, False],
           [False,  True,  True, False,  True,  True, False],
           [False, False, False, False, False, False, False]])
    T)signed_floatr   r%   r[   r\   r]   )r`   r   rc   s        r   local_minimard     s8    L U...!#   r   )N)NNFT)__doc__numpyr&   _shared.utilsr   utilr   r   r    r	   r
   _extrema_cyr   r   r   r:   r=   r`   rd   rG   r   r   <module>rk      s  
 
                 - - - - - - - - - - $ $ $ $ $ $ $ $ & & & & & &    ~/ ~/ ~/ ~/B^/ ^/ ^/ ^/D LPc  c  c  c N LPl l l l l lr   