o
    :ήc                     @   s  d dl Z d dlZd dlZd dlmZ d dlmZ d dlZd dl	m
Z ddlmZ ddlmZmZm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lmZ ddlmZmZ g dZ dGddZ!edddHddZ"	 	 dIddZ#dJddZ$dKdd!d"d#Z%dKdd!d$d%Z&dLdd!d&d'Z'e(e)d(d)dZ*e*fd*d+Z+dddd,d-d.Z,ed/d0id1d2d3dMdd!d5d6Z-d7d8 Z.dNd9d:Z/d;d< Z0dOd?d@Z1dPdAdBZ2dCdD Z3dQdd!dEdFZ4dS )R    N)OrderedDict)Iterable)ndimage   )gaussian)_supported_float_typedeprecate_kwargwarn)require)	histogram)_get_multiotsu_thresh_indices!_get_multiotsu_thresh_indices_lut)integral_image)dtype_limits   )_correlate_sparse_validate_window_size)try_all_thresholdthreshold_otsuthreshold_yenthreshold_isodatathreshold_lithreshold_localthreshold_minimumthreshold_meanthreshold_niblackthreshold_sauvolathreshold_triangleapply_hysteresis_thresholdthreshold_multiotsuTc                 C   sz  ddl m} d}t|  |dd}|pi }tt|d | }|j|||ddd\}	}
|
 }
|
d j| |j	j
d	 |
d d
 d}| D ]b\}}t|}d|jv r[t|dni }|
| | z|
| j|| fi ||j	j
d	 W n' ty } z|
| jdddt|j dd|
| jd W Y d}~nd}~ww |d7 }|rt|j qH|
D ]}|d q|	  |	|
fS )a  Returns a figure comparing the outputs of different methods.

    Parameters
    ----------
    image : (N, M) ndarray
        Input image.
    methods : dict, optional
        Names and associated functions.
        Functions must take and return an image.
    figsize : tuple, optional
        Figure size (in inches).
    num_cols : int, optional
        Number of columns.
    verbose : bool, optional
        Print function name for each method.

    Returns
    -------
    fig, ax : tuple
        Matplotlib figure and axes.
    r   )pyplot   imagesource_range      ?T)figsizesharexsharey)cmapOriginalr   histr+         ?z%scenter)hava	transformNoff)
matplotlibr    r   ravelmathceillensubplotsimshowcmgray	set_titleitemsinspect	signature
parametersdict	Exceptiontexttype__name__	transAxesprint__orifunc__axistight_layout)r"   methodsr&   num_colsverbosepltnbinsr+   num_rowsfigaxinamefuncsig_kwargsea rZ   C/tmp/pip-target-vg8gfxp4/lib/python/skimage/filters/thresholding.py_try_all#   s@   


&
r\   r3   z>=3.0.3      c              	   C   sL   dd }t |t|t|t|t|t|t|td}t| |||dS )a  Returns a figure comparing the outputs of different thresholding methods.

    Parameters
    ----------
    image : (N, M) ndarray
        Input image.
    figsize : tuple, optional
        Figure size (in inches).
    verbose : bool, optional
        Print function name for each method.

    Returns
    -------
    fig, ax : tuple
        Matplotlib figure and axes.

    Notes
    -----
    The following algorithms are used:

    * isodata
    * li
    * mean
    * minimum
    * otsu
    * triangle
    * yen

    Examples
    --------
    >>> from skimage.data import text
    >>> fig, ax = try_all_threshold(text(), figsize=(10, 6), verbose=False)
    c                    sB    fdd}z j |_ W |S  ty     jd  j |_ Y |S w )zC
        A wrapper function to return a thresholded image.
        c                    s   |  | kS )NrZ   )imrU   rZ   r[   wrapper   s   z2try_all_threshold.<locals>.thresh.<locals>.wrapper.)rH   AttributeError
__module__rE   )rU   rb   rZ   ra   r[   thresh   s   
z!try_all_threshold.<locals>.thresh)IsodataLiMeanMinimumOtsuTriangleYen)r&   rK   rM   )	r   r   r   r   r   r   r   r   r\   )r"   r&   rM   rf   rK   rZ   rZ   r[   r   a   s   #r      r   reflectc           
      C   s6  t |r|f| j }nt|| jkrtdt|}tdd |D r,td| dt| }| j|dd} t j	| j
