
    9i                        S SK r S SKJr  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Jr  SSKJrJr  SS	KJr  SS
KJr  \S.S jr\S.S jr\S.S jr\R4                  " 5             SSS.S jj5       r\R4                  " 5        SSS.S jj5       rSS jr SSS.S jjrS rS r SS jr!     S S jr"S r#S r$\R4                  " 5              S!SS.S jj5       r%S"SS.S jjr&g)#    N)ceil   )img_as_float)utils)_supported_float_typewarn   )_denoise_bilateral_denoise_tv_bregman)color)ycbcr_from_rgbdtypec                >    [         R                  " SU S-  U-  -  US9$ )a  Helping function. Define a Gaussian weighting from array and
sigma_square.

Parameters
----------
array : ndarray
    Input array.
sigma_squared : float
    The squared standard deviation used in the filter.
dtype : data type object, optional (default : float)
    The type and size of the data to be returned.

Returns
-------
gaussian : ndarray
    The input array filtered by the Gaussian.
g      r   r   )npexp)arraysigma_squaredr   s      \/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/skimage/restoration/_denoise.py_gaussian_weightr      s#    $ 66$%(]235AA    c                H    [         R                  " SX SS9n[        XAS-  US9$ )a  Helping function. Define a lookup table containing Gaussian filter
values using the color distance sigma.

Parameters
----------
bins : int
    Number of discrete values for Gaussian weights of color filtering.
    A larger value results in improved accuracy.
sigma : float
    Standard deviation for grayvalue/color distance (radiometric
    similarity). A larger value results in averaging of pixels with larger
    radiometric differences. Note, that the image will be converted using
    the `img_as_float` function and thus the standard deviation is in
    respect to the range ``[0, 1]``. If the value is ``None`` the standard
    deviation of the ``image`` will be used.
max_value : float
    Maximum value of the input image.
dtype : data type object, optional (default : float)
    The type and size of the data to be returned.

Returns
-------
color_lut : ndarray
    Lookup table for the color distance sigma.
r   F)endpointr   r   )r   linspacer   )binssigma	max_valuer   valuess        r   _compute_color_lutr   %   s'    4 [[Ie<FF1HE::r   c                    [         R                  " U * S-  U S-  S-   5      n[         R                  " X3SS9u  pE[         R                  " XE5      n[	        XaS-  US9R                  5       $ )a5  Helping function. Define a lookup table containing Gaussian filter
values using the spatial sigma.

Parameters
----------
win_size : int
    Window size for filtering.
    If win_size is not specified, it is calculated as
    ``max(5, 2 * ceil(3 * sigma_spatial) + 1)``.
sigma : float
    Standard deviation for range distance. A larger value results in
    averaging of pixels with larger spatial differences.
dtype : data type object
    The type and size of the data to be returned.

Returns
-------
spatial_lut : ndarray
    Lookup table for the spatial sigma.
