o
    X۷i                     @  s  d dl mZ d dlZd dlZd dl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 dlmZ ejdd	d
d Zdd Zd;ddZdd Z	d<ddddZdd Z		d=ddddZ		d=ddddZ	 	d>ddddZ	 	d>dddd Z		d?ddd!d"Z		 d@ddd#d$ZdAd%d&ZdBddd'd(Z		 dCddd+d,Z		 dCddd-d.Z		 dCddd/d0Z		 dCddd1d2Z					)	*	 dCddd3d4Z 					)	*	 dCddd5d6Z!					)	*	 dCddd7d8Z"					)	*	 dCddd9d:Z#dS )D    )annotationsN)_core)_filters_core)_measurements)_util)_filtersT)for_each_devicec                 C  s   |rt | }d}d}	nt |}d}d}	|r"dt | d|	 d}
ndt | d|	 d}
|
d| d }
d	| d
|	 d| d|	 d|	 d}d}|	rO|d7 }| }dt|  }tj||
|d|| ||dd|d|ddS )Nr      z
            bool mv = (bool)mask[i];
            bool _in = (bool)x[i];
            if (!mv) {
                y = cast<Y>(_in);
                return;
            } else if (z && _in == zK) {
                y = cast<Y>(_in);
                return;
            }z4
            bool _in = (bool)x[i];
            if (z
            y = cast<Y>(z);z)
        if ({cond}) {{
            if (!z!) {{
                y = cast<Y>(z]);
                return;
            }}
        }} else {{
            bool nn = {value} ? z : z6;
            if (!nn) {{
                y = cast<Y>(z4);
                return;
            }}
        }}binary_erosion_invert)constant YFT)ctypehas_weightshas_structurehas_maskbinary_morphology)intlenr   _generate_nd_kernel)w_shapeint_typeoffsetscenter_is_trueborder_valueinvertmaskedall_weights_nonzerotrue_val	false_valprefoundnamer   modes r%   U/home/ubuntu/vllm_env/lib/python3.10/site-packages/cupyx/scipy/ndimage/_morphology.py_get_binary_erosion_kernel   s\   


	r'   c                 C  s&   t dd t| j|D }t| | S )Nc                 S  s   g | ]
\}}||d   qS    r%   ).0ssoor%   r%   r&   
<listcomp>U       z#_center_is_true.<locals>.<listcomp>)tuplezipshapebool)	structureorigincoorr%   r%   r&   _center_is_trueT   s   r6   c                   s    dk r  S  d fddjD }fddtt|D tfddtt|D }t|t}dk||< t|d	}|d
u rM|S t	
|jdt} fdd|D }||fS )a  Iterate a structure by dilating it with itself.

    Args:
        structure(array_like): Structuring element (an array of bools,
            for example), to be dilated with itself.
        iterations(int): The number of dilations performed on the structure
            with itself.
        origin(int or tuple of int, optional): If origin is None, only the
            iterated structure is returned. If not, a tuple of the iterated
            structure and the modified origin is returned.

    Returns:
        cupy.ndarray: A new structuring element obtained by dilating
        ``structure`` (``iterations`` - 1) times with itself.

    .. seealso:: :func:`scipy.ndimage.iterate_structure`
    r)   r	   c                   s   g | ]
}| |d    qS )r	   r%   r*   ii)nir%   r&   r-   n   r.   z%iterate_structure.<locals>.<listcomp>c                   s   g | ]} j | d   qS r(   )r1   r7   )r9   r3   r%   r&   r-   o   s    c                 3  s.    | ]}t  |  | j|  d V  qd S N)slicer1   r7   )posr3   r%   r&   	<genexpr>p   s
    