|d}|d	krRtj| |||||d
 || S |dkrs|du rdtdd |D }	n|}	t| |	|||d
 || S |dkrtj| ||||d
 || S |dkrtj| ||||d
 || S td)aT
  Compute a threshold mask image based on local pixel neighborhood.

    Also known as adaptive or dynamic thresholding. The threshold value is
    the weighted mean for the local neighborhood of a pixel subtracted by a
    constant. Alternatively the threshold can be determined dynamically by a
    given function, using the 'generic' method.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.
    block_size : int or sequence of int
        Odd size of pixel neighborhood which is used to calculate the
        threshold value (e.g. 3, 5, 7, ..., 21, ...).
    method : {'generic', 'gaussian', 'mean', 'median'}, optional
        Method used to determine adaptive threshold for local neighbourhood in
        weighted mean image.

        * 'generic': use custom function (see ``param`` parameter)
        * 'gaussian': apply gaussian filter (see ``param`` parameter for custom                      sigma value)
        * 'mean': apply arithmetic mean filter
        * 'median': apply median rank filter

        By default the 'gaussian' method is used.
    offset : float, optional
        Constant subtracted from weighted mean of neighborhood to calculate
        the local threshold value. Default offset is 0.
    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'.
    param : {int, function}, optional
        Either specify sigma for 'gaussian' method or function object for
        'generic' method. This functions takes the flat array of local
        neighbourhood as a single argument and returns the calculated
        threshold for the centre pixel.
    cval : float, optional
        Value to fill past edges of input if mode is 'constant'.

    Returns
    -------
    threshold : (N, M[, ..., P]) ndarray
        Threshold image. All pixels in the input image higher than the
        corresponding pixel in the threshold image are considered foreground.

    References
    ----------
    .. [1] Gonzalez, R. C. and Wood, R. E. "Digital Image Processing
           (2nd Edition)." Prentice-Hall Inc., 2002: 600--612.
           ISBN: 0-201-18075-8

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()[:50, :50]
    >>> binary_image1 = image > threshold_local(image, 15, 'mean')
    >>> func = lambda arr: arr.mean()
    >>> binary_image2 = image > threshold_local(image, 15, 'generic',
    ...                                         param=func)

    z&len(block_size) must equal image.ndim.c                 s   s    | ]	}|d  dkV  qdS )r   r   NrZ   .0brZ   rZ   r[   	<genexpr>   s    z"threshold_local.<locals>.<genexpr>z)block_size must be odd! Given block_size z contains even values.Fcopydtypegeneric)outputmodecvalr   Nc                 S   s   g | ]}|d  d qS )r   g      @rZ   rp   rZ   rZ   r[   
<listcomp>   s    z#threshold_local.<locals>.<listcomp>meanmedianzPInvalid method specified. Please use `generic`, `gaussian`, `mean`, or `median`.)npisscalarndimr7   
ValueErrortupleanyr   astypezerosshapendigeneric_filterr   uniform_filtermedian_filter)
r"   
block_sizemethodoffsetrz   paramr{   float_dtypethresh_imagesigmarZ   rZ   r[   r      sD   
A

	r   Fc           	      C   s   | du r|du rt d|durTt|ttfr|\}}n|}t|j}|d dks0|d dkrS|dk}t|}|jt|ddd  }||| ||| }}nt| 	 |d|d\}}|
t|fS )a  Ensure that either image or hist were given, return valid histogram.

    If hist is given, image is ignored.

    Parameters
    ----------
    image : array or None
        Grayscale image.
    hist : array, 2-tuple of array, or None
        Histogram, either a 1D counts array, or an array of counts together
        with an array of bin centers.
    nbins : int, optional
        The number of bins with which to compute the histogram, if `hist` is
        None.
    normalize : bool
        If hist is not given, it will be computed by this function. This
        parameter determines whether the computed histogram is normalized
        (i.e. entries sum up to 1) or not.

    Returns
    -------
    counts : 1D array of float
        Each element is the number of pixels falling in each intensity bin.
    bin_centers : 1D array
        Each element is the value corresponding to the center of each intensity
        bin.

    Raises
    ------
    ValueError : if image and hist are both None
    Nz&Either image or hist must be provided.r   r"   )r$   	normalize)rB   