r   r	   ij)indexingr   )r   arangemeshgridhypotr   ravel)win_sizer   r   grid_pointsrrcc	distancess          r   _compute_spatial_lutr,   C   s]    * ))XINHMA,=>K[[DAFB IIaxu=CCEEr   channel_axisc                   Ub  U R                   S:w  a4  U R                   S:X  a  [        S5      e[        SU R                    S35      eU R                  S   S;  aZ  U R                  S   S:  a,  SU R                   S	U R                  S    S
3n[        U5        OESU R                   S3n[        U5        O)U R                   S:  a  [        SU R                   S35      eUc'  [	        SS[        [        SU-  5      5      -  S-   5      nU R                  5       n	U R	                  5       n
X:X  a  U $ [        R                  " [        U 5      5      n [        R                  " U 5      n U=(       d    U R                  5       n[        XBXR                  S9n[        XU R                  S9n[        R                   " U R                  U R                  S9nU R                  S   n[        R                   " XR                  S9nU	S:  a  X	-
  n X-  n
[#        U U
UUUUUUUUUU5        [        R$                  " U5      nU	S:  a  X-  nU$ )a  Denoise image using bilateral filter.

Parameters
----------
image : ndarray, shape (M, N[, 3])
    Input image, 2D grayscale or RGB.
win_size : int
    Window size for filtering.
    If win_size is not specified, it is calculated as
    ``max(5, 2 * ceil(3 * sigma_spatial) + 1)``.
sigma_color : float
    Standard deviation for grayvalue/color distance (radiometric
    similarity). A larger value results in averaging of pixels with larger
    radiometric differences. If ``None``, the standard deviation of
    ``image`` will be used.
sigma_spatial : float
    Standard deviation for range distance. A larger value results in
    averaging of pixels with larger spatial differences.
bins : int
    Number of discrete values for Gaussian weights of color filtering.
    A larger value results in improved accuracy.
mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}
    How to handle values outside the image borders. See
    `numpy.pad` for detail.
cval : int or float
    Used in conjunction with mode 'constant', the value outside
    the image boundaries.
channel_axis : int or None, optional
    If ``None``, the image is assumed to be grayscale (single-channel).
    Otherwise, this parameter indicates which axis of the array corresponds
    to channels.

    .. versionadded:: 0.19
       ``channel_axis`` was added in 0.19.

Returns
-------
denoised : ndarray
    Denoised image.

Notes
-----
This is an edge-preserving, denoising filter. It averages pixels based on
their spatial closeness and radiometric similarity [1]_.

Spatial closeness is measured by the Gaussian function of the Euclidean
distance between two pixels and a certain standard deviation
(`sigma_spatial`).

Radiometric similarity is measured by the Gaussian function of the
Euclidean distance between two color values and a certain standard
deviation (`sigma_color`).

Note that, if the image is of any `int` dtype, ``image`` will be
converted using the `img_as_float` function and thus the standard
deviation (`sigma_color`) will be in range ``[0, 1]``.

For more information on scikit-image's data type conversions and how
images are rescaled in these conversions,
see: https://scikit-image.org/docs/stable/user_guide/data_types.html.

References
----------
.. [1] C. Tomasi and R. Manduchi. "Bilateral Filtering for Gray and Color
       Images." IEEE International Conference on Computer Vision (1998)
       839-846. :DOI:`10.1109/ICCV.1998.710815`

Examples
--------
>>> from skimage import data, img_as_float
>>> astro = img_as_float(data.astronaut())
>>> astro = astro[220:300, 220:320]
>>> rng = np.random.default_rng()
>>> noisy = astro + 0.6 * astro.std() * rng.random(astro.shape)
>>> noisy = np.clip(noisy, 0, 1)
>>> denoised = denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15,
...                              channel_axis=-1)
   r   zUse ``channel_axis=None`` for 2D grayscale images. The last axis of the input image must be multiple color channels not another spatial dimension.zBilateral filter is only implemented for 2D grayscale images (image.ndim == 2) and 2D multichannel (image.ndim == 3) images, but the input image has z dimensions.)r0      r1   zTThe last axis of the input image is interpreted as channels. Input image with shape z has zc channels in last axis. ``denoise_bilateral``is implemented for 2D grayscale and color images only.z;Input image must be grayscale, RGB, or RGBA; but has shape .zfBilateral filter is not implemented for grayscale images of 3 or more dimensions, but input image has z2 shape. Use ``channel_axis=-1`` for 2D RGB images.   r	   r   r   )ndim
ValueErrorshaper   maxintr   minr   
atleast_3dr   ascontiguousarraystdr   r   r,   emptyr
   squeeze)imager'   sigma_colorsigma_spatialr   modecvalr.   msg	min_valuer   	color_lut	range_lutoutdims
empty_dimss                   r   denoise_bilateralrK   ^   sG   t ::?zzQ )  !/ 05zzl,H  [[^6){{1~!"[[Mu{{1~.> ?>?  S	%%*[[M4  S	::>'',{{m 49:  q!c$q='8"9::Q>?		I		I MM,u-.E  'E,K"4i{{SI$XEKKPI
((5;;ekk
2C;;q>D $kk2J1}!	 **S/C1}Jr   c          	         [         R                  " [        U 5      5      n U R                  S   nU R                  S   nU R                  S   nUS-   US-   U4n	[         R                  " XR
                  5      n
Ub  [         R                  " U	SS S-   U
R
                  S9n[        U R                  S   5       HU  n[         R                  " U SXS-   24   5      n[        UU R
                  R                  U5      UUUU5        US	   U
SU4'   MW     O<[         R                  " U 5      n [        X R
                  R                  U5      X#XJ5        [         R                  " U
SS2SS24   5      $ )
u  Perform total variation denoising using split-Bregman optimization.

Given :math:`f`, a noisy image (input data),
total variation denoising (also known as total variation regularization)
aims to find an image :math:`u` with less total variation than :math:`f`,
under the constraint that :math:`u` remain similar to :math:`f`.
This can be expressed by the Rudin--Osher--Fatemi (ROF) minimization
problem:

.. math::

    \min_{u} \sum_{i=0}^{N-1} \left( \left| \nabla{u_i} \right| + \frac{\lambda}{2}(f_i - u_i)^2 \right)

where :math:`\lambda` is a positive parameter.
The first term of this cost function is the total variation;
the second term represents data fidelity. As :math:`\lambda \to 0`,
the total variation term dominates, forcing the solution to have smaller
total variation, at the expense of looking less like the input data.

This code is an implementation of the split Bregman algorithm of Goldstein
and Osher to solve the ROF problem ([1]_, [2]_, [3]_).

Parameters
----------
image : ndarray
    Input image to be denoised (converted using :func:`~.img_as_float`).
weight : float, optional
    Denoising weight. It is equal to :math:`\frac{\lambda}{2}`. Therefore,
    the smaller the `weight`, the more denoising (at
    the expense of less similarity to `image`).
eps : float, optional
    Tolerance :math:`\varepsilon > 0` for the stop criterion:
    The algorithm stops when :math:`\|u_n - u_{n-1}\|_2 < \varepsilon`.
max_num_iter : int, optional
    Maximal number of iterations used for the optimization.
isotropic : boolean, optional
    Switch between isotropic and anisotropic TV denoising.
channel_axis : int or None, optional
    If ``None``, the image is assumed to be grayscale (single-channel).
    Otherwise, this parameter indicates which axis of the array corresponds
    to channels.

    .. versionadded:: 0.19
       ``channel_axis`` was added in 0.19.

Returns
-------
u : ndarray
    Denoised image.

Notes
-----
Ensure that `channel_axis` parameter is set appropriately for color
images.

The principle of total variation denoising is explained in [4]_.
It is about minimizing the total variation of an image,
which can be roughly described as
the integral of the norm of the image gradient. Total variation
denoising tends to produce cartoon-like images, that is,
piecewise-constant images.

See Also
--------
denoise_tv_chambolle : Perform total variation denoising in nD.

References
----------
.. [1] Tom Goldstein and Stanley Osher, "The Split Bregman Method For L1
       Regularized Problems",
       https://ww3.math.ucla.edu/camreport/cam08-29.pdf
.. [2] Pascal Getreuer, "Rudin–Osher–Fatemi Total Variation Denoising
       using Split Bregman" in Image Processing On Line on 2012–05–19,
       https://www.ipol.im/pub/art/2012/g-tvd/article_lr.pdf
.. [3] https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf
.. [4] https://en.wikipedia.org/wiki/Total_variation_denoising

r   r	   r   N)r	   r   .).r   )r   r:   r   r6   zerosr   ranger;   r   typer>   )r?   weightmax_num_itereps	isotropicr.   rowscolsrI   	shape_extrH   channel_outc
channel_ins                 r   denoise_tv_bregmanr[     sP   d MM,u-.E;;q>D;;q>D;;q>D4!8T*I
((9kk
*Chhy!}t3399Eu{{2'A --eCUN.CDJ  ( &f-CQK ($ $$U+;;##F+\		
 ::c!B$"*o&&r   c                    U R                   n[        R                  " U R                   4U R                  -   U R                  S9n[        R
                  " U5      n[        R
                  " U 5      nSnX:  Ga  US:  a  UR                  S5      * n[        S5      /U-  n	[        S5      /US-   -  n
[        U5       He  n[        SS5      X'   [        SS5      XS-   '   XS'   U[        U	5      ==   U[        U
5         -  ss'   [        S5      X'   [        S5      XS-   '   Mg     X-   nOU nUS-  R                  5       n[        S5      /US-   -  n[        U5       HH  n[        SS5      XS-   '   XS'   [        R                  " XS9U[        U5      '   [        S5      XS-   '   MJ     [        R                  " US-  R                  SS95      [        R                  S4   nXUR                  5       -  -  nS	S
U-  -  nUUU-  -  nUS	-  nUUU-  -  nX_-  nU[        U R                  5      -  nUS:X  a  UnUnO%[        R                  " WU-
  5      UW-  :  a   U$ UnUS-  nX:  a  GM  W$ )a  Perform total-variation denoising on n-dimensional images.

Parameters
----------
image : ndarray
    n-D input data to be denoised.
weight : float, optional
    Denoising weight. The greater `weight`, the more denoising (at
    the expense of fidelity to `input`).
eps : float, optional
    Relative difference of the value of the cost function that determines
    the stop criterion. The algorithm stops when:

        (E_(n-1) - E_n) < eps * E_0

max_num_iter : int, optional
    Maximal number of iterations used for the optimization.

Returns
-------
out : ndarray
    Denoised array of floats.

Notes
-----
Rudin, Osher and Fatemi algorithm.
r   r   Nr	   rM   r   axis.g      ?g       @)r4   r   rN   r6   r   
zeros_likesumslicerO   tuplediffsqrtnewaxisfloatsizeabs)r?   rQ   rS   rR   r4   pgdislices_dslices_paxrH   Eslices_gnormtauE_init
E_previouss                      r   _denoise_tv_chambolle_ndrv     sv   : ::D
%**,EKK@A
aA
eA	A

q5q	AdH dH Dk$Q~#(B<a  %/"ah&88"$T{#(;a  " )CCTJJL
 $K
AX +B$Q|H!VQK!#!6AeHo$T{H!V	  ww1zzqz)*2::s?;	dhhj  S4Z f	S1W			U5::6FJvvj1n%f4 J 
	Qc 
d Jr   c                   U R                   nUR                  S:X  d  [        U 5      n [        U R                   5      nU R	                  USS9n Ub  X@R
                  -  n[        R                  " [        R                  US9n[        R                  " U 5      n[        U R                  U   5       H   n	[        X" U	5         XU5      X" U	5      '   M"     U$ [        XX#5      nU$ )a  Perform total variation denoising in nD.

Given :math:`f`, a noisy image (input data),
total variation denoising (also known as total variation regularization)
aims to find an image :math:`u` with less total variation than :math:`f`,
under the constraint that :math:`u` remain similar to :math:`f`.
This can be expressed by the Rudin--Osher--Fatemi (ROF) minimization
problem:

.. math::

    \min_{u} \sum_{i=0}^{N-1} \left( \left| \nabla{u_i} \right| + \frac{\lambda}{2}(f_i - u_i)^2 \right)

where :math:`\lambda` is a positive parameter.
The first term of this cost function is the total variation;
the second term represents data fidelity. As :math:`\lambda \to 0`,
the total variation term dominates, forcing the solution to have smaller
total variation, at the expense of looking less like the input data.

This code is an implementation of the algorithm proposed by Chambolle
in [1]_ to solve the ROF problem.

Parameters
----------
image : ndarray
    Input image to be denoised. If its dtype is not float, it gets
    converted with :func:`~.img_as_float`.
weight : float, optional
    Denoising weight. It is equal to :math:`\frac{1}{\lambda}`. Therefore,
    the greater the `weight`, the more denoising (at the expense of
    fidelity to `image`).
eps : float, optional
    Tolerance :math:`\varepsilon > 0` for the stop criterion (compares to
    absolute value of relative difference of the cost function :math:`E`):
    The algorithm stops when :math:`|E_{n-1} - E_n| < \varepsilon * E_0`.
max_num_iter : int, optional
    Maximal number of iterations used for the optimization.
channel_axis : int or None, optional
    If ``None``, the image is assumed to be grayscale (single-channel).
    Otherwise, this parameter indicates which axis of the array corresponds
    to channels.

    .. versionadded:: 0.19
       ``channel_axis`` was added in 0.19.

Returns
-------
u : ndarray
    Denoised image.

Notes
-----
Make sure to set the `channel_axis` parameter appropriately for color
images.

The principle of total variation denoising is explained in [2]_.
It is about minimizing the total variation of an image,
which can be roughly described as
the integral of the norm of the image gradient. Total variation
denoising tends to produce cartoon-like images, that is,
piecewise-constant images.

See Also
--------
denoise_tv_bregman : Perform total variation denoising using split-Bregman
    optimization.

References
----------
.. [1] A. Chambolle, An algorithm for total variation minimization and
       applications, Journal of Mathematical Imaging and Vision,
       Springer, 2004, 20, 89-97.
.. [2] https://en.wikipedia.org/wiki/Total_variation_denoising

Examples
--------
2D example on astronaut image:

>>> from skimage import color, data
>>> img = color.rgb2gray(data.astronaut())[:50, :50]
>>> rng = np.random.default_rng()
>>> img += 0.5 * img.std() * rng.standard_normal(img.shape)
>>> denoised_img = denoise_tv_chambolle(img, weight=60)

3D example on synthetic data:

>>> x, y, z = np.ogrid[0:20, 0:20, 0:20]
>>> mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2
>>> mask = mask.astype(float)
>>> rng = np.random.default_rng()
>>> mask += 0.2 * rng.standard_normal(mask.shape)
>>> res = denoise_tv_chambolle(mask, weight=100)

fF)copyr]   )r   kindr   r   astyper4   	functoolspartialr   slice_at_axisr   r_   rO   r6   rv   )
r?   rQ   rS   rR   r.   im_typefloat_dtype_atrH   rY   s
             r   denoise_tv_chamboller     s    D kkG<<3U# (4KLL5L1E#jj0 3 3,GmmE"u{{<01A2c!fvLCAK 2 J 'ucHJr   c                     [         R                  " X -  5      n[         R                  " U R                  5      R                  nU[         R
                  " [        X!-
  U5      5      -  nU$ )z:BayesShrink threshold for a zero-mean details coeff array.)r   meanfinfor   rS   rd   r7   )detailsvardvarrS   threshs        r   _bayes_threshr   `  sN     777$%D
((7==
!
%
%C2773tz3/00FMr   c                 v    U[         R                  " S[         R                  " U R                  5      -  5      -  $ )z1Universal threshold used by the VisuShrink methodr   )r   rd   logrg   )imgr   s     r   _universal_threshr   i  s(    2771rvvchh//000r   c                 "   U [         R                  " U 5         n UR                  5       S:X  aX  [        R                  R
                  R                  S5      n[         R                  " [         R                  " U 5      5      U-  nU$ [        S5      e)a)  Calculate the robust median estimator of the noise standard deviation.

Parameters
----------
detail_coeffs : ndarray
    The detail coefficients corresponding to the discrete wavelet
    transform of an image.
distribution : str
    The underlying noise distribution.

Returns
-------
sigma : float
    The estimated noise standard deviation (see section 4.2 of [1]_).

References
----------
.. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation
   by wavelet shrinkage." Biometrika 81.3 (1994): 425-455.
   :DOI:`10.1093/biomet/81.3.425`
gaussiang      ?z5Only Gaussian noise estimation is currently supported)
r   nonzerolowerscipystatsrr   ppfmedianrh   r5   )detail_coeffsdistributiondenomr   s       r   _sigma_est_dwtr   n  ss    . ""**]";<Mz)  $$T*		"&&/058 L STTr   c                     SSK nUR                  U5      nUR                  (       d  [	        SUR
                   S35        [        S U R                   5       5      nUc+  UR                  U R                  U5      n[        US-
  S5      nUR                  XUS	9n	U	SS n
Uc  U
S
   SU R                  -     n[        USS9nUb  Ub  [	        SU S35        Uck  US-  nUc  [        S5      eUS:X  a2  U
 VVs/ s H"  nU Vs0 s H  o[        X   U5      _M     snPM$     nnnO US:X  a  [        X5      nO[        SU 35      e[         R"                  " U5      (       a6  U
 VVs/ s H&  nU Vs0 s H  nXR%                  X   X5S9_M     snPM(     nnnOG['        X:5       VVVs/ s H-  u  nnU Vs0 s H  nXR%                  X   UU   US9_M     snPM/     nnnnU	S   /U-   nUR)                  UU5      U   nUR+                  U R,                  5      nU$ ! [         a    [        S5      ef = fs  snf s  snnf s  snf s  snnf s  snf s  snnnf )a  Perform wavelet thresholding.

Parameters
----------
image : ndarray (2d or 3d) of ints, uints or floats
    Input data to be denoised. `image` can be of any numeric type,
    but it is cast into an ndarray of floats for the computation
    of the denoised image.
wavelet : string
    The type of wavelet to perform. Can be any of the options
    pywt.wavelist outputs. For example, this may be any of ``{db1, db2,
    db3, db4, haar}``.
method : {'BayesShrink', 'VisuShrink'}, optional
    Thresholding method to be used. The currently supported methods are
    "BayesShrink" [1]_ and "VisuShrink" [2]_. If it is set to None, a
    user-specified ``threshold`` must be supplied instead.
threshold : float, optional
    The thresholding value to apply during wavelet coefficient
    thresholding. The default value (None) uses the selected ``method`` to
    estimate appropriate threshold(s) for noise removal.
sigma : float, optional
    The standard deviation of the noise. The noise is estimated when sigma
    is None (the default) by the method in [2]_.
mode : {'soft', 'hard'}, optional
    An optional argument to choose the type of denoising performed. It
    noted that choosing soft thresholding given additive noise finds the
    best approximation of the original image.
wavelet_levels : int or None, optional
    The number of wavelet decomposition levels to use.  The default is
    three less than the maximum number of possible decomposition levels
    (see Notes below).

Returns
-------
out : ndarray
    Denoised image.

References
----------
.. [1] Chang, S. Grace, Bin Yu, and Martin Vetterli. "Adaptive wavelet
       thresholding for image denoising and compression." Image Processing,
       IEEE Transactions on 9.9 (2000): 1532-1546.
       :DOI:`10.1109/83.862633`
.. [2] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation
       by wavelet shrinkage." Biometrika 81.3 (1994): 425-455.
       :DOI:`10.1093/biomet/81.3.425`
r   NYPyWavelets is not installed. Please ensure it is installed in order to use this function.zgWavelet thresholding was designed for use with orthogonal wavelets. For nonorthogonal wavelets such as z%,results are likely to be suboptimal.c              3   8   #    U  H  n[        U5      v   M     g 7f)N)ra   ).0ss     r   	<genexpr>%_wavelet_threshold.<locals>.<genexpr>  s     :kE!HHks   r0   r	   )waveletlevelrM   rk   Gaussianr   zThresholding method z8 selected. The user-specified threshold will be ignored.r   z0If method is None, a threshold must be provided.BayesShrink
VisuShrinkzUnrecognized method: )valuerB   )pywtImportErrorWavelet
orthogonalr   namerb   r6   dwtn_max_levelr7   wavedecnr4   r   r5   r   r   r   isscalar	thresholdzipwaverecnr{   r   )r?   r   methodr   r   rB   wavelet_levelsr   original_extentcoeffsdcoeffsr   r   r   keydenoised_detailr   denoised_coeffsrH   s                      r   _wavelet_thresholdr     s   p
 ll7#G  '~ .'(	
 :ekk::O ,,U[['B ^a/3]]5]HFQRjG}C%**$45}:Fi3"6( +8 9	

 Qh>OPP}$ %$E AFFmEJ44F$  I |#)%7I4VH=>>	{{9 !

 ! ! C ^^EJi^KK  ! 	 
 "%Y!8

 "9 ! C ^^EJfSk^MM  "9 	 
 aykO3O
--
1/
BC
**U[[
!CJ_  
*
 	

b G

sS   H 8
H6H1H6%
I/H<I%I2 IIH.1H6<IIc                    U(       a]  [        U[        R                  5      (       d  Uc  U/U R                  S   -  nO'[	        U5      U R                  S   :w  a  [        S5      eU R                  R                  S:w  a  U(       a!  U R                  5       U R                  5       -
  n[        U 5      n U(       aO  U R                  5       U R                  5       -
  nUW-  nU(       a  U Vs/ s H  owb  Xv-  OUPM     nnX4$ Ub  X-  nX4$ U R                  [        R                  :X  a  U R                  [        R                  5      n X4$ s  snf )zIf the ``image`` is rescaled, also rescale ``sigma`` consistently.

Images that are not floating point will be rescaled via ``img_as_float``.
Half-precision images will be promoted to single precision.
rM   zdWhen channel_axis is not None, sigma must be a scalar or have length equal to the number of channelsrx   )
isinstancenumbersNumberr6   lenr5   r   rz   r7   r9   r   r   float16r{   float32)r?   r   multichannelrescale_sigma	range_pre
range_postscale_factorr   s           r   #_scale_sigma_and_image_consistentlyr     s'    eW^^,,Gekk"o-EZ5;;r?*9  {{3		eiik1IU#uyy{2J%	1LKPQ5a])A5Q
 <	 "% < 


	"RZZ(< Rs   *Ec                     U S   c  U $ [         R                  " U 5      n X -  n[        S5       HC  n[        USS24   n[         R                  " X3-  U-  5      n[         R
                  " U5      X'   ME     U $ )a0  Convert user-provided noise standard deviations to YCbCr space.

Notes
-----
If R, G, B are linearly independent random variables and a1, a2, a3 are
scalars, then random variable C:
    C = a1 * R + a2 * G + a3 * B
has variance, var_C, given by:
    var_C = a1**2 * var_R + a2**2 * var_G + a3**2 * var_B
r   Nr0   )r   asarrayrO   r   r`   rd   )sigmasrgv_variancesrl   scalarsvar_channels        r   _rescale_sigma_rgb2ycbcrr   ;  sq     ayZZFOM1X A&ffW.>?GGK(	  Mr   c                   USLn	US;  a  [        SU S35      eU R                  R                  S:g  n
U(       a  U	(       d  [        S5      e[        XX5      u  pU	(       Ga+  U(       a  [        R
                  " U 5      nU(       a  [        U5      n[        S5       H  nUSU4   R                  5       USU4   R                  5       pX-
  nUS	:X  a  M8  USU4   U-
  nUU-  nX   nUb  UU-  n[        UUUUUUUS
9USU4'   USU4   U-  USU4'   USU4==   U-  ss'   M     [        R                  " U5      nO_[        R                  " U 5      n[        U R                  S   5       H  n[        U SU4   UUUU   UUS9USU4'   M      O[        U UUUUUS9nU
(       a2  U R                  5       S	:  a  SOSn[        R                   " U/UQ7SU06nU$ )a  Perform wavelet denoising on an image.

Parameters
----------
image : ndarray (M[, N[, ...P]][, C]) of ints, uints or floats
    Input data to be denoised. `image` can be of any numeric type,
    but it is cast into an ndarray of floats for the computation
    of the denoised image.
sigma : float or list, optional
    The noise standard deviation used when computing the wavelet detail
    coefficient threshold(s). When None (default), the noise standard
    deviation is estimated via the method in [2]_.
wavelet : string, optional
    The type of wavelet to perform and can be any of the options
    ``pywt.wavelist`` outputs. The default is `'db1'`. For example,
    ``wavelet`` can be any of ``{'db2', 'haar', 'sym9'}`` and many more.
mode : {'soft', 'hard'}, optional
    An optional argument to choose the type of denoising performed. It
    noted that choosing soft thresholding given additive noise finds the
    best approximation of the original image.
wavelet_levels : int or None, optional
    The number of wavelet decomposition levels to use.  The default is
    three less than the maximum number of possible decomposition levels.
convert2ycbcr : bool, optional
    If True and channel_axis is set, do the wavelet denoising in the YCbCr
    colorspace instead of the RGB color space. This typically results in
    better performance for RGB images.
method : {'BayesShrink', 'VisuShrink'}, optional
    Thresholding method to be used. The currently supported methods are
    "BayesShrink" [1]_ and "VisuShrink" [2]_. Defaults to "BayesShrink".
rescale_sigma : bool, optional
    If False, no rescaling of the user-provided ``sigma`` will be
    performed. The default of ``True`` rescales sigma appropriately if the
    image is rescaled internally.

    .. versionadded:: 0.16
       ``rescale_sigma`` was introduced in 0.16
channel_axis : int or None, optional
    If ``None``, the image is assumed to be grayscale (single-channel).
    Otherwise, this parameter indicates which axis of the array corresponds
    to channels.

    .. versionadded:: 0.19
       ``channel_axis`` was added in 0.19.

Returns
-------
out : ndarray
    Denoised image.

Notes
-----
The wavelet domain is a sparse representation of the image, and can be
thought of similarly to the frequency domain of the Fourier transform.
Sparse representations have most values zero or near-zero and truly random
noise is (usually) represented by many small values in the wavelet domain.
Setting all values below some threshold to 0 reduces the noise in the
image, but larger thresholds also decrease the detail present in the image.

If the input is 3D, this function performs wavelet denoising on each color
plane separately.

.. versionchanged:: 0.16
   For floating point inputs, the original input range is maintained and
   there is no clipping applied to the output. Other input types will be
   converted to a floating point value in the range [-1, 1] or [0, 1]
   depending on the input image range. Unless ``rescale_sigma = False``,
   any internal rescaling applied to the ``image`` will also be applied
   to ``sigma`` to maintain the same relative amplitude.

Many wavelet coefficient thresholding approaches have been proposed. By
default, ``denoise_wavelet`` applies BayesShrink, which is an adaptive
thresholding method that computes separate thresholds for each wavelet
sub-band as described in [1]_.

If ``method == "VisuShrink"``, a single "universal threshold" is applied to
all wavelet detail coefficients as described in [2]_. This threshold
is designed to remove all Gaussian noise at a given ``sigma`` with high
probability, but tends to produce images that appear overly smooth.

Although any of the wavelets from ``PyWavelets`` can be selected, the
thresholding methods assume an orthogonal wavelet transform and may not
choose the threshold appropriately for biorthogonal wavelets. Orthogonal
wavelets are desirable because white noise in the input remains white noise
in the subbands. Biorthogonal wavelets lead to colored noise in the
subbands. Additionally, the orthogonal wavelets in PyWavelets are
orthonormal so that noise variance in the subbands remains identical to the
noise variance of the input. Example orthogonal wavelets are the Daubechies
(e.g. 'db2') or symmlet (e.g. 'sym2') families.

References
----------
.. [1] Chang, S. Grace, Bin Yu, and Martin Vetterli. "Adaptive wavelet
       thresholding for image denoising and compression." Image Processing,
       IEEE Transactions on 9.9 (2000): 1532-1546.
       :DOI:`10.1109/83.862633`
.. [2] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation
       by wavelet shrinkage." Biometrika 81.3 (1994): 425-455.
       :DOI:`10.1093/biomet/81.3.425`

Examples
--------
.. testsetup::
    >>> import pytest; _ = pytest.importorskip('pywt')

>>> from skimage import color, data
>>> img = img_as_float(data.astronaut())
>>> img = color.rgb2gray(img)
>>> rng = np.random.default_rng()
>>> img += 0.1 * rng.standard_normal(img.shape)
>>> img = np.clip(img, 0, 1)
>>> denoised_img = denoise_wavelet(img, sigma=0.1, rescale_sigma=True)

N)r   r   zInvalid method: zE. The currently supported methods are "BayesShrink" and "VisuShrink".rx   z-convert2ycbcr requires channel_axis to be setr0   .r   )r   r   r   rB   r   r   rM   )r   r   r   rB   r   )rM   r	   )r   r	   rH   )r5   r   rz   r   r   	rgb2ycbcrr   rO   r9   r7   denoise_wavelet	ycbcr2rgbr   
empty_liker6   r   clip)r?   r   r   rB   r   convert2ycbcrr   r   r.   r   clip_outputrH   rl   _min_maxr   channelsigma_channelrY   
clip_ranges                       r   r   r   Q  s   ~  t+L22vh ': ;
 	
 ++""c)K\HII6lLE //%(C071X a[__.CF0Ad#{1$c1f+,<' % ,!\1M-#!'#1"/CF "#q&kL8CFCFt#- . //#&C--&C5;;r?+0#q&M#!(#1CF , !)
  %		aWV
ggc0J0C0Jr   c          	          SSK nUb  X R                  -  n[        R                  " [
        R                  US9nU R                  U   n[        U5       Vs/ s H  n[        X" U5         SS9PM     nnU(       a  [        R                  " U5      nU$ U R                  S   S::  a  SU R                  S    S	3n[        U5        UR                  U S
S9n	U	SU R                  -     n
[        U
SS9$ ! [         a    [        S5      ef = fs  snf )am  
Robust wavelet-based estimator of the (Gaussian) noise standard deviation.

Parameters
----------
image : ndarray
    Image for which to estimate the noise standard deviation.
average_sigmas : bool, optional
    If true, average the channel estimates of `sigma`.  Otherwise return
    a list of sigmas corresponding to each channel.
channel_axis : int or None, optional
    If ``None``, the image is assumed to be grayscale (single-channel).
    Otherwise, this parameter indicates which axis of the array corresponds
    to channels.

    .. versionadded:: 0.19
       ``channel_axis`` was added in 0.19.

Returns
-------
sigma : float or list
    Estimated noise standard deviation(s).  If `multichannel` is True and
    `average_sigmas` is False, a separate noise estimate for each channel
    is returned.  Otherwise, the average of the individual channel
    estimates is returned.

Notes
-----
This function assumes the noise follows a Gaussian distribution. The
estimation algorithm is based on the median absolute deviation of the
wavelet detail coefficients as described in section 4.2 of [1]_.

References
----------
.. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation
   by wavelet shrinkage." Biometrika 81.3 (1994): 425-455.
   :DOI:`10.1093/biomet/81.3.425`

Examples
--------
.. testsetup::
    >>> import pytest; _ = pytest.importorskip('pywt')

>>> import skimage.data
>>> from skimage import img_as_float
>>> img = img_as_float(skimage.data.camera())
>>> sigma = 0.1
>>> rng = np.random.default_rng()
>>> img = img + sigma * rng.standard_normal(img.shape)
>>> sigma_hat = estimate_sigma(img, channel_axis=None)
r   Nr   r]   r-   rM   r1   zimage is size z~ on the last axis, but channel_axis is None. If this is a color image, please set channel_axis=-1 for proper noise estimation.db2)r   rk   r   r   )r   r   r4   r|   r}   r   r~   r6   rO   estimate_sigmar   r   r   dwtnr   )r?   average_sigmasr.   r   r   	nchannelsrY   r   rD   r   r   s              r   r   r     s    h
 #jj0 3 3,GKK-	FKIFV
FVN5Q=t<FV 	 
 WWV_F	RA	U[[_- .F G 	
 	S	YYueY,F3+,M-jAA3  
*
 	


s   C0 D	0D)NNr	   i'  constantr   )g      @d   gMbP?T)g?g-C6*?   )r   )NNNsoftN)Ndb1r   NFr   T)F)'r|   mathr   r   scipy.statsr   numpyr   
util.dtyper   _sharedr   _shared.utilsr   r   _denoise_cyr
   r    r   color.colorconvr   rf   r   r   r,   channel_as_last_axisrK   r[   rv   r   r   r   r   r   r   r   r   r    r   r   <module>r      sQ        %  7 @  , 5: B* 9> ;< 49 F6  			
w w wt =Au'SWu' u'pTp 14tEItn1
J 
	IX>,  	D D DNOB OBr   