o
    :ήc">                     @   s   d dl mZ d dlZd dlmZ ddlmZ ddl	m
Z
 ddlmZ dd Zdd	d
Zdd Zdd Zdd Ze
ddddddddejddejejf
ddZdddejfddZdS )    )warnN   )measure)
remove_arg)ensure_spacingc           	      C   sp   t |}| | }t | }t || }t |r t|}nd}t||||d}t||kr6|d| }|S )z8
    Return the highest intensity peak coordinates.
    N)spacingp_normmax_out)npnonzeroargsort	transposeisfiniteintr   len)	imagemask	num_peaksmin_distancer   coordintensitiesidx_maxsortr	    r   ;/tmp/pip-target-vg8gfxp4/lib/python/skimage/feature/peak.py_get_high_intensity_peaks	   s   


r   c                 C   s   |j dks
| j dkr| |kS tj| |dd}| |k}|du r#t|nt|| }|rCd|dd< |durCt|t|}d||< || |kM }|S )zJ
    Return the mask containing all peak candidates above thresholds.
       constant)	footprintmodeNFT)sizendimaximum_filterr
   alllogical_xorbinary_opening)r   r   	thresholdr   	image_maxoutimage_is_trivialisolated_pxr   r   r   _get_peak_mask"   s    r*   c                 C   s^   t |D ](\}}|dkrqd| tdf| td|f < d| tdf| t| df < q| S )z#Set label border values to 0.

    r   N)	enumerateslice)labelborder_widthiwidthr   r   r   _exclude_border;   s   "r1   c                 C   s2   |dur|n|   }|durt|||   }|S )zSReturn the threshold value according to an absolute and a relative
    value.

    N)minmax)r   threshold_absthreshold_relr%   r   r   r   _get_thresholdH   s   r6   c                 C   s   t |tr|r	|ndf| j }|S t |tr&|dk rtd|f| j }|S t |trPt|| jkr6td|D ]}t |tsCtd|dk rKtdq8|}|S td)zIReturn border_width values relative to a min_distance if requested.

    r   z+`exclude_border` cannot be a negative valuezP`exclude_border` should have the same length as the dimensionality of the image.zD`exclude_border`, when expressed as a tuple, must only contain ints.z,`exclude_border` can not be a negative valueze`exclude_border` must be bool, int, or tuple with the same length as the dimensionality of the image.)
isinstanceboolndimr   
ValueErrortupler   	TypeError)r   r   exclude_borderr.   excluder   r   r   _get_excluded_border_widthU   s8   



r?   indicesz0.20)changed_versionr   Tc                 C   s
  |du s	|j dkr|dk rtdtdd t| ||}t| ||}|du r6d| d }tj|f| j td}nt	|}|du rSt
| ||}t||}t| ||||
}nt|jtdd|}t| jtjrmt| jj}nt| jj}g }tt|D ]H\}}|du rq}|| |d k}| |  }||t|< t
||||}t|||	||
}t|D ]\}}|dd|f  |j7  < q|| q}|rt|}ntjd	td}t||krtj| td}d
|t |j!< t| ||||
}|r|S tj| td}d
|t |j!< |S )a#  Find peaks in an image as coordinate list or boolean mask.

    Peaks are the local maxima in a region of `2 * min_distance + 1`
    (i.e. peaks are separated by at least `min_distance`).

    If both `threshold_abs` and `threshold_rel` are provided, the maximum
    of the two is chosen as the minimum intensity threshold of peaks.

    .. versionchanged:: 0.18
        Prior to version 0.18, peaks of the same height within a radius of
        `min_distance` were all returned, but this could cause unexpected
        behaviour. From 0.18 onwards, an arbitrary peak within the region is
        returned. See issue gh-2592.

    Parameters
    ----------
    image : ndarray
        Input image.
    min_distance : int, optional
        The minimal allowed distance separating peaks. To find the
        maximum number of peaks, use `min_distance=1`.
    threshold_abs : float or None, optional
        Minimum intensity of peaks. By default, the absolute threshold is
        the minimum intensity of the image.
    threshold_rel : float or None, optional
        Minimum intensity of peaks, calculated as
        ``max(image) * threshold_rel``.
    exclude_border : int, tuple of ints, or bool, optional
        If positive integer, `exclude_border` excludes peaks from within
        `exclude_border`-pixels of the border of the image.
        If tuple of non-negative ints, the length of the tuple must match the
        input array's dimensionality.  Each element of the tuple will exclude
        peaks from within `exclude_border`-pixels of the border of the image
        along that dimension.
        If True, takes the `min_distance` parameter as value.
        If zero or False, peaks are identified regardless of their distance
        from the border.
    indices : bool, optional
        If True, the output will be an array representing peak
        coordinates. The coordinates are sorted according to peaks
        values (Larger first). If False, the output will be a boolean
        array shaped as `image.shape` with peaks present at True
        elements. ``indices`` is deprecated and will be removed in
        version 0.20. Default behavior will be to always return peak
        coordinates. You can obtain a mask as shown in the example
        below.
    num_peaks : int, optional
        Maximum number of peaks. When the number of peaks exceeds `num_peaks`,
        return `num_peaks` peaks based on highest peak intensity.
    footprint : ndarray of bools, optional
        If provided, `footprint == 1` represents the local region within which
        to search for peaks at every point in `image`.
    labels : ndarray of ints, optional
        If provided, each unique region `labels == value` represents a unique
        region to search for peaks. Zero is reserved for background.
    num_peaks_per_label : int, optional
        Maximum number of peaks for each label.
    p_norm : float
        Which Minkowski p-norm to use. Should be in the range [1, inf].
        A finite large p may cause a ValueError if overflow can occur.
        ``inf`` corresponds to the Chebyshev distance and 2 to the
        Euclidean distance.

    Returns
    -------
    output : ndarray or ndarray of bools

        * If `indices = True`  : (row, column, ...) coordinates of peaks.
        * If `indices = False` : Boolean array shaped like `image`, with peaks
          represented by True values.

    Notes
    -----
    The peak local maximum function returns the coordinates of local peaks
    (maxima) in an image. Internally, a maximum filter is used for finding local
    maxima. This operation dilates the original image. After comparison of the
    dilated and original image, this function returns the coordinates or a mask
    of the peaks where the dilated image equals the original image.

    See also
    --------
    skimage.feature.corner_peaks

    Examples
    --------
    >>> img1 = np.zeros((7, 7))
    >>> img1[3, 4] = 1
    >>> img1[3, 2] = 1.5
    >>> img1
    array([[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
           [0. , 0. , 0. , 0. , 0. , 0. , 0. ],
           [0. , 0. , 0. , 0. , 0. , 0. , 0. ],
           [0. , 0. , 1.5, 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. ]])

    >>> peak_local_max(img1, min_distance=1)
    array([[3, 2],
           [3, 4]])

    >>> peak_local_max(img1, min_distance=2)
    array([[3, 2]])

    >>> img2 = np.zeros((20, 20, 20))
    >>> img2[10, 10, 10] = 1
    >>> img2[15, 15, 15] = 1
    >>> peak_idx = peak_local_max(img2, exclude_border=0)
    >>> peak_idx
    array([[10, 10, 10],
           [15, 15, 15]])

    >>> peak_mask = np.zeros_like(img2, dtype=bool)
    >>> peak_mask[tuple(peak_idx.T)] = True
    >>> np.argwhere(peak_mask)
    array([[10, 10, 10],
           [15, 15, 15]])

    Nr   zmWhen min_distance < 1, peak_local_max acts as finding image > max(threshold_abs, threshold_rel * max(image)).r   )
