
    `i֨                        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  ej	        d          d             Z
d	 Zd d
Zd Z	 d!dZ	 	 d"dZ	 	 d"dZ	 	 d#dZ	 	 d#dZ	 	 d$dZ	 	 d%dZd&dZ	 	 d'dZ	 	 d'dZ	 	 d'dZ	 	 d'dZ	 	 	 	 	 	 	 d'dZ	 	 	 	 	 	 	 d'dZ	 	 	 	 	 	 	 d'dZ	 	 	 	 	 	 	 d'dZdS )(    N)_core)_filters_core)_util)_filtersT)for_each_devicec                    |rt          |           }d}d}	nd}d}	|r%d                    t          |          |	          }
n$d                    t          |          |	          }
|
d                    |          z   }
d                    t          |          t          |	          t          |          	          }d
}|	r|dz  }t          j        ||
|dd| ||dddd|d|          S )Nr      a&  
            bool mv = (bool)mask[i];
            bool _in = (bool)x[i];
            if (!mv) {{
                y = cast<Y>(_in);
                return;
            }} else if ({center_is_true} && _in == {false_val}) {{
                y = cast<Y>(_in);
                return;
            }})center_is_true	false_valz
            bool _in = (bool)x[i];
            if ({center_is_true} && _in == {false_val}) {{
                y = cast<Y>(_in);
                return;
            }}z%
            y = cast<Y>({true_val});)true_valaa  
        if ({{cond}}) {{{{
            if (!{border_value}) {{{{
                y = cast<Y>({false_val});
                return;
            }}}}
        }}}} else {{{{
            bool nn = {{value}} ? {true_val} : {false_val};
            if (!nn) {{{{
                y = cast<Y>({false_val});
                return;
            }}}}
        }}}})r   r   border_valuebinary_erosion_invert constantYTF)ctypehas_weightshas_structurehas_maskbinary_morphologyall_weights_nonzero)intformatr   _generate_nd_kernel)w_shapeint_typeoffsetsr
   r   invertmaskedr   r   r   prefoundnames                s/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/ndimage/_morphology.py_get_binary_erosion_kernelr%      sK   
  |+,,			 .	 &N(;(;#,  . . 	
 &N(;(;#,  . . 	  ((.(A(ABC H!$Y$'$5$5  8 8 
  D 	,
GXw$f/1 1 1 1    c                     t          d t          | j        |          D                       }t          | |                   S )Nc                 $    g | ]\  }}||d z  z   S     ).0ssoos      r$   
<listcomp>z#_center_is_true.<locals>.<listcomp>Q   s$    JJJ62r"rQw,JJJr&   )tuplezipshapebool)	structureorigincoors      r$   _center_is_truer7   P   s<    JJS&-I-IJJJKKD	$   r&   c                     dk     r                                  S dz
  fd j        D             } fdt          t          |                    D             t	           fdt          t          |                    D                       }t          j        |t                    } dk    ||<   t          |           }||S t          j
        | j        d	t                    }f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                 &    g | ]}||d z
  z  z   S )r	   r+   )r,   iinis     r$   r/   z%iterate_structure.<locals>.<listcomp>j   s&    :::BR"Q-:::r&   c                 6    g | ]}j         |         d z  z  S r)   )r2   )r,   r:   r;   r4   s     r$   r/   z%iterate_structure.<locals>.<listcomp>k   s*    
G
G
Gr2$)*
G
G
Gr&   c              3   n   K   | ]/}t          |         |         j        |         z   d           V  0d S N)slicer2   )r,   r:   posr4   s     r$   	<genexpr>z$iterate_structure.<locals>.<genexpr>l   sW         	c"gs2w!44d;;     r&   r   )
iterationsNr5   c                     g | ]}|z  S r+   r+   )r,   orB   s     r$   r/   z%iterate_structure.<locals>.<listcomp>w   s    111Q*q.111r&   )copyr2   rangelenr0   cupyzerosr3   binary_dilationr   _fix_sequence_argndimr   )r4   rB   r5   r2   slcoutr;   r@   s   ``    @@r$   iterate_structurerO   U   s0   $ A~~~~	aB::::)/:::E
G
G
G
G
GU3u::5F5F
G
G
GC
     E

##    C *UD
!
!CA~CH
#yR
8
8
8C~
(3OO1111&111F{r&   c                 "   |dk     rd}| dk     rt          j        dt                    S t          j        t          j        dg| z            dz
            }t          j                            |d          }||k    }t          j        |          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   )rH   asarrayr3   numpyfabsindicesaddreduce)rankconnectivityoutputs      r$   generate_binary_structurer]   {   s    ( aaxx|D----ZqcDj11A566FYfa((F|#F<r&   c	           
      8   	 t          j        |          }n# t          $ r t          d          w xY w| j        j        dk    rt          d          |%t          | j        d          }| j        dk    }	d}
d}n|                    t          d          }d}|j        | j        k    rt          d          |j
        j        st          j        |          }|j        dk     rt          d	          |B|j        | j        k    rt          d
          |j
        j        st          j        |          }d}nd}t!          j        || j        dt$                    }t'          |t          j                  r |j        j        dk    rt          d          nt          }t!          j        ||           }t          j        || d          }|r|}t!          j        |j        |           }|j        dk    rOt/          |          rt          j        | t                    |d<   nt          j        | t                     |d<   |S t3          |          }t!          j        |           }t7          j        ||j                  }|sAt%          t          j        |                    }||j        k    }	|	rd}
nt=          ||          }
t?          |j        |||
||||	          }|dk    r!|r || |||          }n || ||          }n|
r|stA          d          t          j        || d          rtC          d          t          j"        | |j                  }|}|dk    r	|dz  s||}}|r || |||          }n || ||          }| |k    #                                 }d}||k     s|dk     rX|rV||}}|r |||||          }n ||||          }||k    #                                 }|dz  }|s|dz  sn||k     N|dk     r|V|}|rtI          j%        ||           |}|S )Nz)iterations parameter should be an integerczComplex type not supportedr	   TF)rR   rE   z1structure and input must have same dimensionalityzstructure must not be emptyz$mask and input must have equal sizesr5   z!Complex output type not supportedMAY_SHARE_BOUNDSr   rQ   .z/only brute_force iteration has been implementedz*output and input may not overlap in memory)&operatorindex	TypeErrorrR   kindr]   rL   astyper3   RuntimeErrorflagsc_contiguousrH   ascontiguousarraysizer2   r   rK   r   
isinstancendarray_get_outputshares_memoryfloatrT   r0   _get_inttyper   _origins_to_offsetscount_nonzeror7   r%   NotImplementedError
ValueError
empty_likeallr   elementwise_copy)inputr4   rB   maskr\   r   r5   r   brute_forcer   r
   default_structurer    temp_neededtempr   r   nnzerode_kerneltmp_intmp_outchangedr:   s                          r$   _binary_erosionr      s   E^J//

 E E ECDDDE {34555-ej!<<	#jAo $$4e$<<	 "~##NOOO?' 6*955	~8999:$$EFFFz& 	0)$//D$VUZ3GGF&$,'' <##?@@@ $ vu--F$VU4FGGK 8"6<77~ 	;,uD999F3KK<T::::F3K6]]F!%((H/	HHG @$$Y//00!Y^3 	@!NN,Y??N-7NL+ L
 Q 	<!\%D&AAFF!\%F;;FF	  !=
 
 	
 fe-?@@ 	KIJJJfl;;;??:>?%vGF 	>"l5)T7CCGG"l5)W==G',,...:oo:>>w>%vGF C&,vy$HH&,vy'BB!W,11333G!GB BF   :oo:>>w>  vt,,,Ms    1r	   Fc                 0    t          | ||||||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, 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. (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.

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

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_erosion`
    r   )r   )rx   r4   rB   ry   r\   r   r5   rz   s           r$   r   r   
  s-    T 5)Zv'KA A Ar&   c                    |t          | j        d          }t          j        || j        dt                    }|t          t          ddd          g|j        z                     }t          t          |                    D ].}||          ||<   |j	        |         dz  s||xx         dz  cc<   /t          | ||||||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, 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. (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.

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

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_dilation`
    Nr	   r5   )r]   rL   r   rK   r   r0   r?   rF   rG   r2   r   )	rx   r4   rB   ry   r\   r   r5   rz   r:   s	            r$   rJ   rJ   8  s    N -ej!<<	$VUZ3GGF%tT2!6!6 7). HIIJICKK    Rj[r
r"Q& 	2JJJ!OJJJ5)Zv'KA A Ar&   c           
          || j         }t          |d          }t          | |||d|||          }	t          |	|||||||          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, 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. (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.

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

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_opening`
    Nr	   )rL   r]   r   rJ   