isinstancer   listr   arangesizeargmaxr   r4   r   float)	r"   r+   rO   r   countsbin_centerscondstartendrZ   rZ   r[   _validate_image_histogram   s"    


r   r!   r,   c                C   s  | dur| j dkr| jd dv rtd| j d | dur,|  d }t| |kr,|S t| ||\}}t|}t|ddd ddd }t|| | }t|| ddd |ddd  ddd }	|dd |dd  |dd |	dd  d  }
t|
}|| }|S )	az  Return threshold value based on Otsu's method.

    Either image or hist must be provided. If hist is provided, the actual
    histogram of the image is ignored.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray, optional
        Grayscale input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.
    hist : array, or 2-tuple of arrays, optional
        Histogram from which to determine the threshold, and optionally a
        corresponding array of bin center intensities. If no hist provided,
        this function will compute it from the image.


    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.

    References
    ----------
    .. [1] Wikipedia, https://en.wikipedia.org/wiki/Otsu's_Method

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_otsu(image)
    >>> binary = image <= thresh

    Notes
    -----
    The input image must be grayscale.
    Nr   r   rn      zTthreshold_otsu is expected to work correctly only for grayscale images; image shape ! looks like that of an RGB image.r   r   )	r   r   r	   r4   r   allr   cumsumr   )r"   rO   r+   first_pixelr   r   weight1weight2mean1mean2
variance12idx	thresholdrZ   rZ   r[   r   8  s"    (

04
r   c          
      C   s   t | ||\}}|jdkr|d S |tj|  }t|}t|d }t|ddd d ddd }t|dd |dd  d |dd d|dd   d  }	||	  S )a<  Return threshold value based on Yen's method.
    Either image or hist must be provided. In case hist is given, the actual
    histogram of the image is ignored.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.
    hist : array, or 2-tuple of arrays, optional
        Histogram from which to determine the threshold, and optionally a
        corresponding array of bin center intensities.
        An alternative use of this function is to pass it only hist.

    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.

    References
    ----------
    .. [1] Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion
           for Automatic Multilevel Thresholding" IEEE Trans. on Image
           Processing, 4(3): 370-378. :DOI:`10.1109/83.366472`
    .. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
           Techniques and Quantitative Performance Evaluation" Journal of
           Electronic Imaging, 13(1): 146-165, :DOI:`10.1117/1.1631315`
           http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
    .. [3] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_yen(image)
    >>> binary = image <= thresh
    r   r   r   Nr   r%   )	r   r   r   r   float32sumr   logr   )
r"   rO   r+   r   r   pmfP1P1_sqP2_sqcritrZ   rZ   r[   r     s   )

"r   c                C   s   t | ||\}}t|dkr|r|S |d S |tj}t|}|d | }|| }t|}	|	dd |dd  }
|	d |	dd  |dd  }|
| d }|d |d  }||dd  }|dd |dk||k @  }|rt|S |d S )a	  Return threshold value(s) based on ISODATA method.

    Histogram-based threshold, known as Ridler-Calvard method or inter-means.
    Threshold values returned satisfy the following equality::

        threshold = (image[image <= threshold].mean() +
                     image[image > threshold].mean()) / 2.0

    That is, returned thresholds are intensities that separate the image into
    two groups of pixels, where the threshold intensity is midway between the
    mean intensities of these groups.

    For integer images, the above equality holds to within one; for floating-
    point images, the equality holds to within the histogram bin-width.

    Either image or hist must be provided. In case hist is given, the actual
    histogram of the image is ignored.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.
    return_all : bool, optional
        If False (default), return only the lowest threshold that satisfies
        the above equality. If True, return all valid thresholds.
    hist : array, or 2-tuple of arrays, optional
        Histogram to determine the threshold from and a corresponding array
        of bin center intensities. Alternatively, only the histogram can be
        passed.

    Returns
    -------
    threshold : float or int or array
        Threshold value(s).

    References
    ----------
    .. [1] Ridler, TW & Calvard, S (1978), "Picture thresholding using an
           iterative selection method"
           IEEE Transactions on Systems, Man and Cybernetics 8: 630-632,
           :DOI:`10.1109/TSMC.1978.4310039`
    .. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
           Techniques and Quantitative Performance Evaluation" Journal of
           Electronic Imaging, 13(1): 146-165,
           http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
           :DOI:`10.1117/1.1631315`
    .. [3] ImageJ AutoThresholder code,
           http://fiji.sc/wiki/index.php/Auto_Threshold

    Examples
    --------
    >>> from skimage.data import coins
    >>> image = coins()
    >>> thresh = threshold_isodata(image)
    >>> binary = image > thresh
    r   r   r   Ng       @)r   r7   r   r   r   r   )r"   rO   