z$iterate_structure.<locals>.<genexpr>r   
iterationsNr4   c                   s   g | ]} | qS r%   r%   r*   or>   r%   r&   r-   {   s    )copyr1   ranger   r/   cupyzerosr2   binary_dilationr   _fix_sequence_argndimr   )r3   r?   r4   r1   slcoutr%   )r?   r9   r<   r3   r&   iterate_structureY   s    
rK   c                 C  s\   |dk rd}| dk rt jdtdS ttdg|  d }tj|d}||k}t |S )a  Generate a binary structure for binary morphological operations.

    Args:
        rank(int): Number of dimensions of the array to which the structuring
            element will be applied, as returned by ``np.ndim``.
        connectivity(int): ``connectivity`` determines which elements of the
            output array belong to the structure, i.e., are considered as
            neighbors of the central element. Elements up to a squared distance
            of ``connectivity`` from the center are considered neighbors.
            ``connectivity`` may range from 1 (no diagonal elements are
            neighbors) to ``rank`` (all elements are neighbors).

    Returns:
        cupy.ndarray: Structuring element which may be used for binary
        morphological operations, with ``rank`` dimensions and all
        dimensions equal to 3.

    .. seealso:: :func:`scipy.ndimage.generate_binary_structure`
    r	   Tdtype   r   )rD   asarrayr2   numpyfabsindicesaddreduce)rankconnectivityoutputr%   r%   r&   generate_binary_structure   s   
rX   axesc	             	   C  s4  zt |}W n ty   tdw | jjdkrtd| j}
t|	|
}	t|	}|d u r>t	|d}| jdk}d}|j
}n7t|trP|}t|dkrOtdn%|jtdd	}|j
}|j|krctd
|jjslt|}|jdk rutd||
k rtj|
|	|dd}|j
}|d ur|j
| j
krtd|jjst|}d}nd}t||dt}||
k rt|
|	|}t|tjr|jjdkrtdnt}t|| }t|| d}|r|}t|j| }t|dkrt|tst|rtj| td|d< |S tj| td |d< |S t|}t| }t ||}t|tr%t!"|}d}d}ntt#|}||jk}|r7d}nt$||}t%||||||||}|rV|rR| |f}n| f}n|r_| ||f}n| |f}|dkrr|g ||R  }n|r||s|t&dt|| drt'dtj(| |jd}|}|dkr|d@ s||}}|g ||R  }| |k)  }d}||k s|dk r|r||}}|r|r||f}n|f}n|r|||f}n||f}|g ||R  }||k)  }|d7 }|s|d@ sn||k s|dk r|s|}|rt*+|| |}|S )Nz)iterations parameter should be an integerczComplex type not supportedr	   Tr   zstructure must not be emptyF)rM   rB   z1structure and input must have same dimensionalityr3   )footprint_namez$mask and input must have equal sizesr4   !Complex output type not supportedMAY_SHARE_BOUNDSrL   .z/only brute_force iteration has been implementedz*output and input may not overlap in memory),operatorindex	TypeErrorrM   kindrH   r   _check_axesr   rX   r1   
isinstancer/   RuntimeErrorastyper2   flagsc_contiguousrD   ascontiguousarraysize_expand_footprintrG   r   _expand_originndarray_get_outputshares_memoryfloatrO   _get_inttyper   _origins_to_offsetsmathprodcount_nonzeror6   r'   NotImplementedError
ValueError
empty_likeallr   elementwise_copy)inputr3   r?   maskrW   r   r4   r   brute_forcerZ   rH   num_axesr   r   structure_shaper   temp_neededtempr   r   nnzerode_kernelin_argstmp_intmp_outchangedr8   r%   r%   r&   _binary_erosion   s   
















r   c                 C  sn   | d u rt |d} | | jdfS t| tr| f| } n	t| tr#t| } t| tr-d}| }nd}| j}| ||fS )Nr	   TF)rX   r1   rd   r   listr/   )r3   rH   symmetric_structurer   r%   r%   r&   _prep_structure.  s   




r   r	   Fc          
      C  s>   t || j}t|t|\}}	}	t| ||||||d||d
