
    0-Ph)A                         d Z ddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZ d	Zd
 eD             ZdZe                    d eD                        d Zd ZddddZddddZddddddZdS )z#Miscellaneous morphology functions.    N)ndimage)cKDTree   )warn   )_remove_objects_by_distance)erosiondilationopeningclosingc                     i | ]}|d |z   	S )grey_ .0xs     W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/morphology/misc.py
<dictcomp>r      s    111a1gk111    )binary_erosionbinary_dilationbinary_openingbinary_closingblack_tophatwhite_tophatc                     i | ]}||S r   r   r   s     r   r   r      s    ,,,1,,,r   c                 H     t          j                   d fd	            }|S )a  Decorator to add a default footprint to morphology functions.

    Parameters
    ----------
    func : function
        A morphology function such as erosion, dilation, opening, closing,
        white_tophat, or black_tophat.

    Returns
    -------
    func_out : function
        The function, using a default footprint of same dimension
        as the input image with connectivity 1.

    Nc                 X    |t          j        | j        d          } | g|R d|i|S )Nr   	footprint)ndigenerate_binary_structurendim)imager   argskwargsfuncs       r   func_outz#default_footprint.<locals>.func_out.   sB    5ej!DDItE@@@@Y@@@@r   N)	functoolswraps)r&   r'   s   ` r   default_footprintr+      sE    " _TA A A A A A
 Or   c                     | j         t          k    s<t          j        | j         t          j                  st          d| j          d          d S d S )Nz4Only bool or integer image types are supported. Got .)dtypeboolnp
issubdtypeinteger	TypeError)ars    r   _check_dtype_supportedr5   7   sT    Hbh
 C CQbhQQQ
 
 	
 r   @   outc                L   t          |            ||                                 }n| |dd<   |dk    r|S |j        t          k    rRt	          j        | j        |          }t          j        | t          j	                  }t	          j
        | ||           n|}	 t          j        |                                          }n# t          $ r t          d          w xY wt          |          dk    r|j        t          k    rt          d           ||k     }||         }d||<   |S )a  Remove objects smaller than the specified size.

    Expects ar to be an array with labeled objects, and removes objects
    smaller than min_size. If `ar` is bool, the image is first labeled.
    This leads to potentially different behavior for bool and 0-and-1
    arrays.

    Parameters
    ----------
    ar : ndarray (arbitrary shape, int or bool type)
        The array containing the objects of interest. If the array type is
        int, the ints must be non-negative.
    min_size : int, optional (default: 64)
        The smallest allowable object size.
    connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1)
        The connectivity defining the neighborhood of a pixel. Used during
        labelling if `ar` is bool.
    out : ndarray
        Array of the same shape as `ar`, into which the output is
        placed. By default, a new array is created.

    Raises
    ------
    TypeError
        If the input array is of an invalid type, such as float or string.
    ValueError
        If the input array contains negative values.

    Returns
    -------
    out : ndarray, same shape and type as input `ar`
        The input array with small connected components removed.

    See Also
    --------
    skimage.morphology.remove_objects_by_distance

    Examples
    --------
    >>> from skimage import morphology
    >>> a = np.array([[0, 0, 0, 1, 0],
    ...               [1, 1, 1, 0, 0],
    ...               [1, 1, 1, 0, 1]], bool)
    >>> b = morphology.remove_small_objects(a, 6)
    >>> b
    array([[False, False, False, False, False],
           [ True,  True,  True, False, False],
           [ True,  True,  True, False, False]])
    >>> c = morphology.remove_small_objects(a, 7, connectivity=2)
    >>> c
    array([[False, False, False,  True, False],
           [ True,  True,  True, False, False],
           [ True,  True,  True, False, False]])
    >>> d = morphology.remove_small_objects(a, 6, out=a)
    >>> d is a
    True

    Nr   r.   )outputz{Negative value labels are not supported. Try relabeling the input with `scipy.ndimage.label` or `skimage.morphology.label`.r   z[Only one label was provided to `remove_small_objects`. Did you mean to use a boolean array?)r5   copyr.   r/   r    r!   r"   r0   
zeros_likeint32labelbincountravel
ValueErrorlenr   )	r4   min_sizeconnectivityr8   r   ccscomponent_sizes	too_smalltoo_small_masks	            r   remove_small_objectsrJ   ?   sD   x 2
{ggiiAAA1}}