return_allr+   r   r   csumlcsumhintensity_sumcsum_intensitylowerhigherall_mean	bin_width	distances
thresholdsrZ   rZ   r[   r     s&   <

 	r   g      gQo@c                 C   s   t j| |dd\}}t j|ddgdd}t ||kd }t |d| }t ||d }t |d| |d|  }	t ||d ||d  }
|	| }|
| }|	 t | |
t |  }|S )a  Compute cross-entropy between distributions above and below a threshold.

    Parameters
    ----------
    image : array
        The input array of values.
    threshold : float
        The value dividing the foreground and background in ``image``.
    bins : int or array of float, optional
        The number of bins or the bin edges. (Any valid value to the ``bins``
        argument of ``np.histogram`` will work here.) For an exact calculation,
        each unique value should have its own bin. The default value for bins
        ensures exact handling of uint8 images: ``bins=256`` results in
        aliasing problems due to bin width not being equal to 1.

    Returns
    -------
    nu : float
        The cross-entropy target value as defined in [1]_.

    Notes
    -----
    See Li and Lee, 1993 [1]_; this is the objective function ``threshold_li``
    minimizes. This function can be improved but this implementation most
    closely matches equation 8 in [1]_ and equations 1-3 in [2]_.

    References
    ----------
    .. [1] Li C.H. and Lee C.K. (1993) "Minimum Cross Entropy Thresholding"
           Pattern Recognition, 26(4): 617-625
           :DOI:`10.1016/0031-3203(93)90115-D`
    .. [2] Li C.H. and Tam P.K.S. (1998) "An Iterative Algorithm for Minimum
           Cross Entropy Thresholding" Pattern Recognition Letters, 18(8): 771-776
           :DOI:`10.1016/S0167-8655(98)00057-9`
    T)binsdensityr-   validrz   r   N)r   r   convolveflatnonzeror   r   )r"   r   r   r   	bin_edgesr   tm0am0bm1am1bmuamubnurZ   rZ   r[   _cross_entropy8  s   $r   )	toleranceinitial_guessiter_callbackc                C   s  | t |   } | jdkrt jS t | | jd kr| jd S | t |  } | jdkr-dS t | }| |8 } | jj	dv rA|p?d}n|pOt t 
