
    9iPQ                         S r SSKrSSKJr  SSKJrJrJr  SSK	J
r
Jr  SSKJr  S	 rS
 rSS jrSS jr SS jr SS jrg)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                 ^    [        U SS9u  p#XU-
  :  a  [        S5      eX-   nX4XU-
  :  '   U$ )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/land-doc-ocr/venv/lib/python3.13/site-packages/skimage/morphology/extrema.py_add_constant_clipr      sK    'UCI)+,N
 	
  F.75{**+M    c                 ^    [        U SS9u  p#XU-
  :  a  [        S5      eX-
  nX$XU-   :  '   U$ )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   #   sK    'UCI)+,S
 	
  F095)+,-Mr   c                    U[         R                  " U 5      :  a-  [         R                  " U R                  [         R                  S9$ [         R
                  " [        U5      [         R                  5      (       ax  [         R
                  " U R                  [         R                  5      (       aD  US-  S:w  a   [        SSS9  U R                  [        5      n OU R                  R                  U5      nUS:X  a  [        S5      e[         R
                  " U R                  [         R                  5      (       aL  S[         R                  " U R                  5      R                  -  [         R                   " U 5      -  nX-
  U-
  nO[#        X5      n[$        R&                  " X@SUS	9nX-
  nXa:  R                  [         R                  5      $ )
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   sH   J 	266%=xx28844$ 
}}T!Wbkk**r}}U[["**/U/UEa<: 	 LL'E  #AAvMNN	}}U[["++.. %++.999BFF5MI
i*,-e7,,:G /K$$RXX..r   c                    U[         R                  " U 5      :  a-  [         R                  " U R                  [         R                  S9$ [         R
                  " [        U5      [         R                  5      (       ax  [         R
                  " U R                  [         R                  5      (       aD  US-  S:w  a   [        SSS9  U R                  [        5      n OU R                  R                  U5      nUS:X  a  [        S5      e[         R
                  " U R                  [         R                  5      (       aL  S[         R                  " U R                  5      R                  -  [         R                   " U 5      -  nX-   U-   nO[#        X5      n[$        R&                  " X@SUS	9nXP-
  nXa:  R                  [         R                  5      $ )
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=      sD   D 	266%=xx28844	}}T!Wbkk**r}}U[["**/U/UEa<: 	 LL'E  #AAvMNN	}}U[["++..%++.999BFF5MI
i*,(2,,9	G /K$$RXX..r   c                    [         R                  " U SS9n U R                  S:X  a@  U(       a  [         R                  " U 5      $ [         R                  " U R
                  [        S9$ U(       a%  [         R                  " U SSU R                  5       S9n [         R                  " U R
                  [         R                  S9n[        R                  " USS	9  [        S
 U R
                   5       5      (       a  [        SSS9  Ox[        R                  " XU R                  5      n[        R                   " U R
                  USU R                  -  S9n [#        U R%                  5       UR%                  5       U5        U(       a  [-        US5      nO[        R                  " USS	9  U(       a  [         R                  " U5      $ UR/                  [        5      $ ! [&         a+    U R(                  [         R*                  :X  a  ['        S5      ee f = f)aJ  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   *   #    U  H	  oS :  v   M     g7f)rD   N ).0ss     r   	<genexpr>local_maxima.<locals>.<genexpr>  s     
&+Qq5+s   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_maximara     s   X JJuC(EzzQ::e$$88EKKt44 uaj%))+N HHU[[1E	U!,

&%++
&&& 	(	
 //	T	 >>KKD5::,=

	%++-8HI UA 	  a0zz%  zz$)  	{{bjj(: 
 	s   )G 5Hc                 ,    [        [        U SS9UUUUS9$ )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^   )ra   r   rd   s        r   local_minimare     s(    L U.!# r   )N)NNFT)__doc__numpyr&   _shared.utilsr   utilr   r   r    r	   r
   _extrema_cyr   r   r   r:   r=   ra   re   rG   r   r   <module>rl      sQ   
    - - $ &~/B^/D LPc N LPlr   