stackleveldtypesafe)casting)r   r   T)"r   r   RuntimeWarningr?   r6   r
   onesr9   r8   asarrayr*   r1   r   astyper   
issubdtyperD   floatingfinfor2   iinfor+   r    find_objectscopylogical_notstartappendvstackemptyr   
zeros_liker;   T)r   r   r4   r5   r=   r@   r   r   labelsnum_peaks_per_labelr   r.   r%   r   r   coordinates_labelsbg_vallabels_peak_coord	label_idxroi
label_mask
img_objectidxsr'   r   r   r   peak_local_maxw   sr   |

rd   c                 C   s4  |   }|j\}}|du rdt| }d| d }d| d }	tj||dddd}
tj|
|	dddd}
||
k}||9 }||k}t|}t||
}t	|dd	 d
ddd }tj
dd |D td}g }g }g }tj| |d | |d f \}}|D ]e\}}|
||f }||kr|| }|| }t|dk||k }|| }|| }|dk }|||  ||< ||  |7  < ||k}|||  ||< ||  |8  < d|
||f< || || || qt
|}t
|}t
|}|t|k rt|ddd d| }|| }|| }|| }|||fS )a{  Return peaks with non-maximum suppression.

    Identifies most prominent features separated by certain distances.
    Non-maximum suppression with different sizes is applied separately
    in the first and second dimension of the image to identify peaks.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    min_xdistance : int
        Minimum distance separating features in the x dimension.
    min_ydistance : int
        Minimum distance separating features in the y dimension.
    threshold : float
        Minimum intensity of peaks. Default is `0.5 * max(image)`.
    num_peaks : int
        Maximum number of peaks. When the number of peaks exceeds `num_peaks`,
        return `num_peaks` coordinates based on peak intensity.

    Returns
    -------
    intensity, xcoords, ycoords : tuple of array
        Peak intensity values, x and y indices.
    Ng      ?r   r   r   r   )r   axisr   cvalc                 S   s   | j S N)intensity_max)xr   r   r   <lambda>z  s    z"_prominent_peaks.<locals>.<lambda>)keyc                 S   s   g | ]}t |jqS r   )r
   roundcentroid).0pr   r   r   
<listcomp>{  s    z$_prominent_peaks.<locals>.<listcomp>rC   )rP   shaper
   r3   r    maximum_filter1dr   r-   regionpropssortedarrayr   mgridlogical_andrS   r   r   )r   min_xdistancemin_ydistancer%   r   imgrowscolsycoords_sizexcoords_sizeimg_maxr   img_t	label_imgpropscoords	img_peaksycoords_peaksxcoords_peaksycoords_extxcoords_extycoords_idxxcoords_idxaccum
ycoords_nh
xcoords_nh
ycoords_inxcoords_lowxcoords_highr   r   r   r   _prominent_peaksI  sj   











r   rg   )warningsr   numpyr
   scipy.ndimagendimager     r   _shared.utilsr   _shared.coordr   r   r*   r1   r6   r?   infrd   r   r   r   r   r   <module>   s*    

" R