t | d }|du rZt | }n<t|rc|| }n3t |r|| }t | | }d|  k rt | k sn d| d| d	| d
}t|ntdd| }|dur|||  | jj	dv rt| ddd\}	}
|	t}	t|| |kr|}|
|k}| }t j|
| |	| d}t j|
| |	| d}|| t |t |  }|dur|||  t|| |ksn@t|| |krD|}| |k}t | | }t | |  }|| t |t |  }|dur;|||  t|| |ks|| }|S )a.	  Compute threshold value by Li's iterative Minimum Cross Entropy method.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.

    tolerance : float, optional
        Finish the computation when the change in the threshold in an iteration
        is less than this value. By default, this is half the smallest
        difference between intensity values in ``image``.

    initial_guess : float or Callable[[array[float]], float], optional
        Li's iterative method uses gradient descent to find the optimal
        threshold. If the image intensity histogram contains more than two
        modes (peaks), the gradient descent could get stuck in a local optimum.
        An initial guess for the iteration can help the algorithm find the
        globally-optimal threshold. A float value defines a specific start
        point, while a callable should take in an array of image intensities
        and return a float value. Example valid callables include
        ``numpy.mean`` (default), ``lambda arr: numpy.quantile(arr, 0.95)``,
        or even :func:`skimage.filters.threshold_otsu`.

    iter_callback : Callable[[float], Any], optional
        A function that will be called on the threshold at every iteration of
        the algorithm.

    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.

    References
    ----------
    .. [1] Li C.H. and Lee C.K. (1993) "Minimum Cross Entropy Thresholding"
           Pattern Recognition, 26(4): 617-625
           :DOI:`10.1016/0031-3203(93)90115-D`
    .. [2] Li C.H. and Tam P.K.S. (1998) "An Iterative Algorithm for Minimum
           Cross Entropy Thresholding" Pattern Recognition Letters, 18(8): 771-776
           :DOI:`10.1016/S0167-8655(98)00057-9`
    .. [3] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
           Techniques and Quantitative Performance Evaluation" Journal of
           Electronic Imaging, 13(1): 146-165
           :DOI:`10.1117/1.1631315`
    .. [4] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_li(image)
    >>> binary = image > thresh
    r   g        iur-   r   NzNThe initial guess for threshold_li must be within the range of the image. Got z for image min z	 and max rc   zIncorrect type for `initial_guess`; should be a floating point value, or a function mapping an array to a floating point value.r   r"   r#   )weights)r   isnanr   nanr   flatisfiniteminrw   kinddiffuniquer}   callabler   maxr   	TypeErrorr   reshaper   r   absaverager   )r"   r   r   r   	image_mint_next	image_maxmsgt_currr+   r   
foreground
background	mean_fore	mean_backr   rZ   rZ   r[   r   i  s   9












r   max_itermax_num_iterz1.0z0.19)removed_versiondeprecated_version'  c                C   s   dd }t | ||\}}|jtjdd}t|D ]}t|d}||}	t|	dk r, nqt|	dkr7td||d krAtd	t	||	d
 |	d d  }
||	d
 |
  S )a	  Return threshold value based on minimum method.

    The histogram of the input ``image`` is computed if not provided and
    smoothed until there are only two maxima. Then the minimum in between is
    the threshold value.

    Either image or hist must be provided. In case hist is given, the actual
    histogram of the image is ignored.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray, optional
        Grayscale input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.
    max_num_iter : int, optional
        Maximum number of iterations to smooth the histogram.
    hist : array, or 2-tuple of arrays, optional
        Histogram to determine the threshold from and a corresponding array
        of bin center intensities. Alternatively, only the histogram can be
        passed.

    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.

    Raises
    ------
    RuntimeError
        If unable to find two local maxima in the histogram or if the
        smoothing takes more than 1e4 iterations.

    References
    ----------
    .. [1] C. A. Glasbey, "An analysis of histogram-based thresholding
           algorithms," CVGIP: Graphical Models and Image Processing,
           vol. 55, pp. 532-537, 1993.
    .. [2] Prewitt, JMS & Mendelsohn, ML (1966), "The analysis of cell
           images", Annals of the New York Academy of Sciences 128: 1035-1053
           :DOI:`10.1111/j.1749-6632.1965.tb11715.x`

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_minimum(image)
    >>> binary = image > thresh
    c                 S   sj   t  }d}t| jd d D ]$}|dkr&| |d  | | k r%d}|| q| |d  | | kr2d}q|S )Nr   r   r   )r   ranger   append)r+   maximum_idxs	directionrS   rZ   rZ   r[   find_local_maxima_idx5  s   
z0threshold_minimum.<locals>.find_local_maxima_idxFrt   rn   r   z&Unable to find two maxima in histogramr   z0Maximum iteration reached for histogramsmoothingr   )
r   r   r   float64r   r   uniform_filter1dr7   RuntimeErrorargmin)r"   rO   r   r+   r   r   r   smooth_histcounterr   threshold_idxrZ   rZ   r[   r     s   7r   c                 C   s
   t | S )a  Return threshold value based on the mean of grayscale values.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.

    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.

    References
    ----------
    .. [1] C. A. Glasbey, "An analysis of histogram-based thresholding
        algorithms," CVGIP: Graphical Models and Image Processing,
        vol. 55, pp. 532-537, 1993.
        :DOI:`10.1006/cgip.1993.1040`

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_mean(image)
    >>> binary = image > thresh
    )r   r}   r"   rZ   rZ   r[   r   \  s   
