
    0-Ph                        d dl Z d dlmZ 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mZmZ ddlmZmZ dd	lmZ dd
lmZ eddZeddZeddZ ej                    	 	 	 	 	 	 d*ddd            Z ej                    	 d+ddd            Zd,dZ	 d,dddZd Zd Z d-d Z!	 	 	 	 	 d.d"Z"d# Z#d$ Z$ ej                    	 	 	 	 	 	 	 d/ddd(            Z%d0ddd)Z&dS )1    N)ceil   )img_as_float)utils)_supported_float_typewarn   )_denoise_bilateral_denoise_tv_bregman)color)ycbcr_from_rgbdtypec                @    t          j        d| dz  |z  z  |          S )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/test/jupyter/venv/lib/python3.11/site-packages/skimage/restoration/_denoise.py_gaussian_weightr      s'    $ 6$%(]235AAAA    c                \    t          j        d|| d          }t          ||dz  |          S )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   %   s5    4 [Ite<<<FFE1HE::::r   c                    t          j        |  dz  | dz  dz             }t          j        ||d          \  }}t          j        ||          }t	          ||dz  |                                          S )ay  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   st    * )XINHMA,=>>K[kDAAAFBR  IIuaxu===CCEEEr   '  constantchannel_axisc                r   || j         dk    r2| j         dk    rt          d          t          d| j          d          | j        d         dvrT| j        d         dk    r)d	| j         d
| j        d          d}t          |           n>d| j         d}t          |           n#| j         dk    rt          d| j         d          |3t	          ddt          t          d|z                      z  dz             }|                                 }	|                                 }
|	|
k    r| S t          j	        t          |                     } t          j        |           } |p|                                 }t          |||
| j                  }t          ||| j                  }t          j        | j        | j                  }| j        d         }t          j        || j                  }|	dk     r
| |	z
  } |
|	z  }
t#          | |
||||||||||           t          j        |          }|	dk     r||	z  }|S )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)
    N   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.)r2      r3   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cvalr0   msg	min_valuer   	color_lut	range_lutoutdims
empty_dimss                   r   denoise_bilateralrM   ^   s   t :??zQ )   !H 05zH H H   [^6)){1~!!?"[? ?/4{1~? ? ?  S				4%*[4 4 4  S			:>>:',{: : :   q!c$q='8"9"9:::Q>??		I		II M,u--..E ''E,K"4iu{SSSI$X}EKPPPI
(5;ek
2
2
2C;q>D $ek222J1}}	!Y	   *S//C1}}yJr         @d   MbP?Tc          	         t          j        t          |                     } | j        d         }| j        d         }| j        d         }|dz   |dz   |f}	t          j        |	| j                  }
|t          j        |	dd         dz   |
j                  }t          | j        d                   D ]\}t          j        | d||dz   f                   }t          || j        	                    |          ||||           |d	         |
d|f<   ]n@t          j        |           } t          | | j        	                    |          ||||
           t          j
        |
ddddf                   S )
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   r8   zerosr   ranger=   r   typer@   )rA   weightmax_num_itereps	isotropicr0   rowscolsrK   	shape_extrJ   channel_outc
channel_ins                 r   denoise_tv_bregmanr`     s   d M,u--..E;q>D;q>D;q>D4!8T*I
(9ek
*
*Chy!}t339EEEu{2'' 	. 	.A -eCQUN.CDDJ  ((   &f-CQKK	.$ $U++5;##F++\3	3	
 	
 	
 :c!B$"*o&&&r   皙?-C6*?   c                 J   | j         }t          j        | j         f| j        z   | j                  }t          j        |          }t          j        |           }d}||k     rA|dk    r|                    d           }t          d          g|z  }	t          d          g|dz   z  }
t          |          D ]}t          dd          |	|<   t          dd          |
|dz   <   ||
d<   |t          |	          xx         |t          |
                   z  cc<   t          d          |	|<   t          d          |
|dz   <   | |z   }n| }|dz                                  }t          d          g|dz   z  }t          |          D ]X}t          dd          ||dz   <   ||d<   t          j
        ||          |t          |          <   t          d          ||dz   <   Yt          j        |dz                      d                    t          j        df         }|||                                z  z  }d	d
|z  z  }|||z  z  }|d	z  }|||z  z  }||z  }|t          | j                  z  }|dk    r|}|}n!t          j        ||z
            ||z  k     rn|}|dz  }||k     A|S )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	   rR   r   axis.g      ?g       @)r6   r   rS   r8   r   
zeros_likesumslicerT   tuplediffsqrtnewaxisfloatsizeabs)rA   rV   rX   rW   r6   pgdislices_dslices_paxrJ   Eslices_gnormtauE_init
E_previouss                      r   _denoise_tv_chambolle_ndr~     s   : :D
%*,EK@@@A
aA
eA	A
l

q55q	AdH dH Dkk / /$Q~~#(B<<a  %//"""ah&88"""$T{{#(;;a  !)CCCTJJLL
 $KK
AX ++ 	+ 	+B$Q||HR!VHQK!#2!6!6!6AeHoo$T{{HR!Vw1zzqz))**2:s?;	Vdhhjj  S4Z f	S1W	T		U5:66FJJvj1n%%f44
	Qc l

d Jr   c                   | j         }|j        dk    st          |           } t          | j                   }|                     |d          } ||| j        z  }t          j        t          j	        |          }t          j        |           }t          | j        |                   D ]/}	t          |  ||	                   |||          | ||	          <   0nt          | |||          }|S )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)copyNre   )r   kindr   r   astyper6   	functoolspartialr   slice_at_axisr   rg   rT   r8   r~   )
rA   rV   rX   rW   r0   im_typefloat_dtype_atrJ   r^   s
             r   denoise_tv_chamboller     s    D kG<3U## (44KLL5L11E#ej0 3,GGGmE""u{<011 	 	A2cc!ffvsL CAKK	
 'ufc<HHJr   c                     t          j        | | z            }t          j        | j                  j        }|t          j        t          ||z
  |                    z  }|S )z:BayesShrink threshold for a zero-mean details coeff array.)r   meanfinfor   rX   rl   r9   )detailsvardvarrX   threshs        r   _bayes_threshr   `  sS     77W$%%D