yD1"'<HH	mBbh///	"i,,,,,
+ciikk22 
 
 
*
 
 	

 ?q  SY$%6%63	
 	
 	

  (*Is^NCJs   &C Cc                h   t          |            | j        t          k    rt          dt                     | |j        t          k    rt          d          n|                     t          d          }t          j        | |           t          ||||          }t          j        ||           |S )ap  Remove contiguous holes smaller than the specified size.

    Parameters
    ----------
    ar : ndarray (arbitrary shape, int or bool type)
        The array containing the connected components of interest.
    area_threshold : int, optional (default: 64)
        The maximum area, in pixels, of a contiguous hole that will be filled.
        Replaces `min_size`.
    connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1)
        The connectivity defining the neighborhood of a pixel.
    out : ndarray
        Array of the same shape as `ar` and bool dtype, into which the
        output is placed. By default, a new array is created.

    Raises
    ------
    TypeError
        If the input array is of an invalid type, such as float or string.
    ValueError
        If the input array contains negative values.

    Returns
    -------
    out : ndarray, same shape and type as input `ar`
        The input array with small holes within connected components removed.

    Examples
    --------
    >>> from skimage import morphology
    >>> a = np.array([[1, 1, 1, 1, 1, 0],
    ...               [1, 1, 1, 0, 1, 0],
    ...               [1, 0, 0, 1, 1, 0],
    ...               [1, 1, 1, 1, 1, 0]], bool)
    >>> b = morphology.remove_small_holes(a, 2)
    >>> b
    array([[ True,  True,  True,  True,  True, False],
           [ True,  True,  True,  True,  True, False],
           [ True, False, False,  True,  True, False],
           [ True,  True,  True,  True,  True, False]])
    >>> c = morphology.remove_small_holes(a, 2, connectivity=2)
    >>> c
    array([[ True,  True,  True,  True,  True, False],
           [ True,  True,  True, False,  True, False],
           [ True, False, False,  True,  True, False],
           [ True,  True,  True,  True,  True, False]])
    >>> d = morphology.remove_small_holes(a, 2, out=a)
    >>> d is a
    True

    Notes
    -----
    If the array type is int, it is assumed that it contains already-labeled
    objects. The labels are not kept in the output image (this function always
    outputs a bool image). It is suggested that labeling is completed after
    using this function.

    z\Any labeled images will be returned as a boolean array. Did you mean to use a boolean array?Nzout dtype must be boolTr<   r7   )
r5   r.   r/   r   UserWarningr3   astyper0   logical_notrJ   )r4   area_thresholdrE   r8   s       r   remove_small_holesrQ      s    v 2 
x43	
 	
 	
 94555  ii4i(( N23 sNLc
J
J
JCN3C    Jr   )priorityp_normspacingr8   c          	         |dk     rt          d|           t          j        | j        t          j                  st          d| j                   ||                     d          }n|| ur| |dd<   |                    d          }Lt          j                  j        |j	        fk    s
                                dk    rt          d          t          j        |          }t          j        d         k              r!|dk    rt          j        |j	        d	          }nt          j        |j	        |j	                  }t          j        ||
          t          j        ||
          k                                    |         }	||	         }
||	          }|
j        dk    r|S |
t          j        ||
                            }
|t          j        ||                            }|nt          j        |j        t          j        d          s4t          j        |                    t          j        d                    }nt          j        |          }||
d                  }|dk     rt          d|          	 |
t          j        |||
                  d          ddd                  }