r   c                 C   s  t |  |dd\}}t|}t|}|| }t|dkd ddg \}}|| || k }|rD|ddd }|| d }|| d }~|| }	t|	}
||
|  }t|d |	d  }|| }|	| }	||
 |	|  }t|| }|r~|| d }|| S )a  Return threshold value based on the triangle algorithm.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.

    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.

    References
    ----------
    .. [1] Zack, G. W., Rogers, W. E. and Latt, S. A., 1977,
       Automatic Measurement of Sister Chromatid Exchange Frequency,
       Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753
       :DOI:`10.1177/25.7.70454`
    .. [2] ImageJ AutoThresholder code,
       http://fiji.sc/wiki/index.php/Auto_Threshold

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_triangle(image)
    >>> binary = image > thresh
    r"   r#   r   r   Nr   r   )r   r4   r7   r   r   wherer   sqrt)r"   rO   r+   r   arg_peak_heightpeak_heightarg_low_levelarg_high_levelflipwidthx1y1normlength	arg_levelrZ   rZ   r[   r   {  s,   #

r   c                    s.  t |ts|f j }t| t j}tdd |D }tj j	|dd|dd}t
|tjd}||9 }t
|tjd}ttjtdd	 |D  } fd
d	|D }t|}	tdd |D }
t||
||}|j	|dd}||	 }t||
||}|j	|dd}||	 }tt|||  dd}||fS )uH  Return local mean and standard deviation of each pixel using a
    neighborhood defined by a rectangular window size ``w``.
    The algorithm uses integral images to speedup computation. This is
    used by :func:`threshold_niblack` and :func:`threshold_sauvola`.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.
    w : int, or iterable of int
        Window size specified as a single odd integer (3, 5, 7, …),
        or an iterable of length ``image.ndim`` containing only odd
        integers (e.g. ``(1, 5, 5)``).

    Returns
    -------
    m : ndarray of float, same shape as ``image``
        Local mean of the image.
    s : ndarray of float, same shape as ``image``
        Local standard deviation of the image.

    References
    ----------
    .. [1] F. Shafait, D. Keysers, and T. M. Breuel, "Efficient
           implementation of local adaptive thresholding techniques
           using integral images." in Document Recognition and
           Retrieval XV, (San Jose, USA), Jan. 2008.
           :DOI:`10.1117/12.767755`
    c                 s   s$    | ]}|d  d |d  fV  qdS )r   r   NrZ   )rq   krZ   rZ   r[   rs     s   " z_mean_std.<locals>.<genexpr>Frt   ro   r   rv   c                 S   s   g | ]}d |fqS )r   rZ   rq   _wrZ   rZ   r[   r|     s    z_mean_std.<locals>.<listcomp>c                    s(   g | ]}d  j d t|d k qS )r   r   )r   r   r   )rq   indicesr   rZ   r[   r|     s     c                 s   s    | ]}|d  V  qdS )r   NrZ   r  rZ   rZ   r[   rs     s    r   N)r   r   r   r   r   rw   r   r   padr   r   r   r   	itertoolsproductprodr   r  clip)r"   wr   	pad_widthpaddedintegralintegral_sqkernel_indiceskernel_valuestotal_window_sizekernel_shapemg2srZ   r   r[   	_mean_std  s:   



r"     皙?c                 C   s   t | |\}}|||  S )uV  Applies Niblack local threshold to an array.

    A threshold T is calculated for every pixel in the image using the
    following formula::

        T = m(x,y) - k * s(x,y)

    where m(x,y) and s(x,y) are the mean and standard deviation of
    pixel (x,y) neighborhood defined by a rectangular window with size w
    times w centered around the pixel. k is a configurable parameter
    that weights the effect of standard deviation.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.
    window_size : int, or iterable of int, optional
        Window size specified as a single odd integer (3, 5, 7, …),
        or an iterable of length ``image.ndim`` containing only odd
        integers (e.g. ``(1, 5, 5)``).
    k : float, optional
        Value of parameter k in threshold formula.

    Returns
    -------
    threshold : (N, M) ndarray
        Threshold mask. All pixels with an intensity higher than
        this value are assumed to be foreground.

    Notes
    -----
    This algorithm is originally designed for text recognition.

    The Bradley threshold is a particular case of the Niblack
    one, being equivalent to

    >>> from skimage import data
    >>> image = data.page()
    >>> q = 1
    >>> threshold_image = threshold_niblack(image, k=0) * q

    for some value ``q``. By default, Bradley and Roth use ``q=1``.


    References
    ----------
    .. [1] W. Niblack, An introduction to Digital Image Processing,
           Prentice-Hall, 1986.
    .. [2] D. Bradley and G. Roth, "Adaptive thresholding using Integral
           Image", Journal of Graphics Tools 12(2), pp. 13-21, 2007.
           :DOI:`10.1080/2151237X.2007.10129236`

    Examples
    --------
    >>> from skimage import data
    >>> image = data.page()
    >>> threshold_image = threshold_niblack(image, window_size=7, k=0.1)
    )r"  )r"   window_sizer  r  r!  rZ   rZ   r[   r     s   ;r   c                 C   sJ   |du rt | dd\}}d||  }t| |\}}|d||| d    S )u  Applies Sauvola local threshold to an array. Sauvola is a
    modification of Niblack technique.

    In the original method a threshold T is calculated for every pixel
    in the image using the following formula::

        T = m(x,y) * (1 + k * ((s(x,y) / R) - 1))

    where m(x,y) and s(x,y) are the mean and standard deviation of
    pixel (x,y) neighborhood defined by a rectangular window with size w
    times w centered around the pixel. k is a configurable parameter
    that weights the effect of standard deviation.
    R is the maximum standard deviation of a grayscale image.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.
    window_size : int, or iterable of int, optional
        Window size specified as a single odd integer (3, 5, 7, …),
        or an iterable of length ``image.ndim`` containing only odd
        integers (e.g. ``(1, 5, 5)``).
    k : float, optional
        Value of the positive parameter k.
    r : float, optional
        Value of R, the dynamic range of standard deviation.
        If None, set to the half of the image dtype range.

    Returns
    -------
    threshold : (N, M) ndarray
        Threshold mask. All pixels with an intensity higher than
        this value are assumed to be foreground.

    Notes
    -----
    This algorithm is originally designed for text recognition.

    References
    ----------
    .. [1] J. Sauvola and M. Pietikainen, "Adaptive document image
           binarization," Pattern Recognition 33(2),
           pp. 225-236, 2000.
           :DOI:`10.1016/S0031-3203(99)00055-2`

    Examples
    --------
    >>> from skimage import data
    >>> image = data.page()
    >>> t_sauvola = threshold_sauvola(image, window_size=15, k=0.2)
    >>> binary_image = image > t_sauvola
    NF)clip_negativer-   r   )r   r"  )r"   r%  r  riminimaxr  r!  rZ   rZ   r[   r   K  s
   5r   c           
      C   sZ   t j|d|d}| |k}| |k}t|\}}t||t |d }|dk}|| }	|	S )ak  Apply hysteresis thresholding to ``image``.

    This algorithm finds regions where ``image`` is greater than ``high``
    OR ``image`` is greater than ``low`` *and* that region is connected to
    a region greater than ``high``.

    Parameters
    ----------
    image : array, shape (M,[ N, ..., P])
        Grayscale input image.
    low : float, or array of same shape as ``image``
        Lower threshold.
    high : float, or array of same shape as ``image``
        Higher threshold.

    Returns
    -------
    thresholded : array of bool, same shape as ``image``
        Array in which ``True`` indicates the locations where ``image``
        was above the hysteresis threshold.

    Examples
    --------
    >>> image = np.array([1, 2, 3, 2, 1, 2, 1, 3, 2])
    >>> apply_hysteresis_threshold(image, 1.5, 2.5).astype(int)
    array([0, 1, 1, 1, 0, 0, 0, 1, 1])

    References
    ----------
    .. [1] J. Canny. A computational approach to edge detection.
           IEEE Transactions on Pattern Analysis and Machine Intelligence.
           1986; vol. 8, pp.679-698.
           :DOI:`10.1109/TPAMI.1986.4767851`
    N)a_mina_maxr   r   )r   r  r   labelr   r   )