S )a	  Multidimensional binary erosion with a given structuring element.

    Binary erosion is a mathematical morphology operation used for image
    processing.

    Args:
        input(cupy.ndarray): The input binary array_like to be eroded.
            Non-zero (True) elements form the subset to be eroded.
        structure(cupy.ndarray or tuple or int, optional): The structuring
            element used for the erosion. Non-zero elements are considered
            true. If no structuring element is provided an element is
            generated with a square connectivity equal to one. If a tuple of
            integers is provided, a structuring element of the specified shape
            is used (all elements true). If an integer is provided, the
            structuring element will have the same size along all axes.
            (Default value = None).
        iterations(int, optional): The erosion is repeated ``iterations`` times
            (one, by default). If iterations is less than 1, the erosion is
            repeated until the result does not change anymore. Only an integer
            of iterations is accepted.
        mask(cupy.ndarray or None, optional): If a mask is given, only those
            elements with a True value at the corresponding mask element are
            modified at each iteration. (Default value = None)
        output(cupy.ndarray, optional): Array of the same shape as input, into
            which the output is placed. By default, a new array is created.
        border_value(int (cast to 0 or 1), optional): Value at the
            border in the output array. (Default value = 0)
        origin(int or tuple of ints, optional): Placement of the filter, by
            default 0.
        brute_force(boolean, optional): Memory condition: if False, only the
            pixels whose value was changed in the last iteration are tracked as
            candidates to be updated (eroded) in the current iteration; if
            True all pixels are considered as candidates for erosion,
            regardless of what happened in the previous iteration.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The result of binary erosion.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_erosion`
    r   rY   )r   rc   rH   r   r   r   )
r{   r3   r?   r|   rW   r   r4   r}   rZ   _r%   r%   r&   r
   @  s
   1
r
   c                C  s   t || j}t|t|\}}	}
t |t|dt}|
s+|ttdddg|j  }t	t|D ]}||  ||< |	| d@ sH||  d8  < q1t
| ||||||d||d
S )a	  Multidimensional binary dilation with the given structuring element.

    Args:
        input(cupy.ndarray): The input binary array_like to be dilated.
            Non-zero (True) elements form the subset to be dilated.
        structure(cupy.ndarray or tuple or int, optional): The structuring
            element used for the dilation. Non-zero elements are considered
            true. If no structuring element is provided an element is
            generated with a square connectivity equal to one. If a tuple of
            integers is provided, a structuring element of the specified shape
            is used (all elements true). If an integer is provided, the
            structuring element will have the same size along all axes.
            (Default value = None).
        iterations(int, optional): The dilation is repeated ``iterations``
            times (one, by default). If iterations is less than 1, the dilation
            is repeated until the result does not change anymore. Only an
            integer of iterations is accepted.
        mask(cupy.ndarray or None, optional): If a mask is given, only those
            elements with a True value at the corresponding mask element are
            modified at each iteration. (Default value = None)
        output(cupy.ndarray, optional): Array of the same shape as input, into
            which the output is placed. By default, a new array is created.
        border_value(int (cast to 0 or 1), optional): Value at the
            border in the output array. (Default value = 0)
        origin(int or tuple of ints, optional): Placement of the filter, by
            default 0.
        brute_force(boolean, optional): Memory condition: if False, only the
            pixels whose value was changed in the last iteration are tracked as
            candidates to be updated (dilated) in the current iteration; if
            True all pixels are considered as candidates for dilation,
            regardless of what happened in the previous iteration.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The result of binary dilation.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_dilation`
    r4   Nr	   rY   )r   rc   rH   r   r   rG   r   r/   r;   rC   r   )r{   r3   r?   r|   rW   r   r4   r}   rZ   r   	symmetricr8   r%   r%   r&   rF   w  s   /