rx   r4   rB   r\   r5   ry   r   rz   rZ   tmps
             r$   binary_openingr   k  sd    V z-dA66	
	:tT%v{< <C3	:tV'> > >r&   c           
          || j         }t          |d          }t          | |||d|||          }	t          |	|||||||          S )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, 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. (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.

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

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_closing`
    Nr	   )rL   r]   rJ   r   r   s
             r$   binary_closingr     sd    V z-dA66	
%Jd&= =C#y*dF&= = =r&   c                 ,   |t          | j        d          }|t          j        |          }t	          j        || j        dt                    }||}n!t	          j        || j        dt                    }t          | |dddd|dd	  	        }t          |t          j	                  }t          | |dd|d|dd	  	        }|r-t          j        ||           t          j
        |||           dS t          j        ||           t          j
        ||          S )ay  
    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``.

    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   F)r]   rL   rH   logical_notr   rK   r   r   rk   rl   logical_and)	rx   
structure1
structure2r\   r   r   tmp1inplaceresults	            r$   binary_hit_or_missr     s   J .uz1==
%j11
%guz9cJJG)'5:y#NN5*atQ " "D..GUJ4GQ"$ $F .(((vv.....(((f---r&   c           
      0    t          | |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.

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

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_propagation`
    r   Trz   )rJ   )rx   r4   ry   r\   r   r5   s         r$   binary_propagationr     s,    : 5)Rv|!t5 5 5 5r&   c           
      X   t          j        |           }t          j        |j        t                    }t          |t           j                  }|r.t          ||d||d|d           t          j        ||           dS t          ||d|dd|d          }t          j        ||           |S )a	  Fill the holes in binary objects.

    Args:
        input (cupy.ndarray): N-D binary array with holes to be filled.
        structure (cupy.ndarray, optional):  Structuring element used in the
            computation; large-size elements make 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.

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

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`scipy.ndimage.binary_fill_holes`
    r   r	   Tr   N)rH   r   rI   r2   r3   rk   rl   rJ   )rx   r4   r\   r5   ry   r   r   s          r$   binary_fill_holesr   0  s    4 E""D