(7=
!
!
%C273tcz3//000FMr   c                 d    |t          j        dt          j        | j                  z            z  S )z1Universal threshold used by the VisuShrink methodr   )r   rl   logro   )imgr   s     r   _universal_threshr   i  s(    271rvch///0000r   Gaussianc                 $   | t          j        |                    } |                                dk    rNt          j        j                            d          }t          j        t          j        |                     |z  }nt          d          |S )am  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statsrz   ppfmedianrp   r7   )detail_coeffsdistributiondenomr   s       r   _sigma_est_dwtr   n  s{    . ""*]";";<Mz)) $$T**	"&//0058STTTLr   softc                    	 ddl n# t          $ r t          d          w xY w                    |          }|j        st	          d|j         d           t          d | j        D                       }|.                    | j        |          }t          |dz
  d          }
                    | ||	          }|dd         }	|'|	d
         d| j        z           }
t          |
d          }|t	          d| d           T|dz  |t          d          |dk    rfd|	D             n)|dk    rt          | |          nt          d|           t          j                  rfd|	D             }nfdt#          |	          D             }|d         g|z   }                    ||          |         }|                    | j                  }|S )aT  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   4   K   | ]}t          |          V  d S N)ri   ).0ss     r   	<genexpr>z%_wavelet_threshold.<locals>.<genexpr>  s(      ::E!HH::::::r   r2   r	   )waveletlevelrR   rs   r   r   zThresholding method z8 selected. The user-specified threshold will be ignored.r   z0If method is None, a threshold must be provided.BayesShrinkc                 0    g | ]fd D             S )c                 >    i | ]}|t          |                   S  )r   )r   keyr   r   s     r   
<dictcomp>z1_wavelet_threshold.<locals>.<listcomp>.<dictcomp>  s)    FFFmE#J44FFFr   r   )r   r   r   s    @r   
<listcomp>z&_wavelet_threshold.<locals>.<listcomp>  sB        GFFFFFFF  r   
VisuShrinkzUnrecognized method: c                 4    g | ]fd D             S )c                 N    i | ]!}|                     |                    "S )valuerD   	threshold)r   r   r   rD   pywtr   s     r   r   z1_wavelet_threshold.<locals>.<listcomp>.<dictcomp>  sA        T^^E#Jid^KK  r   r   )r   r   rD   r   r   s    @r   r   z&_wavelet_threshold.<locals>.<listcomp>  s\     
 
 

 	         
 
 
r   c                 <    g | ]\  fd D             S )c                 Z    i | ]'}|                     |         |                    (S r   r   )r   r   r   rD   r   r   s     r   r   z1_wavelet_threshold.<locals>.<listcomp>.<dictcomp>  sE        T^^E#JfSk^MM  r   r   )r   r   r   rD   r   s    @@r   r   z&_wavelet_threshold.<locals>.<listcomp>  sa     
 
 

 	         
 
 
r   )r   ImportErrorWavelet
orthogonalr   namerj   r8   dwtn_max_levelr9   wavedecnr6   r   r7   r   r   isscalarzipwaverecnr   r   )rA   r   methodr   r   rD   wavelet_levelsoriginal_extentcoeffsdcoeffsr   denoised_detaildenoised_coeffsrJ   r   r   s      ` `        @@r   _wavelet_thresholdr     s   p
 
 
 
*
 
 	

 ll7##G 
( '( ( (	
 	
 	
 ::ek:::::O ,,U['BB ^a/33]]5']HHFQRRjG}C%*$45}:FFFi396 9 9 9	
 	
 	

 Qh>OPPP}$$   $  II |##)%77II=V==>>>	{9 

 
 
 
 
 

 !
 
 

 
 
 
 

 "%Y!8!8
 
 
 aykO3O