rF   c                C  V   t || j}t|t|\}}	}	t| |||d||||d	}
t|
||||||||d	S )a
  
    Multidimensional binary opening with the given structuring element.

    The *opening* of an input image by a structuring element is the
    *dilation* of the *erosion* of the image by the structuring element.

    Args:
        input(cupy.ndarray): The input binary array to be opened.
            Non-zero (True) elements form the subset to be opened.
        structure(cupy.ndarray or tuple or int, optional): The structuring
            element used for the opening. Non-zero elements are considered
            true. If no structuring element is provided an element is
            generated with a square connectivity equal to one. If a tuple of
            integers is provided, a structuring element of the specified shape
            is used (all elements true). If an integer is provided, the
            structuring element will have the same size along all axes.
            (Default value = None).
        iterations(int, optional): The opening is repeated ``iterations`` times
            (one, by default). If iterations is less than 1, the opening is
            repeated until the result does not change anymore. Only an integer
            of iterations is accepted.
        output(cupy.ndarray, optional): Array of the same shape as input, into
            which the output is placed. By default, a new array is created.
        origin(int or tuple of ints, optional): Placement of the filter, by
            default 0.
        mask(cupy.ndarray or None, optional): If a mask is given, only those
            elements with a True value at the corresponding mask element are
            modified at each iteration. (Default value = None)
        border_value(int (cast to 0 or 1), optional): Value at the
            border in the output array. (Default value = 0)
        brute_force(boolean, optional): Memory condition: if False, only the
            pixels whose value was changed in the last iteration are tracked as
            candidates to be updated (dilated) in the current iteration; if
            True all pixels are considered as candidates for opening,
            regardless of what happened in the previous iteration.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The result of binary opening.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_opening`
    NrY   )r   rc   rH   r   r   r
   rF   r{   r3   r?   rW   r4   r|   r   r}   rZ   r   tmpr%   r%   r&   binary_opening     2r   c                C  r   )a
  
    Multidimensional binary closing with the given structuring element.

    The *closing* of an input image by a structuring element is the
    *erosion* of the *dilation* of the image by the structuring element.

    Args:
        input(cupy.ndarray): The input binary array to be closed.
            Non-zero (True) elements form the subset to be closed.
        structure(cupy.ndarray or tuple or int, optional): The structuring
            element used for the closing. Non-zero elements are considered
            true. If no structuring element is provided an element is
            generated with a square connectivity equal to one. If a tuple of
            integers is provided, a structuring element of the specified shape
            is used (all elements true). If an integer is provided, the
            structuring element will have the same size along all axes.
            (Default value = None).
        iterations(int, optional): The closing is repeated ``iterations`` times
            (one, by default). If iterations is less than 1, the closing is
            repeated until the result does not change anymore. Only an integer
            of iterations is accepted.
        output(cupy.ndarray, optional): Array of the same shape as input, into
            which the output is placed. By default, a new array is created.
        origin(int or tuple of ints, optional): Placement of the filter, by
            default 0.
        mask(cupy.ndarray or None, optional): If a mask is given, only those
            elements with a True value at the corresponding mask element are
            modified at each iteration. (Default value = None)
        border_value(int (cast to 0 or 1), optional): Value at the
            border in the output array. (Default value = 0)
        brute_force(boolean, optional): Memory condition: if False, only the
            pixels whose value was changed in the last iteration are tracked as
            candidates to be updated (dilated) in the current iteration; if
            True all pixels are considered as candidates for closing,
            regardless of what happened in the previous iteration.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The result of binary closing.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_closing`
    NrY   )r   rc   rH   r   r   rF   r
   r   r%   r%   r&   binary_closing  r   r   c                C  s   t || j}t|}|du rt|d}|du rt|}t ||dt}|du r,|}nt ||dt}t	| |dddd|dd|d
}t
|tj}	t	| |dd|d|dd|d
}
|	rgt|| t||| dS t|
|
 t||
S )aX  
    Multidimensional binary hit-or-miss transform.

    The hit-or-miss transform finds the locations of a given pattern
    inside the input image.

    Args:
        input (cupy.ndarray): Binary image where a pattern is to be detected.
        structure1 (cupy.ndarray, optional): Part of the structuring element to
            be fitted to the foreground (non-zero elements) of ``input``. If no
            value is provided, a structure of square connectivity 1 is chosen.
        structure2 (cupy.ndarray, optional): Second part of the structuring
            element that has to miss completely the foreground. If no value is
            provided, the complementary of ``structure1`` is taken.
        output (cupy.ndarray, dtype or None, optional): Array of the same shape
            as input, into which the output is placed. By default, a new array
            is created.
        origin1 (int or tuple of ints, optional): Placement of the first part
            of the structuring element ``structure1``, by default 0 for a
            centered structure.
        origin2 (int or tuple of ints or None, optional): Placement of the
            second part of the structuring element ``structure2``, by default 0
            for a centered structure. If a value is provided for ``origin1``
            and not for ``origin2``, then ``origin2`` is set to ``origin1``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: Hit-or-miss transform of ``input`` with the given
        structuring element (``structure1``, ``structure2``).

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_hit_or_miss`
    Nr	   origin1origin2r   FrY   )r   rc   rH   r   rX   rD   logical_notrG   r   r   rd   rm   logical_and)r{   
structure1
structure2rW   r   r   rZ   r~   tmp1inplaceresultr%   r%   r&   binary_hit_or_miss)  s,   (

r   c                C  s   t | |d||||d|d	S )a  
    Multidimensional binary propagation with the given structuring element.

    Args:
        input (cupy.ndarray): Binary image to be propagated inside ``mask``.
        structure (cupy.ndarray, optional): Structuring element used in the
            successive dilations. The output may depend on the structuring
            element, especially if ``mask`` has several connex components. If
            no structuring element is provided, an element is generated with a
            squared connectivity equal to one.
        mask (cupy.ndarray, optional): Binary mask defining the region into
            which ``input`` is allowed to propagate.
        output (cupy.ndarray, optional): Array of the same shape as input, into
            which the output is placed. By default, a new array is created.
        border_value (int, optional): Value at the border in the output array.
            The value is cast to 0 or 1.
        origin (int or tuple of ints, optional): Placement of the filter.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray : Binary propagation of ``input`` inside ``mask``.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_propagation`
    r   Tr}   rZ   )rF   )r{   r3   r|   rW   r   r4   rZ   r%   r%   r&   binary_propagationj  s    r   c                 C  s   | j tjkr| t} n
