U
    ?hZ                     @   s   d Z ddlZddlZddlmZ ddlmZ ddl	m
Z
mZ ddlmZ d	d
ddddgZdd Zdd Zdd Zdd Zed dd	Zed!dd
Zeed"ddZeed#ddZdd Zed$ddZed%ddZdS )&z$
Grayscale morphological operations
    N)ndimage   )crop   )_footprint_is_sequence_shape_from_sequence)default_footprinterosiondilationopeningclosingwhite_tophatblack_tophatc                 C   sv   |d \}}| |||d t d|D ]}| | ||d q$|dd D ](\}}t |D ]}| | ||d qXqH|S )zHelper to call `binary_func` for each footprint in a sequence.

    binary_func is a binary morphology function that accepts "structure",
    "output" and "iterations" keyword arguments
    (e.g. `scipy.ndimage.binary_erosion`).
    r   	footprintoutputr   N)rangecopy)Z	gray_funcimage
footprintsoutfpZnum_iter_ r   I/var/www/html/venv/lib/python3.8/site-packages/skimage/morphology/gray.py_iterate_gray_func   s    r   c                 C   s   | j dkr| S | j\}}|d dkr`td|f| j}|rJt| |f} nt|| f} |d7 }|d dkrt|df| j}|rt| |f} nt|| f} | S )a  Shift the binary image `footprint` in the left and/or up.

    This only affects 2D footprints with even number of rows
    or columns.

    Parameters
    ----------
    footprint : 2D array, shape (M, N)
        The input footprint.
    shift_x, shift_y : bool
        Whether to move `footprint` along each axis.

    Returns
    -------
    out : 2D array, shape (M + int(shift_x), N + int(shift_y))
        The shifted footprint.
    r   r   r   )ndimshapenpZzerosdtypeZvstackZhstack)r   shift_xshift_ymnZ	extra_rowZ	extra_colr   r   r   _shift_footprint#   s    

r$   c                 C   s   | t dddf| j  }|S )a  Change the order of the values in `footprint`.

    This is a patch for the *weird* footprint inversion in
    `ndi.grey_morphology` [1]_.

    Parameters
    ----------
    footprint : array
        The input footprint.

    Returns
    -------
    inverted : array, same shape and type as `footprint`
        The footprint, in opposite order.

    Examples
    --------
    >>> footprint = np.array([[0, 0, 0], [0, 1, 1], [0, 1, 1]], np.uint8)
    >>> _invert_footprint(footprint)
    array([[1, 1, 0],
           [1, 1, 0],
           [0, 0, 0]], dtype=uint8)

    References
    ----------
    .. [1] https://github.com/scipy/scipy/blob/ec20ababa400e39ac3ffc9148c01ef86d5349332/scipy/ndimage/morphology.py#L1285  # noqa
    N)slicer   )r   invertedr   r   r   _invert_footprintI   s    r(   c                    s   t  d fdd	}|S )a  Pad input images for certain morphological operations.

    Parameters
    ----------
    func : callable
        A morphological function, either opening or closing, that
        supports eccentric footprints. Its parameters must
        include at least `image`, `footprint`, and `out`.

    Returns
    -------
    func_out : callable
        The same function, but correctly padding the input image before
        applying the input function.

    See Also
    --------
    opening, closing.
    Nc                    s   g }d}|d krt | }t|r,t|}n|j}|D ]2}|d dkrT|d }	d}nd}	||	fd  q6|rt j| |dd} t | }
n|}
 | |f|d|
i|}
|rt|
||d d < n|
}|S )	NFr   r   r   Tedge)moder   )r   
empty_liker   r   r   appendpadr   )r   r   r   argskwargs
pad_widthspaddingZfootprint_shapeZaxis_lenZaxis_pad_widthZout_tempfuncr   r   func_out}   s,    

z.pad_for_eccentric_footprints.<locals>.func_out)N)	functoolswraps)r3   r4   r   r2   r   pad_for_eccentric_footprintsi   s    r7   Fc                    sl   |dkrt | }t|rBt fdd|D }ttj| ||S t |}t| }tj| ||d |S )a	  Return grayscale morphological erosion of an image.

    Morphological erosion sets a pixel at (i,j) to the minimum over all pixels
    in the neighborhood centered at (i,j). Erosion shrinks bright regions and
    enlarges dark regions.

    Parameters
    ----------
    image : ndarray
        Image array.
    footprint : ndarray or tuple, optional
        The neighborhood expressed as a 2-D array of 1's and 0's.
        If None, use a cross-shaped footprint (connectivity=1). The footprint
        can also be provided as a sequence of smaller footprints as described
        in the notes below.
    out : ndarrays, optional
        The array to store the result of the morphology. If None is
        passed, a new array will be allocated.
    shift_x, shift_y : bool, optional
        shift footprint about center point. This only affects
        eccentric footprints (i.e. footprint with even numbered
        sides).

    Returns
    -------
    eroded : array, same shape as `image`
        The result of the morphological erosion.

    Notes
    -----
    For ``uint8`` (and ``uint16`` up to a certain bit-depth) data, the
    lower algorithm complexity makes the `skimage.filters.rank.minimum`
    function more efficient for larger images and footprints.

    The footprint can also be a provided as a sequence of 2-tuples where the
    first element of each 2-tuple is a footprint ndarray and the second element
    is an integer describing the number of times it should be iterated. For
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
    computational cost. Most of the builtin footprints such as
    ``skimage.morphology.disk`` provide an option to automatically generate a
    footprint sequence of this type.

    Examples
    --------
    >>> # Erosion shrinks bright regions
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> bright_square = np.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]], dtype=np.uint8)
    >>> erosion(bright_square, square(3))
    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]], dtype=uint8)

    Nc                 3   s"   | ]\}}t | |fV  qd S N)r$   .0r   r#   r    r!   r   r   	<genexpr>   s   zerosion.<locals>.<genexpr>r   )	r   r+   r   tupler   ndigrey_erosionarrayr$   r   r   r   r    r!   r   r   r;   r   r	      s    @

c                    st   |dkrt | }t|rBt fdd|D }ttj| ||S t |}t| }t	|}tj| ||d |S )a>
  Return grayscale morphological dilation of an image.

    Morphological dilation sets the value of a pixel to the maximum over all
    pixel values within a local neighborhood centered about it. The values
    where the footprint is 1 define this neighborhood.
    Dilation enlarges bright regions and shrinks dark regions.

    Parameters
    ----------
    image : ndarray
        Image array.
    footprint : ndarray or tuple, optional
        The neighborhood expressed as a 2-D array of 1's and 0's.
        If None, use a cross-shaped footprint (connectivity=1). The footprint
        can also be provided as a sequence of smaller footprints as described
        in the notes below.
    out : ndarray, optional
        The array to store the result of the morphology. If None is
        passed, a new array will be allocated.
    shift_x, shift_y : bool, optional
        Shift footprint about center point. This only affects 2D
        eccentric footprints (i.e., footprints with even-numbered
        sides).

    Returns
    -------
    dilated : uint8 array, same shape and type as `image`
        The result of the morphological dilation.

    Notes
    -----
    For `uint8` (and `uint16` up to a certain bit-depth) data, the lower
    algorithm complexity makes the `skimage.filters.rank.maximum` function more
    efficient for larger images and footprints.

    The footprint can also be a provided as a sequence of 2-tuples where the
    first element of each 2-tuple is a footprint ndarray and the second element
    is an integer describing the number of times it should be iterated. For
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
    computational cost. Most of the builtin footprints such as
    ``skimage.morphology.disk`` provide an option to automatically generate a
    footprint sequence of this type.

    Examples
    --------
    >>> # Dilation enlarges bright regions
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> bright_pixel = np.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]], dtype=np.uint8)
    >>> dilation(bright_pixel, square(3))
    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]], dtype=uint8)

    Nc                 3   s&   | ]\}}t t| |fV  qd S r8   )r(   r$   r9   r;   r   r   r<   2  s   zdilation.<locals>.<genexpr>r   )
r   r+   r   r=   r   r>   grey_dilationr@   r$   r(   rA   r   r;   r   r
      s    A

c                 C   s    t | |}t|||ddd}|S )a  Return grayscale morphological opening of an image.

    The morphological opening of an image is defined as an erosion followed by
    a dilation. Opening can remove small bright spots (i.e. "salt") and connect
    small dark cracks. This tends to "open" up (dark) gaps between (bright)
    features.

    Parameters
    ----------
    image : ndarray
        Image array.
    footprint : ndarray or tuple, optional
        The neighborhood expressed as a 2-D array of 1's and 0's.
        If None, use a cross-shaped footprint (connectivity=1). The footprint
        can also be provided as a sequence of smaller footprints as described
        in the notes below.
    out : ndarray, optional
        The array to store the result of the morphology. If None
        is passed, a new array will be allocated.

    Returns
    -------
    opening : array, same shape and type as `image`
        The result of the morphological opening.

    Notes
    -----
    The footprint can also be a provided as a sequence of 2-tuples where the
    first element of each 2-tuple is a footprint ndarray and the second element
    is an integer describing the number of times it should be iterated. For
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
    computational cost. Most of the builtin footprints such as
    ``skimage.morphology.disk`` provide an option to automatically generate a
    footprint sequence of this type.

    Examples
    --------
    >>> # Open up gap between two bright regions (but also shrink regions)
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> bad_connection = np.array([[1, 0, 0, 0, 1],
    ...                            [1, 1, 0, 1, 1],
    ...                            [1, 1, 1, 1, 1],
    ...                            [1, 1, 0, 1, 1],
    ...                            [1, 0, 0, 0, 1]], dtype=np.uint8)
    >>> opening(bad_connection, square(3))
    array([[0, 0, 0, 0, 0],
           [1, 1, 0, 1, 1],
           [1, 1, 0, 1, 1],
           [1, 1, 0, 1, 1],
           [0, 0, 0, 0, 0]], dtype=uint8)

    Tr   r    r!   )r	   r
   )r   r   r   Zerodedr   r   r   r   E  s    :
c                 C   s    t | |}t|||ddd}|S )a  Return grayscale morphological closing of an image.

    The morphological closing of an image is defined as a dilation followed by
    an erosion. Closing can remove small dark spots (i.e. "pepper") and connect
    small bright cracks. This tends to "close" up (dark) gaps between (bright)
    features.

    Parameters
    ----------
    image : ndarray
        Image array.
    footprint : ndarray or tuple, optional
        The neighborhood expressed as a 2-D array of 1's and 0's.
        If None, use a cross-shaped footprint (connectivity=1). The footprint
        can also be provided as a sequence of smaller footprints as described
        in the notes below.
    out : ndarray, optional
        The array to store the result of the morphology. If None,
        a new array will be allocated.

    Returns
    -------
    closing : array, same shape and type as `image`
        The result of the morphological closing.

    Notes
    -----
    The footprint can also be a provided as a sequence of 2-tuples where the
    first element of each 2-tuple is a footprint ndarray and the second element
    is an integer describing the number of times it should be iterated. For
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
    computational cost. Most of the builtin footprints such as
    ``skimage.morphology.disk`` provide an option to automatically generate a
    footprint sequence of this type.

    Examples
    --------
    >>> # Close a gap between two bright lines
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> broken_line = np.array([[0, 0, 0, 0, 0],
    ...                         [0, 0, 0, 0, 0],
    ...                         [1, 1, 0, 1, 1],
    ...                         [0, 0, 0, 0, 0],
    ...                         [0, 0, 0, 0, 0]], dtype=np.uint8)
    >>> closing(broken_line, square(3))
    array([[0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [1, 1, 1, 1, 1],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0]], dtype=uint8)

    TrC   )r
   r	   )r   r   r   Zdilatedr   r   r   r     s    :
c                 C   sn   t tj| ||}t tj| ||}|dkr0|}| jtjkrZ|jtjkrZtj| ||d ntj	| ||d |S )zReturn white top hat for a sequence of footprints.

    Like SciPy's implementation, but with ``ndi.grey_erosion`` and
    ``ndi.grey_dilation`` wrapped with ``_iterate_gray_func``.
    Nr   )
r   r>   r?   rB   r   r   r   bool_Zbitwise_xorsubtract)r   r   r   tmpr   r   r   _white_tophat_seqence  s    rH   c                 C   s   || kr>t | |}t|jtr2tj|||d n||8 }|S |dkrPt| }t| tjrv| jtkrv| j	tj
d}n| }t|tjr|jtkr|j	tj
d}n|}t|rt|||S t|}tj|||d}|S )a  Return white top hat of an image.

    The white top hat of an image is defined as the image minus its
    morphological opening. This operation returns the bright spots of the image
    that are smaller than the footprint.

    Parameters
    ----------
    image : ndarray
        Image array.
    footprint : ndarray or tuple, optional
        The neighborhood expressed as a 2-D array of 1's and 0's.
        If None, use a cross-shaped footprint (connectivity=1). The footprint
        can also be provided as a sequence of smaller footprints as described
        in the notes below.
    out : ndarray, optional
        The array to store the result of the morphology. If None
        is passed, a new array will be allocated.

    Returns
    -------
    out : array, same shape and type as `image`
        The result of the morphological white top hat.

    Notes
    -----
    The footprint can also be a provided as a sequence of 2-tuples where the
    first element of each 2-tuple is a footprint ndarray and the second element
    is an integer describing the number of times it should be iterated. For
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
    computational cost. Most of the builtin footprints such as
    ``skimage.morphology.disk`` provide an option to automatically generate a
    footprint sequence of this type.

    See Also
    --------
    black_tophat

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

    Examples
    --------
    >>> # Subtract gray background from bright peak
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> 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]], dtype=np.uint8)
    >>> white_tophat(bright_on_gray, square(3))
    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]], dtype=uint8)

    rD   N)r   r   )r   r   
issubdtyper   boollogical_xorr+   
isinstanceZndarrayviewZuint8r   rH   r@   r>   r   )r   r   r   ZopenedZimage_Zout_r   r   r   r     s&    @


c                 C   sR   || kr|   }n| }t| ||d}t|jtjrFtj|||d n||8 }|S )aS	  Return black top hat of an image.

    The black top hat of an image is defined as its morphological closing minus
    the original image. This operation returns the dark spots of the image that
    are smaller than the footprint. Note that dark spots in the
    original image are bright spots after the black top hat.

    Parameters
    ----------
    image : ndarray
        Image array.
    footprint : ndarray or tuple, optional
        The neighborhood expressed as a 2-D array of 1's and 0's.
        If None, use a cross-shaped footprint (connectivity=1). The footprint
        can also be provided as a sequence of smaller footprints as described
        in the notes below.
    out : ndarray, optional
        The array to store the result of the morphology. If None
        is passed, a new array will be allocated.

    Returns
    -------
    out : array, same shape and type as `image`
        The result of the morphological black top hat.

    Notes
    -----
    The footprint can also be a provided as a sequence of 2-tuples where the
    first element of each 2-tuple is a footprint ndarray and the second element
    is an integer describing the number of times it should be iterated. For
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
    computational cost. Most of the builtin footprints such as
    ``skimage.morphology.disk`` provide an option to automatically generate a
    footprint sequence of this type.

    See Also
    --------
    white_tophat

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

    Examples
    --------
    >>> # Change dark peak to bright peak and subtract background
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> 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]], dtype=np.uint8)
    >>> black_tophat(dark_on_gray, square(3))
    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]], dtype=uint8)

    rD   )r   r   r   rI   r   rE   rK   )r   r   r   originalr   r   r   r   /  s    A
)NNFF)NNFF)NN)NN)NN)NN)__doc__r5   numpyr   Zscipyr   r>   utilr   r   r   r   miscr   __all__r   r$   r(   r7   r	   r
   r   r   rH   r   r   r   r   r   r   <module>   s8   
& 5MX>>X