--
1
1/
BC
**U[
!
!CJs    %c                 T   |r[t          |t          j                  s||g| j        d         z  }n-t	          |          | j        d         k    rt          d          | j        j        dk    r|r)|                                 | 	                                z
  }t          |           } |rF|                                 | 	                                z
  }||z  |rfd|D             }n<||z  }n4| j        t          j        k    r|                     t          j                  } | |fS )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.
    NrR   zdWhen channel_axis is not None, sigma must be a scalar or have length equal to the number of channelsr   c                 "    g | ]}||z  n|S r   r   )r   r   scale_factors     r   r   z7_scale_sigma_and_image_consistently.<locals>.<listcomp>3  s'    QQQaQ]\))QQQr   )
isinstancenumbersNumberr8   lenr7   r   r   r9   r;   r   r   float16r   float32)rA   r   multichannelrescale_sigma	range_pre
range_postr   s         @r   #_scale_sigma_and_image_consistentlyr     s4     eW^,, 	Gek"o-EEZZ5;r?**9   {3 	2		eiikk1IU## 	&uyy{{2J%	1L &QQQQ5QQQ"%	
	"	"RZ((%<r   c                     | d         | S t          j        |           } | | z  }t          d          D ]D}t          |ddf         }t          j        ||z  |z            }t          j        |          | |<   E| S )aP  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   Nr2   )r   asarrayrT   r   rh   rl   )sigmasrgv_variancesrt   scalarsvar_channels        r   _rescale_sigma_rgb2ycbcrr   ;  s     ayZFVOM1XX ) ) AAA&fWw.>??GK((q		Mr   db1Fr   c          
         |du}	|dvrt          d| d          | j        j        dk    }
|r|	st          d          t          | ||	|          \  } }|	rL|rt	          j        |           }|rt          |          }t          d          D ]}|d|f                                         |d|f         	                                }}||z
  }|d	k    rF|d|f         |z
  }||z  }||         }|||z  }t          |||||||
          |d|f<   |d|f         |z  |d|f<   |d|fxx         |z  cc<   t	          j        |          }not          j        |           }t          | j        d                   D ]*}t          | d|f         ||||         ||          |d|f<   +nt          | |||||          }|
r1|                                 d	k     rdnd}t          j        |g|R d|i}|S )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".r   z-convert2ycbcr requires channel_axis to be setr2   .r   )r   r   r   rD   r   r   rR   )r   r   r   rD   r   )rR   r	   )r   r	   rJ   )r7   r   r   r   r   	rgb2ycbcrr   rT   r;   r9   denoise_wavelet	ycbcr2rgbr   
empty_liker8   r   clip)rA   r   r   rD   r   convert2ycbcrr   r   r0   r   clip_outputrJ   rt   _min_maxr   channelsigma_channelr^   
clip_ranges                       r   r   r   Q  s   ~  t+L222;v ; ; ;
 
 	
 +"c)K J\ JHIII6ulM LE5  1
 '	/%((C 80771XX $ $ a[__..CF0A0Ad#d{1$$c1f+,<' %a ,!\1M-#!'#1"/  CF "#q&kL8CFCFt#/#&&CC-&&C5;r?++  0#q&M#!(#1  CF !)
 
 
  1 %		aWWV
gc0J000C00Jr   c                   	 	 ddl }n# t          $ r t          d          w xY w|k| j        z  }t          j        t
          j        |          	 j        |         }	 fdt          |          D             }|rt          j
        |          }|S  j        d         dk    r d j        d          d	}t          |           |                     d
          }|d j        z           }t          |d          S )a  
    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   re   c                 P    g | ]"}t           |                   d           #S )Nr/   )estimate_sigma)r   r^   r   rA   s     r   r   z"estimate_sigma.<locals>.<listcomp>Y  s?     
 
 
ABN5Q=t<<<
 
 
r   rR   r3   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   rs   r   r   )r   r   r6   r   r   r   r   r8   rT   r   r   r   dwtnr   )
rA   average_sigmasr0   r   	nchannelsr   rF   r   r   r   s
   `        @r   r   r     sL   h
 
 
 
*
 
 	

 #ej0 3,GGGK-	
 
 
 
 
FKIFVFV
 
 
  	%WV__F	RA		GU[_ G G G 	
 	S			YYueY,,F3+,M-jAAAAs   	 #)NNr	   r-   r.   r   )rN   rO   rP   T)ra   rb   rc   )r   )NNNr   N)Nr   r   NFr   T)F)'r   mathr   r   scipy.statsr   numpyr   
util.dtyper   _sharedr   _shared.utilsr   r   _denoise_cyr
   r    r   color.colorconvr   rn   r   r   r,   channel_as_last_axisrM   r`   r~   r   r   r   r   r   r   r   r   r   r   r   r   <module>r     s                      % % % % % %       7 7 7 7 7 7 7 7 @ @ @ @ @ @ @ @       , , , , , , 5: B B B B B* 9> ; ; ; ; ;< 49 F F F F F6  			
w w w w w wt =Au'SWu' u' u' u' u'pT T T Tp 14tEIt t t t tn  1 1 1
   J 
	I I I IX  >  ,  	D D D D D DNOB OB OB OB OB OB OB OBr   