r"   lowhighmask_low	mask_high
labels_low
num_labelssumsconnected_to_highthresholdedrZ   rZ   r[   r     s   #r   c          
      C   s   | dur| j dkr| jd dv rtd| j d t| ||dd\}}|d	}t|}||k r>d
| d| d}t|||krPt|dkd dd }nz	t	||d }W n t
yi   t||d }Y nw || }	|	S )a
  Generate `classes`-1 threshold values to divide gray levels in `image`,
    following Otsu's method for multiple classes.

    The threshold values are chosen to maximize the total sum of pairwise
    variances between the thresholded graylevel classes. See Notes and [1]_
    for more details.

    Either image or hist must be provided. If hist is provided, the actual
    histogram of the image is ignored.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray, optional
        Grayscale input image.
    classes : int, optional
        Number of classes to be thresholded, i.e. the number of resulting
        regions.
    nbins : int, optional
        Number of bins used to calculate the histogram. This value is ignored
        for integer arrays.
    hist : array, or 2-tuple of arrays, optional
        Histogram from which to determine the threshold, and optionally a
        corresponding array of bin center intensities. If no hist provided,
        this function will compute it from the image (see notes).

    Returns
    -------
    thresh : array
        Array containing the threshold values for the desired classes.

    Raises
    ------
    ValueError
         If ``image`` contains less grayscale value then the desired
         number of classes.

    Notes
    -----
    This implementation relies on a Cython function whose complexity
    is :math:`O\left(\frac{Ch^{C-1}}{(C-1)!}\right)`, where :math:`h`
    is the number of histogram bins and :math:`C` is the number of
    classes desired.

    If no hist is given, this function will make use of
    `skimage.exposure.histogram`, which behaves differently than
    `np.histogram`. While both allowed, use the former for consistent
    behaviour.

    The input image must be grayscale.

    References
    ----------
    .. [1] Liao, P-S., Chen, T-S. and Chung, P-C., "A fast algorithm for
           multilevel thresholding", Journal of Information Science and
           Engineering 17 (5): 713-727, 2001. Available at:
           <https://ftp.iis.sinica.edu.tw/JISE/2001/200109_01.pdf>
           :DOI:`10.6688/JISE.2001.17.5.1`
    .. [2] Tosa, Y., "Multi-Otsu Threshold", a java plugin for ImageJ.
           Available at:
           <http://imagej.net/plugins/download/Multi_OtsuThreshold.java>

    Examples
    --------
    >>> from skimage.color import label2rgb
    >>> from skimage import data
    >>> image = data.camera()
    >>> thresholds = threshold_multiotsu(image)
    >>> regions = np.digitize(image, bins=thresholds)
    >>> regions_colorized = label2rgb(regions)
    Nr   r   r   zYthreshold_multiotsu is expected to work correctly only for grayscale images; image shape r   T)r   r   zThe input image has only z/ different values. It cannot be thresholded in z	 classes.r   r   )r   r   r	   r   r   r   count_nonzeror   r   r   MemoryErrorr   )
r"   classesrO   r+   probr   nvaluesr   
thresh_idxrf   rZ   rZ   r[   r     s.    G



r   )NNr   T)r]   T)rn   r   r   ro   Nr   )NF)Nr!   )Nr!   F)Nr!   r   )r!   )r#  r$  )r#  r$  N)Nrn   r!   )5r>   r  r5   collectionsr   collections.abcr   numpyr   scipyr   r   _shared.filtersr   _shared.utilsr   r   r	   _shared.version_requirementsr
   exposurer   filters._multiotsur   r   r1   r   utilr   _sparser   r   __all__r\   r   r   r   r   r   r   r   r   _DEFAULT_ENTROPY_BINSr   r   r   r   r   r"  r   r   r   r   rZ   rZ   rZ   r[   <module>   sV    
>;

c8H=x1 
\
M
D
?</