
    (ph                       S SK r S SKrS SKrSSKJr  SSKJr  SSKJr  / SQrS r	SS jr
S	 rS
 r  S SS.S jjr   S SS.S jjr  S!SS.S jjr  S!SS.S jjr  S"SS.S jjr  S#SS.S jjrS$SS.S jjr  S%SS.S jjr  S%SS.S jjr  S%SS.S jjr  S%SS.S jjr  S%SS.S jjr  S%SS.S jjr  S%SS.S jjr  S%SS.S jjr   S&S jr  S'S jr  S(S jrS rg))    N   )_ni_support)	_nd_image)_filters)iterate_structuregenerate_binary_structurebinary_erosionbinary_dilationbinary_openingbinary_closingbinary_hit_or_missbinary_propagationbinary_fill_holesgrey_erosiongrey_dilationgrey_openinggrey_closingmorphological_gradientmorphological_laplacewhite_tophatblack_tophatdistance_transform_bfdistance_transform_cdtdistance_transform_edtc           	          [         R                  " U 5      n [        [        U R                  U5       VVs/ s H  u  p#X2S-  -   PM     snn5      n[        X   5      $ s  snnf )N   )npasarraytuplezipshapebool)	structureoriginssoocoors        L/var/www/html/venv/lib/python3.13/site-packages/scipy/ndimage/_morphology.py_center_is_truer)   0   s]    

9%IS17.9 : .962"Qw, .9 : ;D	  :s   A
c                 ^  ^ ^	 [         R                  " T 5      m US:  a  T R                  5       $ US-
  nT R                   Vs/ s H  oDX4S-
  -  -   PM     nn[	        [        U5      5       Vs/ s H  oCT R                  U   S-  -  PM     snm	[        U	U 4S j[	        [        U5      5       5       5      n[         R                  " U[        5      nT S:g  Xv'   [        UT US9nUc  U$ [        R                  " UT R                  5      nU Vs/ s H  oU-  PM	     nnXr4$ s  snf s  snf s  snf )a  
Iterate a structure by dilating it with itself.

Parameters
----------
structure : array_like
   Structuring element (an array of bools, for example), to be dilated with
   itself.
iterations : int
   number of dilations performed on the structure with itself
origin : 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
-------
iterate_structure : ndarray of bools
    A new structuring element obtained by dilating `structure`
    (`iterations` - 1) times with itself.

See Also
--------
generate_binary_structure

Examples
--------
>>> from scipy import ndimage
>>> struct = ndimage.generate_binary_structure(2, 1)
>>> struct.astype(int)
array([[0, 1, 0],
       [1, 1, 1],
       [0, 1, 0]])
>>> ndimage.iterate_structure(struct, 2).astype(int)
array([[0, 0, 1, 0, 0],
       [0, 1, 1, 1, 0],
       [1, 1, 1, 1, 1],
       [0, 1, 1, 1, 0],
       [0, 0, 1, 0, 0]])
>>> ndimage.iterate_structure(struct, 3).astype(int)
array([[0, 0, 0, 1, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1, 1, 1],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 0, 1, 0, 0, 0]])

r   r   c              3   j   >#    U  H(  n[        TU   TU   TR                  U   -   S 5      v   M*     g 7fN)slicer!   ).0iiposr#   s     r(   	<genexpr>$iterate_structure.<locals>.<genexpr>o   s:      -+B c"gs2w)<<dCC+s   03r   )
iterations)r   r   copyr!   rangelenr   zerosr"   r
   r   _normalize_sequencendim)
r#   r3   r$   nir/   r!   slcoutor0   s
   `        @r(   r   r   7   s   d 

9%IA~~~	aB*3//:/B"Q-/E:5:3u:5F
G5Fr$)*5F
GC
 -E
+- -C
((5$
CA~CH
#yR
8C~
00H*01&Qq.&1{ ;
G 2s   D -D%D*c                     US:  a  SnU S:  a  [         R                  " S[        S9$ [         R                  " [         R                  " S/U -  5      S-
  5      n[         R
                  R                  US5      nX!:*  $ )a~
  
Generate a binary structure for binary morphological operations.

Parameters
----------
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
-------
output : ndarray of bools
     Structuring element which may be used for binary morphological
     operations, with `rank` dimensions and all dimensions equal to 3.

See Also
--------
iterate_structure, binary_dilation, binary_erosion

Notes
-----
`generate_binary_structure` can only create structuring elements with
dimensions equal to 3, i.e., minimal dimensions. For larger structuring
elements, that are useful e.g., for eroding large objects, one may either
use `iterate_structure`, or create directly custom arrays with
numpy functions such as `numpy.ones`.

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> struct = ndimage.generate_binary_structure(2, 1)
>>> struct
array([[False,  True, False],
       [ True,  True,  True],
       [False,  True, False]], dtype=bool)
>>> a = np.zeros((5,5))
>>> a[2, 2] = 1
>>> a
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
>>> b
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
array([[ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.]])
>>> struct = ndimage.generate_binary_structure(2, 2)
>>> struct
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> struct = ndimage.generate_binary_structure(3, 1)
>>> struct # no diagonal elements
array([[[False, False, False],
        [False,  True, False],
        [False, False, False]],
       [[False,  True, False],
        [ True,  True,  True],
        [False,  True, False]],
       [[False, False, False],
        [False,  True, False],
        [False, False, False]]], dtype=bool)

r   Tdtype   r   )r   arrayr"   fabsindicesaddreduce)rankconnectivityoutputs      r(   r   r   |   si    f aaxxxD))WWRZZd
+a/0FVV]]61%F!!    c
                     [         R                  " U5      n[        R                  " U 5      n U R
                  n[        R                  " U 5      (       a  [        S5      e[        R                  " XR
                  5      n	[        U	5      nUc  [        US5      nO[        R                  " U[        S9nX:  a  [        R                  " XUSS9nUR
                  U R
                  :w  a  [        S5      eUR                  R                   (       d  UR#                  5       nUR$                  S:  a  [        S5      eUb;  [        R                  " U5      nUR&                  U R&                  :w  a  [        S	5      e[        R(                  " Xl5      n[        R*                  " XU5      n[-        X5      n[/        U[        R0                  5      (       a'  [        R                  " U5      (       a  [        S
5      eO[        n[        R2                  " X@5      n[        R4                  " X5      nU(       a#  Un[        R2                  " UR6                  U 5      nUS:X  a  [8        R:                  " XX4XVX}S5	        GOU(       Ga  U(       d  [8        R:                  " XX4XVX}S5	      u  nnU[=        [?        S S S5      /UR
                  -  5         n[A        [        U5      5       H2  nUU   * UU'   UR&                  U   S-  (       a  M%  UU==   S-  ss'   M4     Ub#  [        R                  " U[        RB                  S9nUR                  R                   (       d  UR#                  5       n[8        RD                  " XAX2S-
  XgU5        O[        RF                  " U [        S9nUnUS:  a  US-  (       d  UUnn[8        R:                  " XUUXVX}S5	      nSnUU:  d  US:  aB  U(       a;  UUnn[8        R:                  " UXUXVX}S5	      nUS-  nUU:  a  M,  US:  a	  U(       a  M;  U(       a  UWS'   UnU$ ! [         a  n
[        S5      U
eS n
A
ff = f)Nz)iterations parameter should be an integerzComplex type not supportedr   r?   r#   )footprint_namez1structure and input must have same dimensionalityzstructure must not be emptyz$mask and input must have equal sizesz!Complex output type not supportedr   .)$operatorindex	TypeErrorr   r   r9   iscomplexobjr   _check_axesr6   r   r"   r   _expand_footprintRuntimeErrorflags
contiguousr4   sizer!   r8   _expand_originr)   
isinstancendarray_get_outputmay_share_memoryr@   r   r	   r   r-   r5   int8binary_erosion2
empty_like)inputr#   r3   maskrI   border_valuer$   invertbrute_forceaxeser9   num_axescittemp_neededtempchangedcoordinate_listr/   tmp_intmp_outs                        r(   _binary_erosionro      s   L^^J/
 JJuE::D	u455""44D4yH-h:	JJy5	..t9>IK	 ~~#NOO??%%NN$	~~899zz$::$EFF,,V>F$$T8F
)
,C&"**%%??6""?@@ # $$V3F%%e4K((u=Q  4!-vA	G	[#,#;#;d&q$2  eU4r%:$;$-NN%3 4 5	F$B *F2J??2&**r
a
 % ::d"''2D))!(I!!&T>"(/	C uD1?:>%vGF**dG&q2 :o*q.W%vGF..	f16G !GB :o*q.WW S	M]  LCD!KLs   P) )
Q3P??Qre   c                "    [        XX#XEUSXx5
      $ )aD  
Multidimensional binary erosion with a given structuring element.

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

Parameters
----------
input : array_like
    Binary image to be eroded. Non-zero (True) elements form
    the subset to be eroded.
structure : array_like, optional
    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.
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.
mask : array_like, optional
    If a mask is given, only those elements with a True value at
    the corresponding mask element are modified at each iteration.
output : 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.
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.
    False by default.
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
-------
binary_erosion : ndarray of bools
    Erosion of the input by the structuring element.

See Also
--------
grey_erosion, binary_dilation, binary_closing, binary_opening,
generate_binary_structure

Notes
-----
Erosion [1]_ is a mathematical morphology operation [2]_ that uses a
structuring element for shrinking the shapes in an image. The binary
erosion of an image by a structuring element is the locus of the points
where a superimposition of the structuring element centered on the point
is entirely contained in the set of non-zero elements of the image.

References
----------
.. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29
.. [2] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[1:6, 2:5] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.binary_erosion(a).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> #Erosion removes objects smaller than the structure
>>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
array([[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, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])

r   )ro   )	r`   r#   r3   ra   rI   rb   r$   rd   re   s	            r(   r	   r	   -  s!    D 5Z!KO OrJ   c                   [         R                  " U 5      n [        R                  " XR                  5      n[        U5      n	Uc  [        U	S5      n[        R                  " Xi5      n[         R                  " U5      nU[        [        SSS5      /UR                  -  5         n[        [        U5      5       H/  n
Xj   * Xj'   UR                  U
   S-  (       a  M#  Xj==   S-  ss'   M1     [        XX#XEUSXx5
      $ )a  
Multidimensional binary dilation with the given structuring element.

Parameters
----------
input : array_like
    Binary array_like to be dilated. Non-zero (True) elements form
    the subset to be dilated.
structure : array_like, optional
    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.
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 : array_like, optional
    If a mask is given, only those elements with a True value at
    the corresponding mask element are modified at each iteration.
output : 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.
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. False by default.
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
-------
binary_dilation : ndarray of bools
    Dilation of the input by the structuring element.

See Also
--------
grey_dilation, binary_erosion, binary_closing, binary_opening,
generate_binary_structure

Notes
-----
Dilation [1]_ is a mathematical morphology operation [2]_ that uses a
structuring element for expanding the shapes in an image. The binary
dilation of an image by a structuring element is the locus of the points
covered by the structuring element, when its center lies within the
non-zero points of the image.

References
----------
.. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29
.. [2] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5, 5))
>>> a[2, 2] = 1
>>> a
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a)
array([[False, False, False, False, False],
       [False, False,  True, False, False],
       [False,  True,  True,  True, False],
       [False, False,  True, False, False],
       [False, False, False, False, False]], dtype=bool)
>>> ndimage.binary_dilation(a).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> # 3x3 structuring element with connectivity 1, used by default
>>> struct1 = ndimage.generate_binary_structure(2, 1)
>>> struct1
array([[False,  True, False],
       [ True,  True,  True],
       [False,  True, False]], dtype=bool)
>>> # 3x3 structuring element with connectivity 2
>>> struct2 = ndimage.generate_binary_structure(2, 2)
>>> struct2
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a, structure=struct1,\
... iterations=2).astype(a.dtype)
array([[ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.]])

Nr   rM   )r   r   r   rR   r9   r6   r   r8   r   r-   r5   r!   ro   )r`   r#   r3   ra   rI   rb   r$   rd   re   rg   r/   s              r(   r
   r
     s    r JJuE""44D4yH-h:	,,V>F

9%I%tT2!6 7 )!/ 0 1ICK j[
r"Q&&J!OJ !
 5Z!KO OrJ   c                    [         R                  " U 5      n [        R                  " XR                  5      n[        U5      n	Uc  [        U	S5      n[        XX%SXdXxS9	n
[        XX%UXdXxS9	$ )a9  
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.

Parameters
----------
input : array_like
    Binary array_like to be opened. Non-zero (True) elements form
    the subset to be opened.
structure : array_like, optional
    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 (i.e., only
    nearest neighbors are connected to the center, diagonally-connected
    elements are not considered neighbors).
iterations : int, optional
    The erosion step of the opening, then the dilation step are each
    repeated `iterations` times (one, by default). If `iterations` is
    less than 1, each operation is repeated until the result does
    not change anymore. Only an integer of iterations is accepted.
output : 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 : array_like, optional
    If a mask is given, only those elements with a True value at
    the corresponding mask element are modified at each iteration.

    .. versionadded:: 1.1.0
border_value : int (cast to 0 or 1), optional
    Value at the border in the output array.

    .. versionadded:: 1.1.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 in the
    current iteration; if true all pixels are considered as candidates for
    update, regardless of what happened in the previous iteration.
    False by default.

    .. versionadded:: 1.1.0
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
-------
binary_opening : ndarray of bools
    Opening of the input by the structuring element.

See Also
--------
grey_opening, binary_closing, binary_erosion, binary_dilation,
generate_binary_structure

Notes
-----
*Opening* [1]_ is a mathematical morphology operation [2]_ that
consists in the succession of an erosion and a dilation of the
input with the same structuring element. Opening, therefore, removes
objects smaller than the structuring element.

Together with *closing* (`binary_closing`), opening can be used for
noise removal.

References
----------
.. [1] https://en.wikipedia.org/wiki/Opening_%28morphology%29
.. [2] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5,5), dtype=int)
>>> a[1:4, 1:4] = 1; a[4, 4] = 1
>>> a
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 1]])
>>> # Opening removes small objects
>>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int)
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])
>>> # Opening can also smooth corners
>>> ndimage.binary_opening(a).astype(int)
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0]])
>>> # Opening is the dilation of the erosion of the input
>>> ndimage.binary_erosion(a).astype(int)
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> ndimage.binary_dilation(ndimage.binary_erosion(a)).astype(int)
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0]])

Nr   rp   )	r   r   r   rR   r9   r6   r   r	   r
   r`   r#   r3   rI   r$   ra   rb   rd   re   rg   tmps              r(   r   r     sr    l JJuE""44D4yH-h:	