*TZ
&
&C..G YD&!V$(	* 	* 	* 	*((((( iT4F-13 3 3(((r&   reflect        c                 d    |||t          d          t          j        | |||||||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``.

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

    .. seealso:: :func:`scipy.ndimage.grey_erosion`
    N.size, footprint or structure must be specifiedmin)rt   r   _min_or_max_filter)rx   rj   	footprintr4   r\   modecvalr5   s           r$   grey_erosionr   Y  sN    B |	)i.?IJJJ&udIy'-tT65J J Jr&   c                    |||t          d          |At          j        |          }|t          t	          ddd          g|j        z                     }|At          j        |          }|t          t	          ddd          g|j        z                     }t          j        || j        dt                    }t          t          |                    D ]f}||          ||<   ||j        |         }	n/||j        |         }	nt          j        |          r|}	n||         }	|	dz  dk    r||xx         dz  cc<   gt          j        | |||||||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``.

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

    .. seealso:: :func:`scipy.ndimage.grey_dilation`
    Nr   r   r5   r*   r   r	   max)rt   rH   arrayr0   r?   rL   r   rK   r   rF   rG   r2   rU   isscalarr   r   )
rx   rj   r   r4   r\   r   r   r5   iszs
             r$   grey_dilationr     sy   B |	)i.?IJJJJy))	eU4r%:%:$;in$LMMN	Jy))	eU4r%:%:$;in$LMMN	$VUZ3GGF3v;;  AYJq	 #BB"#BB^D!! 	BBaB6Q;;1IIINIII&udIy'-tT65J J Jr&   c           
          ||t          j        dt          d           t          | |||d|||          }t	          ||||||||          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``.

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

    .. seealso:: :func:`scipy.ndimage.grey_closing`
    N&ignoring size because footprint is setr*   