nR# t.          $ rE}t          j        |          d	z   f}|j        |k    rt          d| d|j         d          | d}~ww xY wt          j        |
|j                  .t5          fdt7          |j	                  D                       t9          t          j        t          j                  j                  }tA          ||
||||| j                   |j!        |ur|"                    |j                  |dd<   |S )aU  Remove objects, in specified order, until remaining are a minimum distance apart.

    Remove labeled objects from an image until the remaining ones are spaced
    more than a given distance from one another. By default, smaller objects
    are removed first.

    Parameters
    ----------
    label_image : ndarray of integers
        An n-dimensional array containing object labels, e.g. as returned by
        :func:`~.label`. A value of zero is considered background, all other
        object IDs must be positive integers.
    min_distance : int or float
        Remove objects whose distance to other objects is not greater than this
        positive value. Objects with a lower `priority` are removed first.
    priority : ndarray, optional
        Defines the priority with which objects are removed. Expects a
        1-dimensional array of length
        :func:`np.amax(label_image) + 1 <numpy.amax>` that contains the priority
        for each object's label at the respective index. Objects with a lower value
        are removed first until all remaining objects fulfill the distance
        requirement. If not given, priority is given to objects with a higher
        number of samples and their label value second.
    p_norm : int or float, optional
        The Minkowski distance of order p, used to calculate the distance
        between objects. The default ``2`` corresponds to the Euclidean
        distance, ``1`` to the "Manhattan" distance, and ``np.inf`` to the
        Chebyshev distance.
    spacing : sequence of float, optional
        The pixel spacing along each axis of `label_image`. If not specified,
        a grid spacing of unity (1) is implied.
    out : ndarray, optional
        Array of the same shape and dtype as `image`, into which the output is
        placed. By default, a new array is created.

    Returns
    -------
    out : ndarray
        Array of the same shape as `label_image`, for which objects that violate
        the `min_distance` condition were removed.

    See Also
    --------
    skimage.morphology.remove_small_objects
        Remove objects smaller than the specified size.

    Notes
    -----
    The basic steps of this algorithm work as follows:

    1. Find the indices for of all given objects and separate them depending on
       if they point to an object's border or not.
    2. Sort indices by their label value, ensuring that indices which point to
       the same object are next to each other. This optimization allows finding
       all parts of an object, simply by stepping to the neighboring indices.
    3. Sort boundary indices by `priority`. Use a stable-sort to preserve the
       ordering from the previous sorting step. If `priority` is not given,
       use :func:`numpy.bincount` as a fallback.
    4. Construct a :class:`scipy.spatial.cKDTree` from the boundary indices.
    5. Iterate across boundary indices in priority-sorted order, and query the
       kd-tree for objects that are too close. Remove ones that are and don't
       take them into account when evaluating other objects later on.

    The performance of this algorithm depends on the number of samples in
    `label_image` that belong to an object's border.

    Examples
    --------
    >>> import skimage as ski
    >>> ski.morphology.remove_objects_by_distance(np.array([2, 0, 1, 1]), 2)
    array([0, 0, 1, 1])
    >>> ski.morphology.remove_objects_by_distance(
    ...     np.array([2, 0, 1, 1]), 2, priority=np.array([0, 1, 9])
    ... )
    array([2, 0, 0, 0])
    >>> label_image = np.array(
    ...     [[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
    ...      [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9],
    ...      [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0],
    ...      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    ...      [0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0],
    ...      [2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    ...      [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    ...      [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]]
    ... )
    >>> ski.morphology.remove_objects_by_distance(
    ...     label_image, min_distance=3
    ... )
    array([[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
           [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9],
           [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]])
    r   zmin_distance must be >= 0, was z,`label_image` must be of integer dtype, got NC)orderzV`spacing` must contain exactly one positive factor for each dimension of `label_image`r   r   )r   safe)castingFrL   zfound object with negative ID stable)kindzBshape of `priority` must be (np.amax(label_image) + 1,), expected z, got z insteadc              3   :   K   | ]}|         |         z  V  d S r(   r   )r   dimrT   unraveled_indicess     r   	<genexpr>z-remove_objects_by_distance.<locals>.<genexpr>  sC       "
 "
69c"WS\1"
 "
 "
 "
 "
 "
r   r:   )data)r8   border_indicesinner_indiceskdtreemin_distancerS   shape)#rB   r0   r1   r.   r2   r<   rA   arrayrf   r"   minflatnonzeroallr    r!   maximum_filterminimum_filtersizeargsortcan_castintpr@   rN   
IndexErroramaxunravel_indextupleranger   asarrayfloat64Tr   basereshape)label_imagere   rR   rS   rT   r8   out_raveledindicesr   borderrb   rc   smallest_iderrorexpected_shaperd   r_   s       `           @r   remove_objects_by_distancer      s3   T aI<IIJJJ=*BJ77 
N;;LNN
 
 	
 {S))	K		AAA))#)&&K(7##=SXK''7;;==A+=+=6  
 n[))G
 	26'!*"788fkk 1#(A>>		1#(CHEE	3)444cY777	8egggF V_NVG$Ma

 $BJ{>/J$K$KLN!"*[-G"H"HIM{39bgv>>> 	0{;#5#5bgE#5#J#JKKHH{;//H nQ/0KQI+IIJJJ (JxN ;<8LLLTTrTR
  	 	 	'+..24>^++K*K K2:.K K K  
 	 (CC! "
 "
 "
 "
 "
=B38__"
 "
 "
 
 
 "*%6bjIIIKLLLF%#!    s""$$SY//AAAJs   1J? ?
L	A L		L)r6   r   )__doc__numpyr0   r)   scipyr   r    scipy.spatialr   _shared.utilsr   _misc_cyr   funcsskimage2ndimageupdater+   r5   rJ   rQ   r   r   r   r   <module>r      sU   ) )                     ! ! ! ! ! !             1 1 1 1 1 1
 	6115111	   ,,e,,, - - -  4
 
 
` ` ` ` ` `FST S S S S St N N N N N N Nr   