:T%{GC3:V'I IrJ   c                    [         R                  " U 5      n [        R                  " XR                  5      n[        U5      n	Uc  [        U	S5      n[        XX%SXdXxS9	n
[        XX%UXdXxS9	$ )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.

Parameters
----------
input : array_like
    Binary array_like to be closed. Non-zero (True) elements form
    the subset to be closed.
structure : array_like, optional
    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 (i.e., only
    nearest neighbors are connected to the center, diagonally-connected
    elements are not considered neighbors).
iterations : int, optional
    The dilation step of the closing, then the erosion step are each
    repeated `iterations` times (one, by default). If iterations is
    less than 1, each operations is repeated until the result does
    not change anymore. Only an integer of iterations is accepted.
output : 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 : array_like, optional
    If a mask is given, only those elements with a True value at
    the corresponding mask element are modified at each iteration.

    .. versionadded:: 1.1.0
border_value : int (cast to 0 or 1), optional
    Value at the border in the output array.

    .. versionadded:: 1.1.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 in the
    current iteration; if true al pixels are considered as candidates for
    update, regardless of what happened in the previous iteration.
    False by default.

    .. versionadded:: 1.1.0
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
-------
binary_closing : ndarray of bools
    Closing of the input by the structuring element.

See Also
--------
grey_closing, binary_opening, binary_dilation, binary_erosion,
generate_binary_structure

Notes
-----
*Closing* [1]_ is a mathematical morphology operation [2]_ that
consists in the succession of a dilation and an erosion of the
input with the same structuring element. Closing therefore fills
holes smaller than the structuring element.

Together with *opening* (`binary_opening`), closing can be used for
noise removal.

References
----------
.. [1] https://en.wikipedia.org/wiki/Closing_%28morphology%29
.. [2] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5,5), dtype=int)
>>> a[1:-1, 1:-1] = 1; a[2,2] = 0
>>> a
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 0, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])
>>> # Closing removes small holes
>>> ndimage.binary_closing(a).astype(int)
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])
>>> # Closing is the erosion of the dilation of the input
>>> ndimage.binary_dilation(a).astype(int)
array([[0, 1, 1, 1, 0],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [0, 1, 1, 1, 0]])
>>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int)
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])