| j tkr| t} | j}tj| dddd}| }tj	||d\}}d}d|||k< t
||}	tddf| }
|	|
 }	|du rSt|	}|S t|tjrd|j jdkrctd	nt}t|| }|	|dd< |S )
a  Non-iterative method for hole filling.

    This algorithm is based on inverting the input and then using `label` to
    label the holes distinctly from the background. This information is then
    used to create a holes mask which can be applied to fill the holes in the
    original input.

    Initial benchmarks indicate this is a faster approach than calling
    binary_dilation iteratively:

    https://github.com/cupy/cupy/issues/8867#issuecomment-2659471046
    r	   r   r   )modeconstant_values)r3   r   Nr[   r]   )rM   rD   uint8viewr2   rf   rH   padr   label
logical_orr;   ri   rd   rm   rb   ra   r   rn   )r{   r3   rW   rH   binary_maskinverse_binary_maskinverse_labelsr   background_indexr   remove_paddingr%   r%   r&    _binary_fill_holes_non_iterative  s4   




r   c          	      C  s   t || j}|tt| jk}t|tr|ft| }tdd |D r.|r.t	| ||dS |r5t
d t| }t|jt}t|tj}|r^t||d||d|d|d	 t|| d	S t||d|d	d|d|d	}t|| |S )
aU  Fill the holes in binary objects.

    Args:
        input (cupy.ndarray): N-D binary array with holes to be filled.
        structure (cupy.ndarray, optional):  For CuPy, it is recommended to
            leave this None so that a faster non-iterative algorithm will be
            used. This default is equivalent in behavior to the default
            structure use by SciPy. If `structure` array is provided, the
            relatively slow iterative algorithm from SciPy will be used.
            In that case, a larger-size structure can make the iterative
            computations faster, but may miss holes separated from the
            background by thin regions. The default element (with a square
            connectivity equal to one) yields the intuitive result where all
            holes in the input have been filled.
        output (cupy.ndarray, dtype or None, optional): Array of the same shape
            as input, into which the output is placed. By default, a new array
            is created.
        origin (int, tuple of ints, optional): Position of the structuring
            element. Note that if this is changed from its default value of
            0, it will force a slower iterative algorithm to be used.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: Transformation of the initial image ``input`` where holes
        have been filled.

    .. warning::

        This function may synchronize the device.

    .. warning::

        It is recommended to keep the default setting of output=None and
        origin==0 so that a faster, non-iterative algorithm can be used.

    .. seealso:: :func:`scipy.ndimage.binary_fill_holes`
    c                 s  s    | ]}|d kV  qdS )r   Nr%   r@   r%   r%   r&   r=     s    z$binary_fill_holes.<locals>.<genexpr>)r3   rW   zdIt is recommended to keep the default origin=0 so that a faster non-iterative algorithm can be used.r   r	   Tr   N)r   rc   rH   r/   rC   rd   r   r   ry   r   warningswarnrD   r   rE   r1   r2   rm   rF   )	r{   r3   rW   r4   rZ   filter_all_axesr|   r   r   r%   r%   r&   binary_fill_holes  s2   )