stacklevel)warningswarnUserWarningr   r   	rx   rj   r   r4   r\   r   r   r5   r   s	            r$   grey_closingr     st    @ 	y4>!"	$ 	$ 	$ 	$
tY	4t   CT9it     r&   c           
          ||t          j        dt          d           t          | |||d|||          }t	          ||||||||          S )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``.

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

    .. seealso:: :func:`scipy.ndimage.grey_opening`
    Nr   r*   r   )r   r   r   r   r   r   s	            r$   grey_openingr     st    @ 	y4>!"	$ 	$ 	$ 	$
udIy$d CdIy&$! ! !r&   c                     t          | |||d|||          }t          |t          j                  r,t	          | |||||||           t          j        |||          S |t	          | |||d|||          z
  S )a  
    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``.

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

    .. seealso:: :func:`scipy.ndimage.morphological_gradient`
    N)r   rk   rH   rl   r   subtractr   s	            r$   morphological_gradientr     s    Z tY	4tV C &$,'' 
4IvtT6	
 	
 	
 }S&&111\4ItT4
 
 
 	
r&   c           
         t          | |||d|||          }t          |t          j                  rXt	          | |||||||           t          j        |||           t          j        || |           t          j        || |          S t	          | |||d|||          }	t          j        ||	|	           t          j        |	| |	           t          j        |	| |	           |	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``.

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

    .. seealso:: :func:`scipy.ndimage.morphological_laplace`
    N)r   rk   rH   rl   r   rX   r   )
rx   rj   r   r4   r\   r   r   r5   r   tmp2s
             r$   morphological_laplacer   J  s    T tY	4tV D &$,'' 4IvtT6	
 	
 	
 	vv&&&feV,,,}VUF3334ItT4
 
 	tT"""dE4(((dE4(((r&   c           
      P   ||t          j        dt          d           t          | |||d|||          }t	          ||||||||          }| j        t          j        k    r-|j        t          j        k    rt          j	        | ||           nt          j
        | ||           |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``.

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

    .. seealso:: :func:`scipy.ndimage.white_tophat`
    Nr   r*   r   rN   )r   r   r   r   r   rR   rU   bool_rH   bitwise_xorr   r   s	            r$   white_tophatr     s    R 	y44ka	
 	
 	
 	
 tY	4tV C T9itV C {ek!!ci5;&>&>-----eSc****Jr&   c           
      P   ||t          j        dt          d           t          | |||d|||          }t	          ||||||||          }| j        t          j        k    r-|j        t          j        k    rt          j	        || |           nt          j
        || |           |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``.

    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   rR   rU   r   rH   r   r   r   s	            r$   black_tophatr     s    R 	y44ka	
 	
 	
 	
 tY	4tV C T9itV C {ek!!ci5;&>&>e-----c5c****Jr&   r>   )T)Nr	   NNr   r   F)Nr	   Nr   Nr   F)NNNr   N)NNNr   r   )NNr   )NNNNr   r   r   )ra   r   rU   rH   r   cupyx.scipy.ndimager   r   r   memoizer%   r7   rO   r]   r   r   rJ   r   r   r   r   r   r   r   r   r   r   r   r   r   r+   r&   r$   <module>r      s             - - - - - - % % % % % % ( ( ( ( ( ( d###>1 >1 $#>1B! ! !
# # # #L     > 15n n n nb KO9>+A +A +A +A\ ?CGL0A 0A 0A 0Af MN:?1> 1> 1> 1>h MN:?1= 1= 1= 1=h HL*.9. 9. 9. 9.x AE./5 5 5 5B& & & &R KO23%J %J %J %JP ?C@A9J 9J 9J 9Jx >B?@&  &  &  & R >B?@&! &! &! &!V 
		8
 8
 8
 8
z 
		; ; ; ;@ 
		7 7 7 7x 
		7 7 7 7 7 7r&   