>>> a = np.zeros((7,7), dtype=int)
>>> a[1:6, 2:5] = 1; a[1:3,3] = 0
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 1, 0, 0],
       [0, 0, 1, 0, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> # In addition to removing holes, closing can also
>>> # coarsen boundaries with fine hollows.
>>> ndimage.binary_closing(a).astype(int)
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int)
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])

Nr   rp   )	r   r   r   rR   r9   r6   r   r
   r	   rt   s              r(   r   r     sr    Z JJuE""44D4yH-h:	
%Jd&HC#*F&H HrJ   c                   [         R                  " U 5      n [        R                  " X`R                  5      n[        U5      nUc  [        US5      nO[         R                  " U5      nUc  [         R                  " U5      n[        R                  " XG5      nUc  UnO[        R                  " XW5      n[        XSSSSUSSU5
      n[        U[         R                  5      n	[        XSSUSUSSU5
      n
U	(       a.  [         R                  " X35        [         R                  " XU5        g[         R                  " X5        [         R                  " X5      $ )a  
Multidimensional binary hit-or-miss transform.

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

Parameters
----------
input : array_like (cast to booleans)
    Binary image where a pattern is to be detected.
structure1 : array_like (cast to booleans), 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 : array_like (cast to booleans), 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 : ndarray, 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, 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 `origin1` or `origin2` tuples are provided, their
    length must match the number of axes.

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

See Also
--------
binary_erosion

References
----------
.. [1] https://en.wikipedia.org/wiki/Hit-or-miss_transform

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[1, 1] = 1; a[2:4, 2:4] = 1; a[4:6, 4:6] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 0, 0, 0],
       [0, 0, 1, 1, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> structure1 = np.array([[1, 0, 0], [0, 1, 1], [0, 1, 1]])
>>> structure1
array([[1, 0, 0],
       [0, 1, 1],
       [0, 1, 1]])
>>> # Find the matches of structure1 in the array a
>>> ndimage.binary_hit_or_miss(a, structure1=structure1).astype(int)
array([[0, 0, 0, 0, 0, 0, 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, 0, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> # Change the origin of the filter
>>> # origin1=1 is equivalent to origin1=(1,1) here
>>> ndimage.binary_hit_or_miss(a, structure1=structure1,\
... origin1=1).astype(int)
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [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, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 0]])

Nr   r   F)r   r   r   rR   r9   r6   r   logical_notr8   ro   rY   rZ   logical_and)r`   
structure1
structure2rI   origin1origin2re   rg   tmp1inplaceresults              r(   r   r   9  s   t JJuE""44D4yH.x;
ZZ
+
^^J/
--g@G11'D5atQeT+D,GU4$a6F
v&
tV,
v&~~d++rJ   c                    [        XSX#XEUS9$ )a  
Multidimensional binary propagation with the given structuring element.

Parameters
----------
input : array_like
    Binary image to be propagated inside `mask`.
structure : array_like, 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 : array_like, optional
    Binary mask defining the region into which `input` is allowed to
    propagate.
output : 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.
origin : int or tuple of ints, optional
    Placement of the filter, by default 0.
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
-------
binary_propagation : ndarray
    Binary propagation of `input` inside `mask`.

Notes
-----
This function is functionally equivalent to calling binary_dilation
with the number of iterations less than one: iterative dilation until
the result does not change anymore.

The succession of an erosion and propagation inside the original image
can be used instead of an *opening* for deleting small objects while
keeping the contours of larger objects untouched.

References
----------
.. [1] http://cmm.ensmp.fr/~serra/cours/pdf/en/ch6en.pdf, slide 15.
.. [2] I.T. Young, J.J. Gerbrands, and L.J. van Vliet, "Fundamentals of
    image processing", 1998
    ftp://qiftp.tudelft.nl/DIPimage/docs/FIP2.3.pdf

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> input = np.zeros((8, 8), dtype=int)
>>> input[2, 2] = 1
>>> mask = np.zeros((8, 8), dtype=int)
>>> mask[1:4, 1:4] = mask[4, 4]  = mask[6:8, 6:8] = 1
>>> input
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [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, 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, 0]])
>>> mask
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 0, 1, 1]])
>>> ndimage.binary_propagation(input, mask=mask).astype(int)
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0]])
>>> ndimage.binary_propagation(input, mask=mask,\
... structure=np.ones((3,3))).astype(int)
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 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]])

>>> # Comparison between opening and erosion+propagation
>>> a = np.zeros((6,6), dtype=int)
>>> a[2:5, 2:5] = 1; a[0, 0] = 1; a[5, 5] = 1
>>> a
array([[1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 1]])
>>> ndimage.binary_opening(a).astype(int)
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0],
       [0, 0, 1, 1, 1, 0],
       [0, 0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0, 0]])
>>> b = ndimage.binary_erosion(a)
>>> b.astype(int)
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 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]])
>>> ndimage.binary_propagation(b, mask=a).astype(int)
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0]])

rM   rp   )r
   )r`   r#   ra   rI   rb   r$   re   s          r(   r   r     s    H 5R'd< <rJ   c                z   [         R                  " U 5      n [         R                  " U 5      n[         R                  " UR                  [
        5      n[        U[         R                  5      nU(       a$  [        XaSXRSX4S9  [         R                  " X"5        g[        XaSUSSX4S9n[         R                  " X"5        U$ )aG  
Fill the holes in binary objects.


Parameters
----------
input : array_like
    N-D binary array with holes to be filled
structure : array_like, 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 : ndarray, 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.
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
-------
out : ndarray
    Transformation of the initial image `input` where holes have been
    filled.

See Also
--------
binary_dilation, binary_propagation, label

Notes
-----
The algorithm used in this function consists in invading the complementary
of the shapes in `input` from the outer boundary of the image,
using binary dilations. Holes are not connected to the boundary and are
therefore not invaded. The result is the complementary subset of the
invaded region.

References
----------
.. [1] https://en.wikipedia.org/wiki/Mathematical_morphology


Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5, 5), dtype=int)
>>> a[1:4, 1:4] = 1
>>> a[2,2] = 0
>>> a
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 0, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])
>>> ndimage.binary_fill_holes(a).astype(int)
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])
>>> # Too big structuring element
>>> ndimage.binary_fill_holes(a, structure=np.ones((5,5))).astype(int)
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 0, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])

rM   r   rp   N)	r   r   rx   r7   r!   r"   rY   rZ   r
   )r`   r#   rI   r$   re   ra   ru   r   s           r(   r   r   7  s    Z JJuE>>% D
((4::t
$C,GD!VO
v& T4!'4
v&rJ   c                \    Uc  Uc  Uc  [        S5      e[        R                  " XX#XEXgSUS9
$ )a@  
Calculate a greyscale erosion, using either a structuring element,
or a footprint corresponding to a flat structuring element.

Grayscale erosion is a mathematical morphology operation. For the
simple case of a full and flat structuring element, it can be viewed
as a minimum filter over a sliding window.

Parameters
----------
input : array_like
    Array over which the grayscale erosion is to be computed.
size : tuple of ints
    Shape of a flat and full structuring element used for the grayscale
    erosion. Optional if `footprint` or `structure` is provided.
footprint : array of ints, optional
    Positions of non-infinite elements of a flat structuring element
    used for the grayscale erosion. Non-zero values give the set of
    neighbors of the center over which the minimum is chosen.
structure : array of ints, optional
    Structuring element used for the grayscale erosion. `structure`
    may be a non-flat structuring element. The `structure` array applies a
    subtractive offset for each pixel in the neighborhood.
output : array, optional
    An array used for storing the output of the erosion may be provided.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
    The `mode` parameter determines how the array borders are
    handled, where `cval` is the value when mode is equal to
    'constant'. Default is 'reflect'
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'. Default
    is 0.0.
origin : scalar, optional
    The `origin` parameter controls the placement of the filter.
    Default 0
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
-------
output : ndarray
    Grayscale erosion of `input`.

See Also
--------
binary_erosion, grey_dilation, grey_opening, grey_closing
generate_binary_structure, minimum_filter

Notes
-----
The grayscale erosion of an image input by a structuring element s defined
over a domain E is given by:

(input+s)(x) = min {input(y) - s(x-y), for y in E}

In particular, for structuring elements defined as
s(y) = 0 for y in E, the grayscale erosion computes the minimum of the
input image inside a sliding window defined by E.

Grayscale erosion [1]_ is a *mathematical morphology* operation [2]_.

References
----------
.. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29
.. [2] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[1:6, 1:6] = 3
>>> a[4,4] = 2; a[2,3] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 3, 3, 3, 3, 3, 0],
       [0, 3, 3, 1, 3, 3, 0],
       [0, 3, 3, 3, 3, 3, 0],
       [0, 3, 3, 3, 2, 3, 0],
       [0, 3, 3, 3, 3, 3, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_erosion(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 3, 2, 2, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> footprint = ndimage.generate_binary_structure(2, 1)
>>> footprint
array([[False,  True, False],
       [ True,  True,  True],
       [False,  True, False]], dtype=bool)
>>> # Diagonally-connected elements are not considered neighbors
>>> ndimage.grey_erosion(a, footprint=footprint)
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 3, 1, 2, 0, 0],
       [0, 0, 3, 2, 2, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])

/size, footprint, or structure must be specifiedr   rp   )
ValueErrorr   _min_or_max_filter)	r`   rW   	footprintr#   rI   modecvalr$   re   s	            r(   r   r     sA    \ |	)i.?JKK&&uI'-T1,02 2rJ   c                   Uc  Uc  Uc  [        S5      eUb=  [        R                  " U5      nU[        [	        SSS5      /UR
                  -  5         nUb=  [        R                  " U5      nU[        [	        SSS5      /UR
                  -  5         n[        R                  " U 5      n [        R                  " XR
                  5      n[        R                  " U[        U5      5      n[        [        U5      5       Hj  n	Xy   * Xy'   Ub  UR                  U	   n
O5Ub  UR                  U	   n
O"[        R                  " U5      (       a  Un
OX   n
U
S-  (       a  M^  Xy==   S-  ss'   Ml     [        R                  " XX#XEXgSUS9
$ )a  
Calculate a greyscale dilation, using either a structuring element,
or a footprint corresponding to a flat structuring element.

Grayscale dilation is a mathematical morphology operation. For the
simple case of a full and flat structuring element, it can be viewed
as a maximum filter over a sliding window.

Parameters
----------
input : array_like
    Array over which the grayscale dilation is to be computed.
size : tuple of ints
    Shape of a flat and full structuring element used for the grayscale
    dilation. Optional if `footprint` or `structure` is provided.
footprint : array of ints, optional
    Positions of non-infinite elements of a flat structuring element
    used for the grayscale dilation. Non-zero values give the set of
    neighbors of the center over which the maximum is chosen.
structure : array of ints, optional
    Structuring element used for the grayscale dilation. `structure`
    may be a non-flat structuring element. The `structure` array applies an
    additive offset for each pixel in the neighborhood.
output : array, optional
    An array used for storing the output of the dilation may be provided.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
    The `mode` parameter determines how the array borders are
    handled, where `cval` is the value when mode is equal to
    'constant'. Default is 'reflect'
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'. Default
    is 0.0.
origin : scalar, optional
    The `origin` parameter controls the placement of the filter.
    Default 0
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
-------
grey_dilation : ndarray
    Grayscale dilation of `input`.

See Also
--------
binary_dilation, grey_erosion, grey_closing, grey_opening
generate_binary_structure, maximum_filter

Notes
-----
The grayscale dilation of an image input by a structuring element s defined
over a domain E is given by:

(input+s)(x) = max {input(y) + s(x-y), for y in E}

In particular, for structuring elements defined as
s(y) = 0 for y in E, the grayscale dilation computes the maximum of the
input image inside a sliding window defined by E.

Grayscale dilation [1]_ is a *mathematical morphology* operation [2]_.

References
----------
.. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29
.. [2] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[2:5, 2:5] = 1
>>> a[4,4] = 2; a[2,3] = 3
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 3, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 2, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_dilation(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 1, 3, 3, 3, 1, 0],
       [0, 1, 3, 3, 3, 1, 0],
       [0, 1, 3, 3, 3, 2, 0],
       [0, 1, 1, 2, 2, 2, 0],
       [0, 1, 1, 2, 2, 2, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_dilation(a, footprint=np.ones((3,3)))
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 1, 3, 3, 3, 1, 0],
       [0, 1, 3, 3, 3, 1, 0],
       [0, 1, 3, 3, 3, 2, 0],
       [0, 1, 1, 2, 2, 2, 0],
       [0, 1, 1, 2, 2, 2, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> s = ndimage.generate_binary_structure(2,1)
>>> s
array([[False,  True, False],
       [ True,  True,  True],
       [False,  True, False]], dtype=bool)
>>> ndimage.grey_dilation(a, footprint=s)
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 3, 1, 0, 0],
       [0, 1, 3, 3, 3, 1, 0],
       [0, 1, 1, 3, 2, 1, 0],
       [0, 1, 1, 2, 2, 2, 0],
       [0, 0, 1, 1, 2, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_dilation(a, size=(3,3), structure=np.ones((3,3)))
array([[1, 1, 1, 1, 1, 1, 1],
       [1, 2, 4, 4, 4, 2, 1],
       [1, 2, 4, 4, 4, 2, 1],
       [1, 2, 4, 4, 4, 3, 1],
       [1, 2, 2, 3, 3, 3, 1],
       [1, 2, 2, 3, 3, 3, 1],
       [1, 1, 1, 1, 1, 1, 1]])

Nr   rM   r   r   rp   )r   r   r   r   r-   r9   r   rR   r8   r6   r5   r!   isscalarr   r   )r`   rW   r   r#   rI   r   r   r$   re   r/   szs              r(   r   r     sp   z |	)i.?JKKJJy)	eU4r%:$;$-NN%3 4 5	JJy)	eU4r%:$;$-NN%3 4 5	 JJuE""44D,,VSY?FCK j[
 $B"$B[[BBAvvJ!OJ ! &&uI'-T1,02 2rJ   c                x    Ub  Ub  [         R                  " S[        SS9  [        XX#SUXgUS9	n	[	        XX#XEXgUS9	$ )ae
  
Multidimensional grayscale opening.

A grayscale opening consists in the succession of a grayscale erosion,
and a grayscale dilation.

Parameters
----------
input : array_like
    Array over which the grayscale opening is to be computed.
size : tuple of ints
    Shape of a flat and full structuring element used for the grayscale
    opening. Optional if `footprint` or `structure` is provided.
footprint : array of ints, optional
    Positions of non-infinite elements of a flat structuring element
    used for the grayscale opening.
structure : array of ints, optional
    Structuring element used for the grayscale opening. `structure`
    may be a non-flat structuring element. The `structure` array applies
    offsets to the pixels in a neighborhood (the offset is additive during
    dilation and subtractive during erosion).
output : array, optional
    An array used for storing the output of the opening may be provided.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
    The `mode` parameter determines how the array borders are
    handled, where `cval` is the value when mode is equal to
    'constant'. Default is 'reflect'
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'. Default
    is 0.0.
origin : scalar, optional
    The `origin` parameter controls the placement of the filter.
    Default 0
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
-------
grey_opening : ndarray
    Result of the grayscale opening of `input` with `structure`.

See Also
--------
binary_opening, grey_dilation, grey_erosion, grey_closing
generate_binary_structure

Notes
-----
The action of a grayscale opening with a flat structuring element amounts
to smoothen high local maxima, whereas binary opening erases small objects.

References
----------
.. [1] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.arange(36).reshape((6,6))
>>> a[3, 3] = 50
>>> a
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 50, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35]])
>>> ndimage.grey_opening(a, size=(3,3))
array([[ 0,  1,  2,  3,  4,  4],
       [ 6,  7,  8,  9, 10, 10],
       [12, 13, 14, 15, 16, 16],
       [18, 19, 20, 22, 22, 22],
       [24, 25, 26, 27, 28, 28],
       [24, 25, 26, 27, 28, 28]])
>>> # Note that the local maximum a[3,3] has disappeared

N&ignoring size because footprint is setr   
stacklevelrp   )warningswarnUserWarningr   r   
r`   rW   r   r#   rI   r   r   r$   re   ru   s
             r(   r   r     sS    f 	y4>!a	1
uI$$0CI&D2 2rJ   c                x    Ub  Ub  [         R                  " S[        SS9  [        XX#SUXgUS9	n	[	        XX#XEXgUS9	$ )a`
  
Multidimensional grayscale closing.

A grayscale closing consists in the succession of a grayscale dilation,
and a grayscale erosion.

Parameters
----------
input : array_like
    Array over which the grayscale closing is to be computed.
size : tuple of ints
    Shape of a flat and full structuring element used for the grayscale
    closing. Optional if `footprint` or `structure` is provided.
footprint : array of ints, optional
    Positions of non-infinite elements of a flat structuring element
    used for the grayscale closing.
structure : array of ints, optional
    Structuring element used for the grayscale closing. `structure`
    may be a non-flat structuring element. The `structure` array applies
    offsets to the pixels in a neighborhood (the offset is additive during
    dilation and subtractive during erosion)
output : array, optional
    An array used for storing the output of the closing may be provided.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
    The `mode` parameter determines how the array borders are
    handled, where `cval` is the value when mode is equal to
    'constant'. Default is 'reflect'
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'. Default
    is 0.0.
origin : scalar, optional
    The `origin` parameter controls the placement of the filter.
    Default 0
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
-------
grey_closing : ndarray
    Result of the grayscale closing of `input` with `structure`.

See Also
--------
binary_closing, grey_dilation, grey_erosion, grey_opening,
generate_binary_structure

Notes
-----
The action of a grayscale closing with a flat structuring element amounts
to smoothen deep local minima, whereas binary closing fills small holes.

References
----------
.. [1] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.arange(36).reshape((6,6))
>>> a[3,3] = 0
>>> a
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20,  0, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35]])
>>> ndimage.grey_closing(a, size=(3,3))
array([[ 7,  7,  8,  9, 10, 11],
       [ 7,  7,  8,  9, 10, 11],
       [13, 13, 14, 15, 16, 17],
       [19, 19, 20, 20, 22, 23],
       [25, 25, 26, 27, 28, 29],
       [31, 31, 32, 33, 34, 35]])
>>> # Note that the local minimum a[3,3] has disappeared

Nr   r   r   rp   )r   r   r   r   r   r   s
             r(   r   r     sS    f 	y4>!a	1
Y441C941 1rJ   c                    [        XX#SUXgUS9	n	[        U[        R                  5      (       a$  [	        XX#XEXgUS9	  [        R
                  " XU5      $ U	[	        XX#SXVXxS9	-
  $ )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.

Parameters
----------
input : array_like
    Array over which to compute the morphlogical gradient.
size : tuple of ints
    Shape of a flat and full structuring element used for the mathematical
    morphology operations. Optional if `footprint` or `structure` is
    provided. A larger `size` yields a more blurred gradient.
footprint : array of ints, optional
    Positions of non-infinite elements of a flat structuring element
    used for the morphology operations. Larger footprints
    give a more blurred morphological gradient.
structure : array of ints, optional
    Structuring element used for the morphology operations. `structure` may
    be a non-flat structuring element. The `structure` array applies
    offsets to the pixels in a neighborhood (the offset is additive during
    dilation and subtractive during erosion)
output : array, optional
    An array used for storing the output of the morphological gradient
    may be provided.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
    The `mode` parameter determines how the array borders are
    handled, where `cval` is the value when mode is equal to
    'constant'. Default is 'reflect'
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'. Default
    is 0.0.
origin : scalar, optional
    The `origin` parameter controls the placement of the filter.
    Default 0
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
-------
morphological_gradient : ndarray
    Morphological gradient of `input`.

See Also
--------
grey_dilation, grey_erosion, gaussian_gradient_magnitude

Notes
-----
For a flat structuring element, the morphological gradient
computed at a given point corresponds to the maximal difference
between elements of the input among the elements covered by the
structuring element centered on the point.

References
----------
.. [1] https://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[2:5, 2:5] = 1
>>> ndimage.morphological_gradient(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 0, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> # The morphological gradient is computed as the difference
>>> # between a dilation and an erosion
>>> ndimage.grey_dilation(a, size=(3,3)) -\
...  ndimage.grey_erosion(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 0, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> a = np.zeros((7,7), dtype=int)
>>> a[2:5, 2:5] = 1
>>> a[4,4] = 2; a[2,3] = 3
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 3, 1, 0, 0],
       [0, 0, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 2, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.morphological_gradient(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 1, 3, 3, 3, 1, 0],
       [0, 1, 3, 3, 3, 1, 0],
       [0, 1, 3, 2, 3, 2, 0],
       [0, 1, 1, 2, 2, 2, 0],
       [0, 1, 1, 2, 2, 2, 0],
       [0, 0, 0, 0, 0, 0, 0]])

Nrp   )r   rY   r   rZ   r   subtractr   s
             r(   r   r   ]  ss    \ Y441C&"**%%U)	.{{3//l5	#'VH H 	IrJ   c                   [        XX#SUXgUS9	n	[        U[        R                  5      (       aR  [	        XX#XEXgUS9	  [        R
                  " XU5        [        R                  " X@U5        [        R                  " X@U5      $ [	        XX#SUXgUS9	n
[        R
                  " XU
5        [        R                  " XU
5        [        R                  " XU
5        U
$ )a  
Multidimensional morphological laplace.

Parameters
----------
input : array_like
    Input.
size : tuple of ints
    Shape of a flat and full structuring element used for the mathematical
    morphology operations. Optional if `footprint` or `structure` is
    provided.
footprint : array of ints, optional
    Positions of non-infinite elements of a flat structuring element
    used for the morphology operations.
structure : array of ints, optional
    Structuring element used for the morphology operations. `structure` may
    be a non-flat structuring element. The `structure` array applies
    offsets to the pixels in a neighborhood (the offset is additive during
    dilation and subtractive during erosion)
output : ndarray, optional
    An output array can optionally be provided.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
    The mode parameter determines how the array borders are handled.
    For 'constant' mode, values beyond borders are set to be `cval`.
    Default is 'reflect'.
cval : scalar, optional
    Value to fill past edges of input if mode is 'constant'.
    Default is 0.0
origin : origin, optional
    The origin parameter controls the 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
-------
morphological_laplace : ndarray
    Output

Nrp   )r   rY   r   rZ   r   rE   r   )r`   rW   r   r#   rI   r   r   r$   re   r~   tmp2s              r(   r   r     s    X iD$D2D&"**%%U)	.
tV$
F6*{{6&11EtT t5
t4 
D&
D&rJ   c                   [         R                  " U 5      n Ub  Ub  [        R                  " S[        SS9  [        XX#SUXgUS9	n	[        XX#XEXgUS9	n	U	c  Un	U R                  [         R                  :X  a5  U	R                  [         R                  :X  a  [         R                  " X	U	S9  U	$ [         R                  " X	U	S9  U	$ )aq  
Multidimensional white tophat filter.

Parameters
----------
input : array_like
    Input.
size : tuple of ints
    Shape of a flat and full structuring element used for the filter.
    Optional if `footprint` or `structure` is provided.
footprint : array of ints, optional
    Positions of elements of a flat structuring element
    used for the white tophat filter.
structure : array of ints, optional
    Structuring element used for the filter. `structure` may be a non-flat
    structuring element. The `structure` array applies offsets to the
    pixels in a neighborhood (the offset is additive during dilation and
    subtractive during erosion)
output : array, optional
    An array used for storing the output of the filter may be provided.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
    The `mode` parameter determines how the array borders are
    handled, where `cval` is the value when mode is equal to
    'constant'. Default is 'reflect'
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'.
    Default is 0.0.
origin : scalar, optional
    The `origin` parameter controls the placement of the filter.
    Default is 0.
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
-------
output : ndarray
    Result of the filter of `input` with `structure`.

See Also
--------
black_tophat

Examples
--------
Subtract gray background from a bright peak.

>>> from scipy.ndimage import generate_binary_structure, white_tophat
>>> import numpy as np
>>> square = generate_binary_structure(rank=2, connectivity=3)
>>> bright_on_gray = np.array([[2, 3, 3, 3, 2],
...                            [3, 4, 5, 4, 3],
...                            [3, 5, 9, 5, 3],
...                            [3, 4, 5, 4, 3],
...                            [2, 3, 3, 3, 2]])
>>> white_tophat(input=bright_on_gray, structure=square)
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 1, 5, 1, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0]])

Nr   r   r   rp   r<   )r   r   r   r   r   r   r   r@   bool_bitwise_xorr   r   s
             r(   r   r     s    F JJuEy4>!a	1
uI$$0C
941C
{{{bhh399#8
us+ J 	EC(JrJ   c                   [         R                  " U 5      n Ub  Ub  [        R                  " S[        SS9  [        XX#SUXgUS9	n	[        XX#XEXgUS9	n	U	c  Un	U R                  [         R                  :X  a5  U	R                  [         R                  :X  a  [         R                  " XU	S9  U	$ [         R                  " XU	S9  U	$ )a  
Multidimensional black tophat filter.

Parameters
----------
input : array_like
    Input.
size : tuple of ints, optional
    Shape of a flat and full structuring element used for the filter.
    Optional if `footprint` or `structure` is provided.
footprint : array of ints, optional
    Positions of non-infinite elements of a flat structuring element
    used for the black tophat filter.
structure : array of ints, optional
    Structuring element used for the filter. `structure` may be a non-flat
    structuring element. The `structure` array applies offsets to the
    pixels in a neighborhood (the offset is additive during dilation and
    subtractive during erosion)
output : array, optional
    An array used for storing the output of the filter may be provided.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
    The `mode` parameter determines how the array borders are
    handled, where `cval` is the value when mode is equal to
    'constant'. Default is 'reflect'
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'. Default
    is 0.0.
origin : scalar, optional
    The `origin` parameter controls the placement of the filter.
    Default 0
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
-------
black_tophat : ndarray
    Result of the filter of `input` with `structure`.

See Also
--------
white_tophat, grey_opening, grey_closing

Examples
--------
Change dark peak to bright peak and subtract background.

>>> from scipy.ndimage import generate_binary_structure, black_tophat
>>> import numpy as np
>>> square = generate_binary_structure(rank=2, connectivity=3)
>>> dark_on_gray = np.array([[7, 6, 6, 6, 7],
...                          [6, 5, 4, 5, 6],
...                          [6, 4, 0, 4, 6],
...                          [6, 5, 4, 5, 6],
...                          [7, 6, 6, 6, 7]])
>>> black_tophat(input=dark_on_gray, structure=square)
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 1, 5, 1, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0]])

Nr   r   r   rp   r   )r   r   r   r   r   r   r   r@   r   r   r   r   s
             r(   r   r   i  s    D JJuEy4>!a	1
Y441C
s)$0C
{{{bhh399#8
ss+ J 	CC(JrJ   c                    [        U[        R                  5      n[        U[        R                  5      n[        XX45        [        R                  " U 5      S:g  n	[        U	R                  U	R                  5      n
[        X5      n[        R                  " X5      nU	R                  [        R                  5      UR                  [        R                  5      -
  n	UR                  5       nUS:X  a  SnOUS;   a  SnOUS:X  a  SnO[        S5      eUbn  [        R                  " X)R                  5      n[        R                  " U[        R                  S
9nUR                   R"                  (       d  UR%                  5       nU(       a.  [        R&                  " U	R(                  [        R*                  S
9nOS	nU(       a  Ucb  US:X  a.  [        R&                  " U	R(                  [        R                  S
9nO[        R&                  " U	R(                  [        R,                  S
9nOUR(                  U	R(                  :w  a  [        S5      eUS:X  a4  UR.                  R0                  [        R                  :w  a  [        S5      eO3UR.                  R0                  [        R,                  :w  a  [        S5      eUnOS	n[2        R4                  " XX-U5        U(       Ga   [        U[        R                  5      (       ai  UR.                  R0                  [        R*                  :w  a  [        S5      eUR(                  U	R                  4U	R(                  -   :w  a  [        S5      eUnO-[        R6                  " U	R(                  [        R*                  S
9n[        R8                  " U5      n[;        UR(                  S   5       H7  n[        R8                  " XS4   5      U   nU	R(                  Ul        XUS4'   M9     Un/ nU(       a  U(       d  UR=                  U5        U(       a  U(       d  UR=                  U5        [?        U5      S:X  a  [A        U5      $ [?        U5      S:X  a  US   $ g	)a  
Distance transform function by a brute force algorithm.

This function calculates the distance transform of the `input`, by
replacing each foreground (non-zero) element, with its
shortest distance to the background (any zero-valued element).

In addition to the distance transform, the feature transform can
be calculated. In this case the index of the closest background
element to each foreground element is returned in a separate array.

Parameters
----------
input : array_like
    Input
metric : {'euclidean', 'taxicab', 'chessboard'}, optional
    'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
    The default is 'euclidean'.
sampling : float, or sequence of float, optional
    This parameter is only used when `metric` is 'euclidean'.
    Spacing of elements along each dimension. If a sequence, must be of
    length equal to the input rank; if a single number, this is used for
    all axes. If not specified, a grid spacing of unity is implied.
return_distances : bool, optional
    Whether to calculate the distance transform.
    Default is True.
return_indices : bool, optional
    Whether to calculate the feature transform.
    Default is False.
distances : ndarray, optional
    An output array to store the calculated distance transform, instead of
    returning it.
    `return_distances` must be True.
    It must be the same shape as `input`, and of type float64 if `metric`
    is 'euclidean', uint32 otherwise.
indices : int32 ndarray, optional
    An output array to store the calculated feature transform, instead of
    returning it.
    `return_indicies` must be True.
    Its shape must be ``(input.ndim,) + input.shape``.

Returns
-------
distances : ndarray, optional
    The calculated distance transform. Returned only when
    `return_distances` is True and `distances` is not supplied.
    It will have the same shape as the input array.
indices : int32 ndarray, optional
    The calculated feature transform. It has an input-shaped array for each
    dimension of the input. See distance_transform_edt documentation for an
    example.
    Returned only when `return_indices` is True and `indices` is not
    supplied.

See Also
--------
distance_transform_cdt : Faster distance transform for taxicab and
                         chessboard metrics
distance_transform_edt : Faster distance transform for euclidean metric

Notes
-----
This function employs a slow brute force algorithm. See also the
function `distance_transform_cdt` for more efficient taxicab [1]_ and
chessboard algorithms [2]_.

References
----------
.. [1] Taxicab distance. Wikipedia, 2023.
       https://en.wikipedia.org/wiki/Taxicab_geometry
.. [2] Chessboard distance. Wikipedia, 2023.
       https://en.wikipedia.org/wiki/Chebyshev_distance

Examples
--------
Import the necessary modules.

>>> import numpy as np
>>> from scipy.ndimage import distance_transform_bf
>>> import matplotlib.pyplot as plt
>>> from mpl_toolkits.axes_grid1 import ImageGrid

First, we create a toy binary image.

>>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
...     # fill circular area with 1
...     xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
...     circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
...     circle_shape = np.sqrt(circle) < radius
...     image[circle_shape] = fillvalue
...     return image
>>> image = np.zeros((100, 100), dtype=np.uint8)
>>> image[35:65, 20:80] = 1
>>> image = add_circle(28, 65, 10, image)
>>> image = add_circle(37, 30, 10, image)
>>> image = add_circle(70, 45, 20, image)
>>> image = add_circle(45, 80, 10, image)

Next, we set up the figure.

>>> fig = plt.figure(figsize=(8, 8))  # set up the figure structure
>>> grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=(0.4, 0.3),
...                  label_mode="1", share_all=True,
...                  cbar_location="right", cbar_mode="each",
...                  cbar_size="7%", cbar_pad="2%")
>>> for ax in grid:
...     ax.axis('off')  # remove axes from images

The top left image is the original binary image.

>>> binary_image = grid[0].imshow(image, cmap='gray')
>>> cbar_binary_image = grid.cbar_axes[0].colorbar(binary_image)
>>> cbar_binary_image.set_ticks([0, 1])
>>> grid[0].set_title("Binary image: foreground in white")

The distance transform calculates the distance between foreground pixels
and the image background according to a distance metric. Available metrics
in `distance_transform_bf` are: ``euclidean`` (default), ``taxicab``
and ``chessboard``. The top right image contains the distance transform
based on the ``euclidean`` metric.

>>> distance_transform_euclidean = distance_transform_bf(image)
>>> euclidean_transform = grid[1].imshow(distance_transform_euclidean,
...                                      cmap='gray')
>>> cbar_euclidean = grid.cbar_axes[1].colorbar(euclidean_transform)
>>> colorbar_ticks = [0, 10, 20]
>>> cbar_euclidean.set_ticks(colorbar_ticks)
>>> grid[1].set_title("Euclidean distance")

The lower left image contains the distance transform using the ``taxicab``
metric.

>>> distance_transform_taxicab = distance_transform_bf(image,
...                                                    metric='taxicab')
>>> taxicab_transformation = grid[2].imshow(distance_transform_taxicab,
...                                         cmap='gray')
>>> cbar_taxicab = grid.cbar_axes[2].colorbar(taxicab_transformation)
>>> cbar_taxicab.set_ticks(colorbar_ticks)
>>> grid[2].set_title("Taxicab distance")

Finally, the lower right image contains the distance transform using the
``chessboard`` metric.

>>> distance_transform_cb = distance_transform_bf(image,
...                                               metric='chessboard')
>>> chessboard_transformation = grid[3].imshow(distance_transform_cb,
...                                            cmap='gray')
>>> cbar_taxicab = grid.cbar_axes[3].colorbar(chessboard_transformation)
>>> cbar_taxicab.set_ticks(colorbar_ticks)
>>> grid[3].set_title("Chessboard distance")
>>> plt.show()

r   	euclideanr   taxicab	cityblock	manhattanr   
chessboardrA   zdistance metric not supportedNr?   distances array has wrong shapedistances array must be float64zdistances array must be uint32indices array must be int32indices array has wrong shape.)!rY   r   rZ   _distance_tranform_arg_checkr   r   r9   r
   logical_xorastyper]   lowerrT   r   r8   float64rU   rV   r4   r7   r!   int32uint32r@   typer   r   rD   ravelr5   appendr6   r   )r`   metricsamplingreturn_distancesreturn_indices	distancesrD   
ft_inplace
dt_inplacer~   structr   ftdtr/   rtmpr   s                    r(   r   r     s3   x GRZZ0JIrzz2J  0 ::e!D&tyy$))<F4(D>>$%D;;rww$++bgg"66D\\^F	8	8	<	:;;228YYG::hbjj9~~((}}HXXdjj1{XXdjj

;XXdjj		:$**,"#DEE{??''2::5&'HII 6 ??''2994&'GHHB##D(Cgrzz**}}!!RXX-"#@AA}}tzz 99"#BCCD::djj9DXXb\

1&B88DSM*2.DDJ SM '  F
bjb
6{aV}	V	ayrJ   c                 	   [        U[        R                  5      n[        U[        R                  5      n[        XvX#5        [        R                  " U 5      n [        U[
        5      (       aH  US;   a  U R                  n[        US5      nOdUS:X  a  U R                  n[        X5      nOF[        S5      e [        R                  " U5      nUR                   H  n
U
S:w  d  M  [        S5      e   UR                  R                  (       d  UR                  5       nU(       a  UR                  R                  [        R                   :w  a  [        S5      eUR                  U R                  :w  a  [        S	5      eUn[        R"                  " U S
S5      R%                  [        R                   5      US'   O5[        R"                  " U S
S5      R%                  [        R                   5      nUR                  nU(       a?  [        R&                  " UR(                  [        R                   S9nUR                  Ul
        OSn[*        R,                  " XU5        U[/        [1        SSS
5      /U-  5         nU(       a  U[/        [1        SSS
5      /U-  5         n[*        R,                  " XU5        U[/        [1        SSS
5      /U-  5         nU(       Ga%  U[/        [1        SSS
5      /U-  5         n[        R2                  " U5      nU(       ai  UR                  R                  [        R                   :w  a  [        S5      eUR                  UR                  4UR                  -   :w  a  [        S5      eUnO-[        R4                  " UR                  [        R                   S9n[7        UR                  S   5       H7  n[        R2                  " XS4   5      U   nUR                  Ul
        XUS4'   M9     Un/ nU(       a  U(       d  UR9                  U5        U(       a  U(       d  UR9                  U5        [;        U5      S:X  a  [/        U5      $ [;        U5      S:X  a  US   $ g! [         a  n	[        S5      U	eSn	A	ff = f)a  
Distance transform for chamfer type of transforms.

This function calculates the distance transform of the `input`, by
replacing each foreground (non-zero) element, with its
shortest distance to the background (any zero-valued element).

In addition to the distance transform, the feature transform can
be calculated. In this case the index of the closest background
element to each foreground element is returned in a separate array.

Parameters
----------
input : array_like
    Input. Values of 0 are treated as background.
metric : {'chessboard', 'taxicab'} or array_like, optional
    The `metric` determines the type of chamfering that is done. If the
    `metric` is equal to 'taxicab' a structure is generated using
    `generate_binary_structure` with a squared distance equal to 1. If
    the `metric` is equal to 'chessboard', a `metric` is generated
    using `generate_binary_structure` with a squared distance equal to
    the dimensionality of the array. These choices correspond to the
    common interpretations of the 'taxicab' and the 'chessboard'
    distance metrics in two dimensions.
    A custom metric may be provided, in the form of a matrix where
    each dimension has a length of three.
    'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
    The default is 'chessboard'.
return_distances : bool, optional
    Whether to calculate the distance transform.
    Default is True.
return_indices : bool, optional
    Whether to calculate the feature transform.
    Default is False.
distances : int32 ndarray, optional
    An output array to store the calculated distance transform, instead of
    returning it.
    `return_distances` must be True.
    It must be the same shape as `input`.
indices : int32 ndarray, optional
    An output array to store the calculated feature transform, instead of
    returning it.
    `return_indicies` must be True.
    Its shape must be ``(input.ndim,) + input.shape``.

Returns
-------
distances : int32 ndarray, optional
    The calculated distance transform. Returned only when
    `return_distances` is True, and `distances` is not supplied.
    It will have the same shape as the input array.
indices : int32 ndarray, optional
    The calculated feature transform. It has an input-shaped array for each
    dimension of the input. See distance_transform_edt documentation for an
    example.
    Returned only when `return_indices` is True, and `indices` is not
    supplied.

See Also
--------
distance_transform_edt : Fast distance transform for euclidean metric
distance_transform_bf : Distance transform for different metrics using
                        a slower brute force algorithm

Examples
--------
Import the necessary modules.

>>> import numpy as np
>>> from scipy.ndimage import distance_transform_cdt
>>> import matplotlib.pyplot as plt
>>> from mpl_toolkits.axes_grid1 import ImageGrid

First, we create a toy binary image.

>>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
...     # fill circular area with 1
...     xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
...     circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
...     circle_shape = np.sqrt(circle) < radius
...     image[circle_shape] = fillvalue
...     return image
>>> image = np.zeros((100, 100), dtype=np.uint8)
>>> image[35:65, 20:80] = 1
>>> image = add_circle(28, 65, 10, image)
>>> image = add_circle(37, 30, 10, image)
>>> image = add_circle(70, 45, 20, image)
>>> image = add_circle(45, 80, 10, image)

Next, we set up the figure.

>>> fig = plt.figure(figsize=(5, 15))
>>> grid = ImageGrid(fig, 111, nrows_ncols=(3, 1), axes_pad=(0.5, 0.3),
...                  label_mode="1", share_all=True,
...                  cbar_location="right", cbar_mode="each",
...                  cbar_size="7%", cbar_pad="2%")
>>> for ax in grid:
...     ax.axis('off')
>>> top, middle, bottom = grid
>>> colorbar_ticks = [0, 10, 20]

The top image contains the original binary image.

>>> binary_image = top.imshow(image, cmap='gray')
>>> cbar_binary_image = top.cax.colorbar(binary_image)
>>> cbar_binary_image.set_ticks([0, 1])
>>> top.set_title("Binary image: foreground in white")

The middle image contains the distance transform using the ``taxicab``
metric.

>>> distance_taxicab = distance_transform_cdt(image, metric="taxicab")
>>> taxicab_transform = middle.imshow(distance_taxicab, cmap='gray')
>>> cbar_taxicab = middle.cax.colorbar(taxicab_transform)
>>> cbar_taxicab.set_ticks(colorbar_ticks)
>>> middle.set_title("Taxicab metric")

The bottom image contains the distance transform using the ``chessboard``
metric.

>>> distance_chessboard = distance_transform_cdt(image,
...                                              metric="chessboard")
>>> chessboard_transform = bottom.imshow(distance_chessboard, cmap='gray')
>>> cbar_chessboard = bottom.cax.colorbar(chessboard_transform)
>>> cbar_chessboard.set_ticks(colorbar_ticks)
>>> bottom.set_title("Chessboard metric")
>>> plt.tight_layout()
>>> plt.show()

r   r   r   zinvalid metric providedNrA   zmetric sizes must be equal to 3zdistances must be of int32 typezdistances has wrong shaperM   r   .r?   r   r   r   )rY   r   rZ   r   r   strr9   r   r   	Exceptionr!   rU   rV   r4   r@   r   r   wherer   arangerW   r   distance_transform_opr   r-   r   rD   r5   r   r6   )r`   r   r   r   r   rD   r   r   rG   rf   sr   r   ru   r/   r   r   s                    r(   r   r     s   H GRZZ0JIrzz2J  0 JJuE&#::::D.tQ7F|#::D.t:F677	?ZZ'F AAv !BCC  <<""??288+>????ekk)899((5"a(//93XXeR#**288477DYYrwwbhh/88##F3	E5tR()D01	2BuT4,-456##F3	E5tR()D01	2BuT4,-456XXb\}}!!RXX- !>??}}
RXX 55 !@AAC**RXXRXX6C		!%B88CCL)"-DDJCL &  F
bjb
6{aV}	V	ayy  	?67Q>	?s   5Q% %
R /Q;;R c                    [        U[        R                  5      n[        U[        R                  5      n[        XvX#5        [        R                  " [        R
                  " U SS5      R                  [        R                  5      5      n Ubn  [        R                  " XR                  5      n[        R                  " U[        R                  S9nUR                  R                  (       d  UR                  5       nU(       ai  UnUR                   U R                  4U R                   -   :w  a  [#        S5      eUR$                  R&                  [        R(                  :w  a  [#        S5      eO;[        R*                  " U R                  4U R                   -   [        R(                  S9n[,        R.                  " XU5        U(       GaX  U[        R0                  " U R                   UR$                  S9-
  n	U	R                  [        R                  5      n	Ub+  [3        [5        U5      5       H  n
XS4==   X   -  ss'   M     [        R6                  " XU	5        U(       a  [        R8                  R;                  U	SS9n	UR                   U	R                   :w  a  [#        S	5      eUR$                  R&                  [        R                  :w  a  [#        S
5      e[        R<                  " X5        O4[        R8                  R;                  U	SS9n	[        R<                  " U	5      n	/ nU(       a  U(       d  UR?                  W	5        U(       a  U(       d  UR?                  U5        [5        U5      S:X  a  [A        U5      $ [5        U5      S:X  a  US   $ g)a  
Exact Euclidean distance transform.

This function calculates the distance transform of the `input`, by
replacing each foreground (non-zero) element, with its
shortest distance to the background (any zero-valued element).

In addition to the distance transform, the feature transform can
be calculated. In this case the index of the closest background
element to each foreground element is returned in a separate array.

Parameters
----------
input : array_like
    Input data to transform. Can be any type but will be converted
    into binary: 1 wherever input equates to True, 0 elsewhere.
sampling : float, or sequence of float, optional
    Spacing of elements along each dimension. If a sequence, must be of
    length equal to the input rank; if a single number, this is used for
    all axes. If not specified, a grid spacing of unity is implied.
return_distances : bool, optional
    Whether to calculate the distance transform.
    Default is True.
return_indices : bool, optional
    Whether to calculate the feature transform.
    Default is False.
distances : float64 ndarray, optional
    An output array to store the calculated distance transform, instead of
    returning it.
    `return_distances` must be True.
    It must be the same shape as `input`.
indices : int32 ndarray, optional
    An output array to store the calculated feature transform, instead of
    returning it.
    `return_indicies` must be True.
    Its shape must be ``(input.ndim,) + input.shape``.

Returns
-------
distances : float64 ndarray, optional
    The calculated distance transform. Returned only when
    `return_distances` is True and `distances` is not supplied.
    It will have the same shape as the input array.
indices : int32 ndarray, optional
    The calculated feature transform. It has an input-shaped array for each
    dimension of the input. See example below.
    Returned only when `return_indices` is True and `indices` is not
    supplied.

Notes
-----
The Euclidean distance transform gives values of the Euclidean
distance::

                n
  y_i = sqrt(sum (x[i]-b[i])**2)
                i

where b[i] is the background point (value 0) with the smallest
Euclidean distance to input points x[i], and n is the
number of dimensions.

Examples
--------
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.array(([0,1,1,1,1],
...               [0,0,1,1,1],
...               [0,1,1,1,1],
...               [0,1,1,1,0],
...               [0,1,1,0,0]))
>>> ndimage.distance_transform_edt(a)
array([[ 0.    ,  1.    ,  1.4142,  2.2361,  3.    ],
       [ 0.    ,  0.    ,  1.    ,  2.    ,  2.    ],
       [ 0.    ,  1.    ,  1.4142,  1.4142,  1.    ],
       [ 0.    ,  1.    ,  1.4142,  1.    ,  0.    ],
       [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])

With a sampling of 2 units along x, 1 along y:

>>> ndimage.distance_transform_edt(a, sampling=[2,1])
array([[ 0.    ,  1.    ,  2.    ,  2.8284,  3.6056],
       [ 0.    ,  0.    ,  1.    ,  2.    ,  3.    ],
       [ 0.    ,  1.    ,  2.    ,  2.2361,  2.    ],
       [ 0.    ,  1.    ,  2.    ,  1.    ,  0.    ],
       [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])

Asking for indices as well:

>>> edt, inds = ndimage.distance_transform_edt(a, return_indices=True)
>>> inds
array([[[0, 0, 1, 1, 3],
        [1, 1, 1, 1, 3],
        [2, 2, 1, 3, 3],
        [3, 3, 4, 4, 3],
        [4, 4, 4, 4, 4]],
       [[0, 0, 1, 1, 4],
        [0, 1, 1, 1, 4],
        [0, 0, 1, 4, 4],
        [0, 0, 3, 3, 4],
        [0, 0, 3, 3, 4]]], dtype=int32)

With arrays provided for inplace outputs:

>>> indices = np.zeros(((np.ndim(a),) + a.shape), dtype=np.int32)
>>> ndimage.distance_transform_edt(a, return_indices=True, indices=indices)
array([[ 0.    ,  1.    ,  1.4142,  2.2361,  3.    ],
       [ 0.    ,  0.    ,  1.    ,  2.    ,  2.    ],
       [ 0.    ,  1.    ,  1.4142,  1.4142,  1.    ],
       [ 0.    ,  1.    ,  1.4142,  1.    ,  0.    ],
       [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])
>>> indices
array([[[0, 0, 1, 1, 3],
        [1, 1, 1, 1, 3],
        [2, 2, 1, 3, 3],
        [3, 3, 4, 4, 3],
        [4, 4, 4, 4, 4]],
       [[0, 0, 1, 1, 4],
        [0, 1, 1, 1, 4],
        [0, 0, 1, 4, 4],
        [0, 0, 3, 3, 4],
        [0, 0, 3, 3, 4]]], dtype=int32)

r   r   Nr?   r   r   .)axisr   r   r   )!rY   r   rZ   r   
atleast_1dr   r   r]   r   r8   r9   r   r   rU   rV   r4   r!   rT   r@   r   r   r7   r   euclidean_feature_transformrD   r5   r6   multiplyrE   rF   sqrtr   r   )r`   r   r   r   r   rD   r   r   r   r   r/   r   s               r(   r   r   	  sw   | GRZZ0JIrzz2J  0
 MM"((5!Q/66rww?@E228ZZH::hbjj9~~((}}H88

}u{{22>??88==BHH$<== % XXuzzmekk1B))%2>"**U[[99YYrzz"CM*s7x|+ +
BBr*B"((*"#DEE##rzz1"#DEEGGB"r*BB F
bjb
6{aV}	V	ayrJ   c                    / nU(       d  U(       d  UR                  S5        U (       a  U(       d  UR                  S5        U(       a  U(       d  UR                  S5        U(       a  [        SR                  U5      5      eg)z1Raise a RuntimeError if the arguments are invalidz<at least one of return_distances/return_indices must be Truez6return_distances must be True if distances is suppliedz2return_indices must be True if indices is suppliedz, N)r   rT   join)distances_outindices_outr   r   
error_msgss        r(   r   r   7
  si     J~J	L-D	
 >NO499Z011 rJ   r,   )Nr   NNr   r   F)Nr   Nr   Nr   F)NNNr   N)NNNr   r   )NNr   )NNNNreflectg        r   )r   NTFNN)r   TFNN)NTFNN) r   rN   numpyr    r   r   r   __all__r)   r   r   ro   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    rJ   r(   <module>r      s  >      %!BJY"xRj KO9>cOHLcOL ?C89 %HO/3HOV @DDIIID @DDIVHVHr ;?7;s,EIs,l 48;<E<FJE<PXXv >B?@s2s2l ?C@AZ2Z2z >B?@Y2Y2x >B?@Y1Y1x HLIJvI $vIr GKHI:#:z >B?@SSl KO23R=ARj ?C@E26iX IMIMRj CGIMup2rJ   