r   reflect        c          	      C  s>   |du r|du r|du rt dtj| |||||||d|d
S )a  Calculates a greyscale erosion.

    Args:
        input (cupy.ndarray): The input array.
        size (tuple of ints): Shape of a flat and full structuring element used
            for the greyscale erosion. Optional if ``footprint`` or
            ``structure`` is provided.
        footprint (array of ints): Positions of non-infinite elements of a flat
            structuring element used for greyscale erosion. Non-zero values
            give the set of neighbors of the center over which minimum is
            chosen.
        structure (array of ints): Structuring element used for the greyscale
            erosion. ``structure`` may be a non-flat structuring element.
        output (cupy.ndarray, dtype or None): The array in which to place the
            output.
        mode (str): The array borders are handled according to the given mode
            (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
            ``'wrap'``). Default is ``'reflect'``.
        cval (scalar): Value to fill past edges of input if mode is
            ``constant``. Default is ``0.0``.
        origin (scalar or tuple of scalar): The origin parameter controls the
            placement of the filter, relative to the center of the current
            element of the input. Default of 0 is equivalent to
            ``(0,)*input.ndim``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The result of greyscale erosion.

    .. seealso:: :func:`scipy.ndimage.grey_erosion`
    N.size, footprint or structure must be specifiedminrY   )rw   r   _min_or_max_filter)	r{   rj   	footprintr3   rW   r   cvalr4   rZ   r%   r%   r&   grey_erosion
  s   $
r   c                C  s8  |du r|du r|du rt d|dur't|}|ttdddg|j  }|dur>t|}|ttdddg|j  }t|| j}t|t	|dt
}tt	|D ]7}	||	  ||	< |durh|j|	 }
n|durr|j|	 }
nt|rz|}
n||	 }
|
d dkr||	  d8  < qUtj| |||||||d|d	
S )
a  Calculates a greyscale dilation.

    Args:
        input (cupy.ndarray): The input array.
        size (tuple of ints): Shape of a flat and full structuring element used
            for the greyscale dilation. Optional if ``footprint`` or
            ``structure`` is provided.
        footprint (array of ints): Positions of non-infinite elements of a flat
            structuring element used for greyscale dilation. Non-zero values
            give the set of neighbors of the center over which maximum is
            chosen.
        structure (array of ints): Structuring element used for the greyscale
            dilation. ``structure`` may be a non-flat structuring element.
        output (cupy.ndarray, dtype or None): The array in which to place the
            output.
        mode (str): The array borders are handled according to the given mode
            (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
            ``'wrap'``). Default is ``'reflect'``.
        cval (scalar): Value to fill past edges of input if mode is
            ``constant``. Default is ``0.0``.
        origin (scalar or tuple of scalar): The origin parameter controls the
            placement of the filter, relative to the center of the current
            element of the input. Default of 0 is equivalent to
            ``(0,)*input.ndim``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The result of greyscale dilation.

    .. seealso:: :func:`scipy.ndimage.grey_dilation`
    Nr   r   r4   r)   r   r	   maxrY   )rw   rD   arrayr/   r;   rH   r   rc   rG   r   r   rC   r1   rP   isscalarr   r   )r{   rj   r   r3   rW   r   r   r4   rZ   iszr%   r%   r&   grey_dilation6  s4   %



r   c                C  `   |dur|durt jdtdd t||||d}	t| |||dfi |	}
t|
||||fi |	S )a  Calculates a multi-dimensional greyscale closing.

    Args:
        input (cupy.ndarray): The input array.
        size (tuple of ints): Shape of a flat and full structuring element used
            for the greyscale closing. Optional if ``footprint`` or
            ``structure`` is provided.
        footprint (array of ints): Positions of non-infinite elements of a flat
            structuring element used for greyscale closing. Non-zero values
            give the set of neighbors of the center over which closing is
            chosen.
        structure (array of ints): Structuring element used for the greyscale
            closing. ``structure`` may be a non-flat structuring element.
        output (cupy.ndarray, dtype or None): The array in which to place the
            output.
        mode (str): The array borders are handled according to the given mode
            (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
            ``'wrap'``). Default is ``'reflect'``.
        cval (scalar): Value to fill past edges of input if mode is
            ``constant``. Default is ``0.0``.
        origin (scalar or tuple of scalar): The origin parameter controls the
            placement of the filter, relative to the center of the current
            element of the input. Default of 0 is equivalent to
            ``(0,)*input.ndim``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The result of greyscale closing.

    .. seealso:: :func:`scipy.ndimage.grey_closing`
    N&ignoring size because footprint is setr)   
stacklevelr   r   r4   rZ   )r   r   UserWarningdictr   r   r{   rj   r   r3   rW   r   r   r4   rZ   kwargsr   r%   r%   r&   grey_closingx     $r   c                C  r   )a  Calculates a multi-dimensional greyscale opening.

    Args:
        input (cupy.ndarray): The input array.
        size (tuple of ints): Shape of a flat and full structuring element used
            for the greyscale opening. Optional if ``footprint`` or
            ``structure`` is provided.
        footprint (array of ints): Positions of non-infinite elements of a flat
            structuring element used for greyscale opening. Non-zero values
            give the set of neighbors of the center over which opening is
            chosen.
        structure (array of ints): Structuring element used for the greyscale
            opening. ``structure`` may be a non-flat structuring element.
        output (cupy.ndarray, dtype or None): The array in which to place the
            output.
        mode (str): The array borders are handled according to the given mode
            (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
            ``'wrap'``). Default is ``'reflect'``.
        cval (scalar): Value to fill past edges of input if mode is
            ``constant``. Default is ``0.0``.
        origin (scalar or tuple of scalar): The origin parameter controls the
            placement of the filter, relative to the center of the current
            element of the input. Default of 0 is equivalent to
            ``(0,)*input.ndim``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The result of greyscale opening.

    .. seealso:: :func:`scipy.ndimage.grey_opening`
    Nr   r)   r   r   )r   r   r   r   r   r   r   r%   r%   r&   grey_opening  r   r   c                C  sv   t ||||d}	t| |||dfi |	}
t|tjr-t| ||||fi |	 t|
||S |
t| |||dfi |	 S )al  
    Multidimensional morphological gradient.

    The morphological gradient is calculated as the difference between a
    dilation and an erosion of the input with a given structuring element.

    Args:
        input (cupy.ndarray): The input array.
        size (tuple of ints): Shape of a flat and full structuring element used
            for the morphological gradient. Optional if ``footprint`` or
            ``structure`` is provided.
        footprint (array of ints): Positions of non-infinite elements of a flat
            structuring element used for morphological gradient. Non-zero
            values give the set of neighbors of the center over which opening
            is chosen.
        structure (array of ints): Structuring element used for the
            morphological gradient. ``structure`` may be a non-flat
            structuring element.
        output (cupy.ndarray, dtype or None): The array in which to place the
            output.
        mode (str): The array borders are handled according to the given mode
            (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
            ``'wrap'``). Default is ``'reflect'``.
        cval (scalar): Value to fill past edges of input if mode is
            ``constant``. Default is ``0.0``.
        origin (scalar or tuple of scalar): The origin parameter controls the
            placement of the filter, relative to the center of the current
            element of the input. Default of 0 is equivalent to
            ``(0,)*input.ndim``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The morphological gradient of the input.

    .. seealso:: :func:`scipy.ndimage.morphological_gradient`
    r   N)r   r   rd   rD   rm   r   subtractr   r%   r%   r&   morphological_gradient  s   2
r   c                C  s   t ||||d}	t| |||dfi |	}
t|tjr;t| ||||fi |	 t|
|| t|| | t|| |S t| |||dfi |	}t|
|| t|| | t|| | |S )a  
    Multidimensional morphological laplace.

    Args:
        input (cupy.ndarray): The input array.
        size (tuple of ints): Shape of a flat and full structuring element used
            for the morphological laplace. Optional if ``footprint`` or
            ``structure`` is provided.
        footprint (array of ints): Positions of non-infinite elements of a flat
            structuring element used for morphological laplace. Non-zero
            values give the set of neighbors of the center over which opening
            is chosen.
        structure (array of ints): Structuring element used for the
            morphological laplace. ``structure`` may be a non-flat
            structuring element.
        output (cupy.ndarray, dtype or None): The array in which to place the
            output.
        mode (str): The array borders are handled according to the given mode
            (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
            ``'wrap'``). Default is ``'reflect'``.
        cval (scalar): Value to fill past edges of input if mode is
            ``constant``. Default is ``0.0``.
        origin (scalar or tuple of scalar): The origin parameter controls the
            placement of the filter, relative to the center of the current
            element of the input. Default of 0 is equivalent to
            ``(0,)*input.ndim``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: The morphological laplace of the input.

    .. seealso:: :func:`scipy.ndimage.morphological_laplace`
    r   N)r   r   rd   rD   rm   r   rS   r   )r{   rj   r   r3   rW   r   r   r4   rZ   r   r   tmp2r%   r%   r&   morphological_laplace  s   /r   c                C  s   |dur|durt jdtdd t||||d}	t| |||dfi |	}
t|
||||fi |	}
| jtjkrF|
jtjkrFt	j
| |
|
d |
S t	j| |
|
d |
S )a  
    Multidimensional white tophat filter.

    Args:
        input (cupy.ndarray): The input array.
        size (tuple of ints): Shape of a flat and full structuring element used
            for the white tophat. Optional if ``footprint`` or ``structure`` is
            provided.
        footprint (array of ints): Positions of non-infinite elements of a flat
            structuring element used for the white tophat. Non-zero values
            give the set of neighbors of the center over which opening is
            chosen.
        structure (array of ints): Structuring element used for the white
            tophat. ``structure`` may be a non-flat structuring element.
        output (cupy.ndarray, dtype or None): The array in which to place the
            output.
        mode (str): The array borders are handled according to the given mode
            (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
            ``'wrap'``). Default is ``'reflect'``.
        cval (scalar): Value to fill past edges of input if mode is
            ``constant``. Default is ``0.0``.
        origin (scalar or tuple of scalar): The origin parameter controls the
            placement of the filter, relative to the center of the current
            element of the input. Default of 0 is equivalent to
            ``(0,)*input.ndim``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarray: Result of the filter of ``input`` with ``structure``.

    .. seealso:: :func:`scipy.ndimage.white_tophat`
    Nr   r)   r   r   rJ   )r   r   r   r   r   r   rM   rP   bool_rD   bitwise_xorr   r   r%   r%   r&   white_tophatK     .r   c                C  s   |dur|durt jdtdd t||||d}	t| |||dfi |	}
t|
||||fi |	}
| jtjkrF|
jtjkrFt	j
|
| |
d |
S t	j|
| |
d |
S )a  
    Multidimensional black tophat filter.

    Args:
        input (cupy.ndarray): The input array.
        size (tuple of ints): Shape of a flat and full structuring element used
            for the black tophat. Optional if ``footprint`` or ``structure`` is
            provided.
        footprint (array of ints): Positions of non-infinite elements of a flat
            structuring element used for the black tophat. Non-zero values
            give the set of neighbors of the center over which opening is
            chosen.
        structure (array of ints): Structuring element used for the black
            tophat. ``structure`` may be a non-flat structuring element.
        output (cupy.ndarray, dtype or None): The array in which to place the
            output.
        mode (str): The array borders are handled according to the given mode
            (``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
            ``'wrap'``). Default is ``'reflect'``.
        cval (scalar): Value to fill past edges of input if mode is
            ``constant``. Default is ``0.0``.
        origin (scalar or tuple of scalar): The origin parameter controls the
            placement of the filter, relative to the center of the current
            element of the input. Default of 0 is equivalent to
            ``(0,)*input.ndim``.
        axes (tuple of int or None): The axes over which to apply the filter.
            If None, `input` is filtered along all axes. If an `origin` tuple
            is provided, its length must match the number of axes.

    Returns:
        cupy.ndarry : Result of the filter of ``input`` with ``structure``.

    .. seealso:: :func:`scipy.ndimage.black_tophat`
    Nr   r)   r   r   r   )r   r   r   r   r   r   rM   rP   r   rD   r   r   r   r%   r%   r&   black_tophat  r   r   r:   )T)Nr	   NNr   r   F)Nr	   Nr   Nr   F)NNNr   N)NNNr   r   )NN)NNr   )NNNNr   r   r   )$
__future__r   rs   r_   r   rP   rD   r   cupyx.scipy.ndimager   r   r   r   memoizer'   r6   rK   rX   r   r   r
   rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r%   r%   r%   r&   <module>   s    

A
& 7>::A
$8D,B,.
?
@
>
