o
    oi@                     @  sN  d dl mZ d dlmZ d dlmZmZmZ d dlZd dl	m
Z
mZmZ d dlmZ d dlmZmZmZ d dlmZmZmZ d d	lmZ d d
lmZmZ dlddZdlddZdlddZdlddZdlddZ dmdnddZ!dodpd#d$Z"dld%d&Z#dodpd'd(Z$dodpd)d*Z%dqdrd1d2Z&dsdtd4d5Z'dudvd7d8Z(	+	dwdxd;d<Z)edyd?d@Z*edzdAdBZ+d{dEdFZ,d|dIdJZ-d}dLdMZ.ed~dNdOZ/ed~dPdQZ0dddTdUZ1G dVdW dWeZ2G dXdY dYeZ3G dZd[ d[eZ4G d\d] d]eZ5G d^d_ d_eZ6G d`da daeZ7G dbdc dceZ8G ddde deeZ9G dfdg dgeZ:G dhdi dieZ;G djdk dkeZ<dS )    )annotations)pi)ClassVarOptionalUnionN)
hsv_to_rgbrgb_to_grayscale
rgb_to_hsv)ImageModule)	ParameterTensortensor)KORNIA_CHECKKORNIA_CHECK_IS_COLOR_OR_GRAYKORNIA_CHECK_IS_TENSOR)_torch_histc_cast)perform_keep_shape_imageperform_keep_shape_videoimager   factorUnion[float, Tensor]returnc                 C  s   t | d tt|ttfd t|trtj|| j| jd}nt|tr,|	| j| j}t
|jt
| jkrD|d }t
|jt
| jks6tj| ddd\}}}tj|| dd	d
}tj|||gdd}|S )z[Adjust color saturation of an image.

    Expecting image to be in hsv format already.
    Expected shape (*, H, W)!Factor should be float or Tensor.devicedtype.N   chunksdimr      minmaxr"   )r   r   
isinstancefloatr   torch	as_tensorr   r   tolenshapechunkclampcat)r   r   hsvs_outout r7   I/home/ubuntu/.local/lib/python3.10/site-packages/kornia/enhance/adjust.pyadjust_saturation_raw%   s   


r9   c                 C  s   t | d tt|ttfd t| d | jd dkr| S t|tr-tj|| j	| j
d}nt|tr:|| j	| j
}t|jt| jkrR|d }t|jt| jksDt| }d| | ||   }t|dd	}|S )
a4  Adjust color saturation of an image by blending the image with its grayscaled version.

    The image is expected to be an RGB image or a gray image in the range of [0, 1].
    If it is an RGB image, returns blending of the image with its grayscaled version.
    If it is a gray image, returns the image.

    .. note::
        this is just a convenience function to have compatibility with Pil

    Args:
        image: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
        factor: How much to adjust the saturation. 0 will give a black
          and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.

    Return:
        Adjusted image in the shape of :math:`(*, 3, H, W)`.

    Example:
        >>> x = torch.ones(1, 3, 3, 3)
        >>> adjust_saturation_with_gray_subtraction(x, 2.).shape
        torch.Size([1, 3, 3, 3])

        >>> x = torch.ones(2, 3, 3, 3)
        >>> y = torch.tensor([1., 2.])
        >>> adjust_saturation_with_gray_subtraction(x, y).shape
        torch.Size([2, 3, 3, 3])

    r   r   z$Image should be an RGB or gray imager   r#   r   r                 ?)r   r   r(   r)   r   r   r.   r*   r+   r   r   r,   r-   r   r0   )r   r   x_other
x_adjustedr6   r7   r7   r8   'adjust_saturation_with_gray_subtractionC   s    



r>   c                 C     t | }t||}t|}|S )a  Adjust color saturation of an image.

    .. image:: _static/img/adjust_saturation.png

    The image is expected to be an RGB image in the range of [0, 1].

    Args:
        image: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
        factor: How much to adjust the saturation. 0 will give a black
          and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
        saturation_mode: The mode to adjust saturation.

    Return:
        Adjusted image in the shape of :math:`(*, 3, H, W)`.

    .. note::
       See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.

    Example:
        >>> x = torch.ones(1, 3, 3, 3)
        >>> adjust_saturation(x, 2.).shape
        torch.Size([1, 3, 3, 3])

        >>> x = torch.ones(2, 3, 3, 3)
        >>> y = torch.tensor([1., 2.])
        >>> adjust_saturation(x, y).shape
        torch.Size([2, 3, 3, 3])

    )r	   r9   r   r   r   x_hsvr=   r6   r7   r7   r8   adjust_saturation|   s   
rB   c                 C  s   t | d tt|ttfdt|  t|trt|}|| j	| j
}t|jt| jkr>|d }t|jt| jks0tj| ddd\}}}dt }t|| |}tj|||gdd}|S )	zNAdjust hue of an image.

    Expecting image to be in hsv format already.
    r   zRThe factor should be a float number or Tensor in the range between [-PI, PI]. Got r   r   r   r       r'   )r   r   r(   r)   r   typer*   r+   r,   r   r   r-   r.   r/   r   fmodr1   )r   r   r2   r3   r4   divisorh_outr6   r7   r7   r8   adjust_hue_raw   s    


rH   c                 C  r?   )a  Adjust hue of an image.

    .. image:: _static/img/adjust_hue.png

    The image is expected to be an RGB image in the range of [0, 1].

    Args:
        image: Image to be adjusted in the shape of :math:`(*, 3, H, W)`.
        factor: How much to shift the hue channel. Should be in [-PI, PI]. PI
          and -PI give complete reversal of hue channel in HSV space in positive and negative
          direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
          image with complementary colors while 0 gives the original image.

    Return:
        Adjusted image in the shape of :math:`(*, 3, H, W)`.

    .. note::
       See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.

    Example:
        >>> x = torch.ones(1, 3, 2, 2)
        >>> adjust_hue(x, 3.141516).shape
        torch.Size([1, 3, 2, 2])

        >>> x = torch.ones(2, 3, 3, 3)
        >>> y = torch.ones(2) * 3.141516
        >>> adjust_hue(x, y).shape
        torch.Size([2, 3, 3, 3])

    )r	   rH   r   r@   r7   r7   r8   
adjust_hue   s    
rI   r;   inputgammagainc                 C  sZ  t | tstdt|  t |ttfstdt| t |ttfs.tdt| t |tr8t|g}t |trBt|g}|| j| j}|| j| j}|dk  rct	d| |dk  rpt	d| t
t| jt|j D ]	}tj|dd}q|t
t| jt|j D ]	}tj|dd}q|t| | }t|dd	}|S )
a  Perform gamma correction on an image.

    .. image:: _static/img/adjust_contrast.png

    The input image is expected to be in the range of [0, 1].

    Args:
        input: Image to be adjusted in the shape of :math:`(*, H, W)`.
        gamma: Non negative real number, same as y\gammay in the equation.
            gamma larger than 1 make the shadows darker, while gamma smaller than 1 make
            dark regions lighter.
        gain: The constant multiplier.

    Return:
        Adjusted image in the shape of :math:`(*, H, W)`.

    .. note::
       See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.

    Example:
        >>> x = torch.ones(1, 1, 2, 2)
        >>> adjust_gamma(x, 1.0, 2.0)
        tensor([[[[1., 1.],
                  [1., 1.]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y1 = torch.ones(2) * 1.0
        >>> y2 = torch.ones(2) * 2.0
        >>> adjust_gamma(x, y1, y2).shape
        torch.Size([2, 5, 3, 3])

     Input type is not a Tensor. Got z4The gamma should be a positive float or Tensor. Got z3The gain should be a positive float or Tensor. Got r:   z Gamma must be non-negative. Got zGain must be non-negative. Got r'   r;   )r(   r   	TypeErrorrD   r)   r,   r   r   any
ValueErrorranger-   r.   r*   	unsqueezepowr0   )rJ   rK   rL   _x_adjustr6   r7   r7   r8   adjust_gamma   s.   
!



rW   Tclip_outputboolc                 C  s   t | d tt|ttfd t|trtj|| j| jd}nt|tr,|	| j| j}t
|jt
| jkrD|d }t
|jt
| jks6tt|dkd | | }|rZ|jddd	}|S )
a  Adjust the contrast of an image tensor.

    .. image:: _static/img/adjust_contrast.png

    This implementation follows Szeliski's book convention, where contrast is defined as
    a `multiplicative` operation directly to raw pixel values. Beware that other frameworks
    might use different conventions which can be difficult to reproduce exact results.

    The input image and factor is expected to be in the range of [0, 1].

    .. tip::
        This is not the preferred way to adjust the contrast of an image. Ideally one must
        implement :func:`kornia.enhance.adjust_gamma`. More details in the following link:
        https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_log_gamma.html#sphx-glr-auto-examples-color-exposure-plot-log-gamma-py

    Args:
        image: Image to be adjusted in the shape of :math:`(*, H, W)`.
        factor: Contrast adjust factor per element
            in the batch. 0 generates a completely black image, 1 does not modify
            the input image while any other non-negative number modify the
            brightness by this factor.
        clip_output: whether to clip the output image with range of [0, 1].

    Return:
        Adjusted image in the shape of :math:`(*, H, W)`.

    .. note::
       See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.

    Example:
        >>> import torch
        >>> x = torch.ones(1, 1, 2, 2)
        >>> adjust_contrast(x, 0.5)
        tensor([[[[0.5000, 0.5000],
                  [0.5000, 0.5000]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y = torch.tensor([0.65, 0.50])
        >>> adjust_contrast(x, y).shape
        torch.Size([2, 5, 3, 3])

    r   r   r   r   r   z!Contrast factor must be positive.r:   r;   r$   )r   r   r(   r)   r   r*   r+   r   r   r,   r-   r.   rP   r0   r   r   rX   
img_adjustr7   r7   r8   adjust_contrast:  s   
+

r\   c                 C  s   t | d tt|ttfd t|trtj|| j| jd}nt|tr,|	| j| j}t
|jt
| jkrD|d }t
|jt
| jks6| jd dkrTt| dd}n|  }| | |d	|   }|jd
dd}|S )a!  Adjust the contrast of an image tensor by subtracting the mean over channels.

    .. note::
        this is just a convenience function to have compatibility with Pil. For exact
        definition of image contrast adjustment consider using :func:`kornia.enhance.adjust_gamma`.

    Args:
        image: Image to be adjusted in the shape of :math:`(*, H, W)`.
        factor: Contrast adjust factor per element
            in the batch. 0 generates a completely black image, 1 does not modify
            the input image while any other non-negative number modify the
            brightness by this factor.

    Return:
        Adjusted image in the shape of :math:`(*, H, W)`.

    Example:
        >>> import torch
        >>> x = torch.ones(1, 1, 2, 2)
        >>> adjust_contrast_with_mean_subtraction(x, 0.5)
        tensor([[[[1., 1.],
                  [1., 1.]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y = torch.tensor([0.65, 0.50])
        >>> adjust_contrast_with_mean_subtraction(x, y).shape
        torch.Size([2, 5, 3, 3])

    r   r   r   r   r   r   )rN   Tr#   r:   r;   r$   )r   r   r(   r)   r   r*   r+   r   r   r,   r-   r.   r   meanr0   )r   r   img_meanr[   r7   r7   r8   %adjust_contrast_with_mean_subtraction~  s   


r`   c                 C  s   t | d tt|ttfd t|trtj|| j| jd}nt|tr,|	| j| j}t
|jt
| jkrD|d }t
|jt
| jks6| | }|rQ|jddd}|S )aO  Adjust the brightness of an image tensor.

    .. image:: _static/img/adjust_brightness.png

    This implementation follows Szeliski's book convention, where brightness is defined as
    an `additive` operation directly to raw pixel and shift its values according the applied
    factor and range of the image values. Beware that other framework might use different
    conventions which can be difficult to reproduce exact results.

    The input image and factor is expected to be in the range of [0, 1].

    .. tip::
        By applying a large factor might prouce clipping or loss of image detail. We recommenda to
        apply small factors to avoid the mentioned issues. Ideally one must implement the adjustment
        of image intensity with other techniques suchs as :func:`kornia.enhance.adjust_gamma`. More
        details in the following link:
        https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_log_gamma.html#sphx-glr-auto-examples-color-exposure-plot-log-gamma-py

    Args:
        image: Image to be adjusted in the shape of :math:`(*, H, W)`.
        factor: Brightness adjust factor per element in the batch. It's recommended to
            bound the factor by [0, 1]. 0 does not modify the input image while any other
            number modify the brightness.
        clip_output: Whether to clip output to be in [0,1].

    Return:
        Adjusted tensor in the shape of :math:`(*, H, W)`.

    .. note::
       See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.

    Example:
        >>> x = torch.ones(1, 1, 2, 2)
        >>> adjust_brightness(x, 1.)
        tensor([[[[1., 1.],
                  [1., 1.]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y = torch.tensor([0.25, 0.50])
        >>> adjust_brightness(x, y).shape
        torch.Size([2, 5, 3, 3])

    r   r   r   r   r:   r;   r$   r   r   r(   r)   r   r*   r+   r   r   r,   r-   r.   r0   rZ   r7   r7   r8   adjust_brightness  s   
,

rb   c                 C  s   t | d tt|ttfd t|trtj|| j| jd}nt|tr,|	| j| j}t
|jt
| jkrD|d }t
|jt
| jks6| | }|rQ|jddd}|S )a  Adjust the brightness accumulatively of an image tensor.

    This implementation follows PIL convention.

    The input image and factor is expected to be in the range of [0, 1].

    Args:
        image: Image to be adjusted in the shape of :math:`(*, H, W)`.
        factor: Brightness adjust factor per element in the batch. It's recommended to
            bound the factor by [0, 1]. 0 does not modify the input image while any other
            number modify the brightness.
        clip_output: Whether to clip output to be in [0,1].

    Return:
        Adjusted tensor in the shape of :math:`(*, H, W)`.

    Example:
        >>> x = torch.ones(1, 1, 2, 2)
        >>> adjust_brightness_accumulative(x, 1.)
        tensor([[[[1., 1.],
                  [1., 1.]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y = torch.tensor([0.25, 0.50])
        >>> adjust_brightness_accumulative(x, y).shape
        torch.Size([2, 5, 3, 3])

    r   r   r   r   r:   r;   r$   ra   rZ   r7   r7   r8   adjust_brightness_accumulative  s   


rc         ?
   Fcutoffr)   invc                 C  sJ   t | d |rddd|||       }|S dd|||      }|S )a$  Adjust sigmoid correction on the input image tensor.

    The input image is expected to be in the range of [0, 1].

    Reference:
        [1]: Gustav J. Braun, "Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions",
             http://markfairchild.org/PDFs/PAP07.pdf

    Args:
        image: Image to be adjusted in the shape of :math:`(*, H, W)`.
        cutoff: The cutoff of sigmoid function.
        gain: The multiplier of sigmoid function.
        inv: If is set to True the function will return the inverse sigmoid correction.

    Returns:
         Adjusted tensor in the shape of :math:`(*, H, W)`.

    Example:
        >>> x = torch.ones(1, 1, 2, 2)
        >>> adjust_sigmoid(x, gain=0)
        tensor([[[[0.5000, 0.5000],
                  [0.5000, 0.5000]]]])

    r   r#   )r   exp)r   rf   rL   rg   r[   r7   r7   r8   adjust_sigmoid1  s   
ri   r#   c                 C  sF   t | d |rd|  d | }nd|   | }|r!|jddd}|S )a  Adjust log correction on the input image tensor.

    The input image is expected to be in the range of [0, 1].

    Reference:
    [1]: http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf

    Args:
        image: Image to be adjusted in the shape of :math:`(*, H, W)`.
        gain: The multiplier of logarithmic function.
        inv:  If is set to True the function will return the inverse logarithmic correction.
        clip_output: Whether to clip the output image with range of [0, 1].

    Returns:
        Adjusted tensor in the shape of :math:`(*, H, W)`.

    Example:
        >>> x = torch.zeros(1, 1, 2, 2)
        >>> adjust_log(x, inv=True)
        tensor([[[[0., 0.],
                  [0., 0.]]]])

    r   rC   r#   r:   r;   r$   )r   log2r0   )r   rL   rg   rX   r[   r7   r7   r8   
adjust_logS  s   
rk   
thresholdsc                   s   t  tstdt  t |ttfstdt| t |tr]t|jdkr] dt|kr:t|jdksGtd d d| |	 j
	 j}t fdd|D }t |k  d	  S )
a  For each pixel in the image, select the pixel if the value is less than the threshold.

    Otherwise, subtract 1.0 from the pixel.

    Args:
        input: image or batched images to solarize.
        thresholds: solarize thresholds.
            If int or one element tensor, input will be solarized across the whole batch.
            If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input).

    Returns:
        Solarized images.

    rM   3The factor should be either a float or Tensor. Got r   r#   z*thresholds must be a 1-d vector of shape (,). Got c                       g | ]}|j  jd d  qS r   Nexpandr.   .0xrJ   r7   r8   
<listcomp>       z_solarize.<locals>.<listcomp>r;   )r(   r   rO   rD   r)   r-   r.   sizeAssertionErrorr,   r   r   r*   stackwhere)rJ   rl   r7   rv   r8   	_solarizey  s   
 r}   	additionsOptional[Union[float, Tensor]]c                   sN  t  tstdt  t |ttfstdt| t |tr(t|}|durt |ttfs<tdt| t |trFt|}t|dk |dk sYtd| dt |trt	|j
dkr dt	|krut	|j
d	kstd
 d d| | j j}t fdd|D } |   dd t |S )a   For each pixel in the image less than threshold.

    .. image:: _static/img/solarize.png

    We add 'addition' amount to it and then clip the pixel value to be between 0 and 1.0.
    The value of 'addition' is between -0.5 and 0.5.

    Args:
        input: image tensor with shapes like :math:`(*, C, H, W)` to solarize.
        thresholds: solarize thresholds.
            If int or one element tensor, input will be solarized across the whole batch.
            If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input).
        additions: between -0.5 and 0.5.
            If None, no addition will be performed.
            If int or one element tensor, same addition will be added across the whole batch.
            If 1-d tensor, additions will be added element-wisely, len(additions) == len(input).

    Returns:
        The solarized images with shape :math:`(*, C, H, W)`.

    Example:
        >>> x = torch.rand(1, 4, 3, 3)
        >>> out = solarize(x, thresholds=0.5, additions=0.)
        >>> out.shape
        torch.Size([1, 4, 3, 3])

        >>> x = torch.rand(2, 4, 3, 3)
        >>> thresholds = torch.tensor([0.8, 0.5])
        >>> additions = torch.tensor([-0.25, 0.25])
        >>> solarize(x, thresholds, additions).shape
        torch.Size([2, 4, 3, 3])

    rM   rm   Nrd   g      z5The value of 'addition' is between -0.5 and 0.5. Got .r   r#   z)additions must be a 1-d vector of shape (rn   c                   ro   rp   rq   rs   rv   r7   r8   rw     rx   zsolarize.<locals>.<listcomp>r:   r;   )r(   r   rO   rD   r)   r*   r+   allrz   r-   r.   ry   r,   r   r   r{   r0   r}   )rJ   rl   r~   r7   rv   r8   solarize  s*   
&



 
r   bitsUnion[int, Tensor]c                   s  t | tstdt|  t |ttfstdt| t |tr(t|}ddd dd	d
d fdd}t|jdksNt|jdkrSt|dkrS|| |S g }t|jdkr|jd | jd krwt	d|jd  d| jd  dt
| jd D ]}||| | ||  q~tj|ddS |j| jdt|j krt	d|j d| jdt|j  d| jdg| jt|jd R  }| }t
| jd D ]}|||| ||  qtj|ddj| j S )a  Reduce the number of bits for each color channel.

    .. image:: _static/img/posterize.png

    Non-differentiable function, ``torch.uint8`` involved.

    Args:
        input: image tensor with shape :math:`(*, C, H, W)` to posterize.
        bits: number of high bits. Must be in range [0, 8].
            If int or one element tensor, input will be posterized by this bits.
            If 1-d tensor, input will be posterized element-wisely, len(bits) == input.shape[-3].
            If n-d tensor, input will be posterized element-channel-wisely, bits.shape == input.shape[:len(bits.shape)]

    Returns:
        Image with reduced color channels with shape :math:`(*, C, H, W)`.

    Example:
        >>> x = torch.rand(1, 6, 3, 3)
        >>> out = posterize(x, bits=8)
        >>> torch.testing.assert_close(x, out)

        >>> x = torch.rand(2, 6, 3, 3)
        >>> bits = torch.tensor([4, 2])
        >>> posterize(x, bits).shape
        torch.Size([2, 6, 3, 3])

    rM   z'bits type is not an int or Tensor. Got rJ   r   shiftr   c                 S  s$   | d  tjd|   | jd S N   rC        o@r,   r*   uint8r   rJ   r   r7   r7   r8   _left_shift     $zposterize.<locals>._left_shiftc                 S  s$   | d  tjd|  | j d S r   r   r   r7   r7   r8   _right_shift  r   zposterize.<locals>._right_shiftr   c                   s:   |dkr	t | S |dkr|  S d| } | ||S )Nr      )r*   
zeros_likeclone)rJ   r   r   r   r7   r8   _posterize_one  s   
z!posterize.<locals>._posterize_oner   r#   z5Batch size must be equal between bits and input. Got z, r   r'   Nz<Batch and channel must be equal between bits and input. Got rN   )rJ   r   r   r   r   r   )rJ   r   r   r   r   r   )r(   r   rO   rD   intr*   r+   r-   r.   rz   rR   appendr{   viewflattenreshape)rJ   r   r   resi_input_bitsr7   r   r8   	posterize  sB   




(	
"r   c                   sZ  t  tstj jjd t  dkr1 jt	dgkr1t
dd d j tjg dg dg dgjjdddd	d	ddddd
 }tjjj|dddd}t|dd}t|}tjj|g d}tjj|g d}t|dk|t  dkrt S t fddtt D S )a>  Apply sharpness to the input tensor.

    .. image:: _static/img/sharpness.png

    Implemented Sharpness function from PIL using torch ops. This implementation refers to:
    https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L326

    Args:
        input: image tensor with shape :math:`(*, C, H, W)` to sharpen.
        factor: factor of sharpness strength. Must be above 0.
            If float or one element tensor, input will be sharpened by the same factor across the whole batch.
            If 1-d tensor, input will be sharpened element-wisely, len(factor) == len(input).

    Returns:
        Sharpened image or images with shape :math:`(*, C, H, W)`.

    Example:
        >>> x = torch.rand(1, 1, 5, 5)
        >>> sharpness(x, 0.5).shape
        torch.Size([1, 1, 5, 5])

    r   r   zSInput batch size shall match with factor size if factor is not a 0-dim tensor. Got z and )r#   r#   r#   )r#      r#   )r   r   r#   r      N)biasstridegroupsr:   r;   )r#   r#   r#   r#   c                   s$   g | ]}t | |  | qS r7   )
_blend_onert   r   r   rJ   resultr7   r8   rw   k  s   $ zsharpness.<locals>.<listcomp>)r(   r   r*   r+   r   r   r-   ry   r.   Sizerz   r   repeatnn
functionalconv2dr0   	ones_likepadr|   r   r{   rR   )rJ   r   kernel
degeneratemaskpadded_maskpadded_degenerater7   r   r8   	sharpness6  s2   
($	
$r   input1input2c                 C  s   t | tstd|  dt |tstd| dt |tr/t| dkr/td| d|dkr5| S |dkr;|S ||  | }| | }|dkrO|dk rO|S t|ddS )a@  Blend two images into one.

    Args:
        input1: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
        input2: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
        factor: factor 0-dim tensor.

    Returns:
        : image tensor with the batch in the zero position.

    z`input1` must be a tensor. Got r   r   z6Factor shall be a float or single element tensor. Got r:   r;   r#   )r(   r   rz   r-   ry   r*   r0   )r   r   r   diffr   r7   r7   r8   r   n  s   

r   histostepc                 C  s`   t j|ddd}t jt | d| |dd}t t jd|j|jd|d d g}t |ddS )	NrC   truncrounding_moder   r#   r   rN   r   )r*   divcumsumr1   zerosr   r   r0   )r   r   
step_trunclutr7   r7   r8   
_build_lut  s   &r   imc                 C  s0  |   }|  }| dk r$t|tjd|jds$td|  d| dkr@t|tjd|jds@td|  dt| j	}|dvrQt
d| d| d	 } t| d
ddd}t||dk dg}tjt||d  ddd}|dkr| }|d	 S tt||d|   }|| }|d	 S )zScale the data in the channel to implement equalize.

    Args:
        im: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.

    Returns:
        image tensor with the batch in the zero position.

    r:   )r   z?Values in the input tensor must greater or equal to 0.0. Found r   r;   z=Values in the input tensor must lower or equal to 1.0. Found )rC   r   z0Input tensor must have 2 or 3 dimensions. Found r      r   r   )binsr%   r&   rN   r   r   )r%   r&   itemr*   iscloser+   r   rQ   r-   r.   rO   r   r   r   sumgatherr   r   long
reshape_as)r   min_max_ndimsr   nonzero_histor   r   r7   r7   r8   _scale_channel  s&   
$$

r   c                   B   g }| D ] t  fddtt D }|| qt |S )aA  Apply equalize on the input tensor.

    .. image:: _static/img/equalize.png

    Implements Equalize function from PIL using PyTorch ops based on uint8 format:
    https://github.com/tensorflow/tpu/blob/5f71c12a020403f863434e96982a840578fdd127/models/official/efficientnet/autoaugment.py#L355

    Args:
        input: image tensor to equalize with shape :math:`(*, C, H, W)`.

    Returns:
        Equalized image tensor with shape :math:`(*, C, H, W)`.

    Example:
        >>> x = torch.rand(1, 2, 3, 3)
        >>> equalize(x).shape
        torch.Size([1, 2, 3, 3])

    c                   s&   g | ]}t  |d d d d f qS Nr   r   r   r7   r8   rw     s   & zequalize.<locals>.<listcomp>r*   r{   rR   r-   r   )rJ   r   scaled_imager7   r   r8   equalize  s
    
r   c                   r   )a  Equalize the values for a 3D volumetric tensor.

    Implements Equalize function for a sequence of images using PyTorch ops based on uint8 format:
    https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352

    Args:
        input: image tensor with shape :math:`(*, C, D, H, W)` to equalize.

    Returns:
        Equalized volume with shape :math:`(B, C, D, H, W)`.

    c              	     s,   g | ]}t  |d d d d d d f qS r   r   r   volumer7   r8   rw     s   , zequalize3d.<locals>.<listcomp>r   )rJ   r   scaled_inputr7   r   r8   
equalize3d  s
    
r   max_valOptional[Tensor]c                 C  s^   t | tstdtt |du rtdg}n|}t |ts(tdt| || |  S )a  Invert the values of an input image tensor by its maximum value.

    .. image:: _static/img/invert.png

    Args:
        image: The input tensor to invert with an arbitatry shape.
        max_val: The expected maximum value in the input tensor. The shape has to
          according to the input tensor shape, or at least has to work with broadcasting.

    Example:
        >>> img = torch.rand(1, 2, 4, 4)
        >>> invert(img).shape
        torch.Size([1, 2, 4, 4])

        >>> img = 255. * torch.rand(1, 2, 3, 4, 4)
        >>> invert(img, torch.as_tensor(255.)).shape
        torch.Size([1, 2, 3, 4, 4])

        >>> img = torch.rand(1, 3, 4, 4)
        >>> invert(img, torch.as_tensor([[[[1.]]]])).shape
        torch.Size([1, 3, 4, 4])

    zInput is not a Tensor. Got: Nr;   zmax_val is not a Tensor. Got: )r(   r   rz   rD   rJ   r   r,   )r   r   _max_valr7   r7   r8   invert  s   

r   c                      N   e Zd ZU dZg dZded< g dZded< d fd
dZdddZ  Z	S )AdjustSaturationaz  Adjust color saturation of an image.

    The input image is expected to be an RGB image in the range of [0, 1].

    Args:
        saturation_factor: How much to adjust the saturation. 0 will give a black
          and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
        saturation_mode: The mode to adjust saturation.

    Shape:
        - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
        - Output: Adjusted image in the shape of :math:`(*, 3, H, W)`.

    Example:
        >>> x = torch.ones(1, 3, 3, 3)
        >>> AdjustSaturation(2.)(x)
        tensor([[[[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]],
        <BLANKLINE>
                 [[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]],
        <BLANKLINE>
                 [[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]]]])

        >>> x = torch.ones(2, 3, 3, 3)
        >>> y = torch.ones(2)
        >>> out = AdjustSaturation(y)(x)
        >>> torch.nn.functional.mse_loss(x, out)
        tensor(0.)

    rN   r   rN   rN   ClassVar[list[int]]ONNX_DEFAULT_INPUTSHAPEONNX_DEFAULT_OUTPUTSHAPEsaturation_factorr   r   Nonec                      t    || _d S r   super__init__r   selfr   	__class__r7   r8   r   F     

zAdjustSaturation.__init__rJ   r   c                 C     t || jS r   )rB   r   r   rJ   r7   r7   r8   forwardJ     zAdjustSaturation.forwardr   r   r   r   rJ   r   r   r   
__name__
__module____qualname____doc__r   __annotations__r   r   r   __classcell__r7   r7   r   r8   r     s   
 $r   c                      r   )#AdjustSaturationWithGraySubtractiona6  Adjust color saturation of an image.

    This implementation aligns PIL. Hence, the output is close to TorchVision.
    The input image is expected to be in the range of [0, 1].

    The input image is expected to be an RGB or gray image in the range of [0, 1].

    Args:
        saturation_factor: How much to adjust the saturation. 0 will give a black
          and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
        saturation_mode: The mode to adjust saturation.

    Shape:
        - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
        - Output: Adjusted image in the shape of :math:`(*, 3, H, W)`.

    Example:
        >>> x = torch.ones(1, 3, 3, 3)
        >>> AdjustSaturationWithGraySubtraction(2.)(x)
        tensor([[[[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]],
        <BLANKLINE>
                 [[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]],
        <BLANKLINE>
                 [[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]]]])

        >>> x = torch.ones(2, 3, 3, 3)
        >>> y = torch.ones(2)
        >>> out = AdjustSaturationWithGraySubtraction(y)(x)
        >>> torch.nn.functional.mse_loss(x, out)
        tensor(0.)

    r   r   r   r   r   r   r   r   c                   r   r   r   r   r   r7   r8   r   y  r   z,AdjustSaturationWithGraySubtraction.__init__rJ   r   c                 C  r   r   )r>   r   r   r7   r7   r8   r   }  r   z+AdjustSaturationWithGraySubtraction.forwardr   r   r   r7   r7   r   r8   r   N     
 'r   c                      r   )	AdjustHuea9  Adjust hue of an image.

    This implementation aligns PIL. Hence, the output is close to TorchVision.
    The input image is expected to be in the range of [0, 1].

    The input image is expected to be an RGB image in the range of [0, 1].

    Args:
        hue_factor: How much to shift the hue channel. Should be in [-PI, PI]. PI
          and -PI give complete reversal of hue channel in HSV space in positive and negative
          direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
          image with complementary colors while 0 gives the original image.

    Shape:
        - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
        - Output: Adjusted image in the shape of :math:`(*, 3, H, W)`.

    Example:
        >>> x = torch.ones(1, 3, 3, 3)
        >>> AdjustHue(3.141516)(x)
        tensor([[[[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]],
        <BLANKLINE>
                 [[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]],
        <BLANKLINE>
                 [[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]]]])

        >>> x = torch.ones(2, 3, 3, 3)
        >>> y = torch.ones(2) * 3.141516
        >>> AdjustHue(y)(x).shape
        torch.Size([2, 3, 3, 3])

    r   r   r   r   
hue_factorr   r   r   c                   r   r   )r   r   r   )r   r   r   r7   r8   r     r   zAdjustHue.__init__rJ   r   c                 C  r   r   )rI   r   r   r7   r7   r8   r     r   zAdjustHue.forward)r   r   r   r   r   r   r7   r7   r   r8   r     r   r   c                      s.   e Zd ZdZdd fdd	ZdddZ  ZS )AdjustGammaaj  Perform gamma correction on an image.

    The input image is expected to be in the range of [0, 1].

    Args:
        gamma: Non negative real number, same as y\gammay in the equation.
          gamma larger than 1 make the shadows darker, while gamma smaller than 1 make
          dark regions lighter.
        gain: The constant multiplier.

    Shape:
        - Input: Image to be adjusted in the shape of :math:`(*, N)`.
        - Output: Adjusted image in the shape of :math:`(*, N)`.

    Example:
        >>> x = torch.ones(1, 1, 3, 3)
        >>> AdjustGamma(1.0, 2.0)(x)
        tensor([[[[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y1 = torch.ones(2) * 1.0
        >>> y2 = torch.ones(2) * 2.0
        >>> AdjustGamma(y1, y2)(x).shape
        torch.Size([2, 5, 3, 3])

    r;   rK   r   rL   r   r   c                   s   t    || _|| _d S r   )r   r   rK   rL   )r   rK   rL   r   r7   r8   r     s   

zAdjustGamma.__init__rJ   r   c                 C  s   t || j| jS r   )rW   rK   rL   r   r7   r7   r8   r     s   zAdjustGamma.forwardr;   )rK   r   rL   r   r   r   r   r   r   r   r   r   r   r   r7   r7   r   r8   r    s    r  c                      ,   e Zd ZdZd fddZdd
dZ  ZS )AdjustContrasta  Adjust Contrast of an image.

    This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
    The input image is expected to be in the range of [0, 1].

    Args:
        contrast_factor: Contrast adjust factor per element
          in the batch. 0 generates a completely black image, 1 does not modify
          the input image while any other non-negative number modify the
          brightness by this factor.

    Shape:
        - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.
        - Output: Adjusted image in the shape of :math:`(*, N)`.

    Example:
        >>> x = torch.ones(1, 1, 3, 3)
        >>> AdjustContrast(0.5)(x)
        tensor([[[[0.5000, 0.5000, 0.5000],
                  [0.5000, 0.5000, 0.5000],
                  [0.5000, 0.5000, 0.5000]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y = torch.ones(2)
        >>> AdjustContrast(y)(x).shape
        torch.Size([2, 5, 3, 3])

    contrast_factorr   r   r   c                   r   r   r   r   r  r   r  r   r7   r8   r     r   zAdjustContrast.__init__rJ   r   c                 C  r   r   )r\   r  r   r7   r7   r8   r     r   zAdjustContrast.forwardr  r   r   r   r   r  r7   r7   r   r8   r    s    r  c                      r  )!AdjustContrastWithMeanSubtractiona  Adjust Contrast of an image.

    This implementation aligns PIL. Hence, the output is close to TorchVision.
    The input image is expected to be in the range of [0, 1].

    Args:
        contrast_factor: Contrast adjust factor per element
          in the batch by subtracting its mean grayscaled version.
          0 generates a completely black image, 1 does not modify
          the input image while any other non-negative number modify the
          brightness by this factor.

    Shape:
        - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.
        - Output: Adjusted image in the shape of :math:`(*, N)`.

    Example:
        >>> x = torch.ones(1, 1, 3, 3)
        >>> AdjustContrastWithMeanSubtraction(0.5)(x)
        tensor([[[[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y = torch.ones(2)
        >>> AdjustContrastWithMeanSubtraction(y)(x).shape
        torch.Size([2, 5, 3, 3])

    r  r   r   r   c                   r   r   r  r  r   r7   r8   r      r   z*AdjustContrastWithMeanSubtraction.__init__rJ   r   c                 C  r   r   )r`   r  r   r7   r7   r8   r   $  r   z)AdjustContrastWithMeanSubtraction.forwardr	  r   r  r7   r7   r   r8   r
    s    r
  c                      r  )AdjustBrightnessaa  Adjust Brightness of an image.

    This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
    The input image is expected to be in the range of [0, 1].

    Args:
        brightness_factor: Brightness adjust factor per element
          in the batch. 0 does not modify the input image while any other number modify the
          brightness.

    Shape:
        - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.
        - Output: Adjusted image in the shape of :math:`(*, N)`.

    Example:
        >>> x = torch.ones(1, 1, 3, 3)
        >>> AdjustBrightness(1.)(x)
        tensor([[[[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y = torch.ones(2)
        >>> AdjustBrightness(y)(x).shape
        torch.Size([2, 5, 3, 3])

    brightness_factorr   r   r   c                   r   r   r   r   r  r   r  r   r7   r8   r   E  r   zAdjustBrightness.__init__rJ   r   c                 C  r   r   )rb   r  r   r7   r7   r8   r   I  r   zAdjustBrightness.forwardr  r   r   r   r   r  r7   r7   r   r8   r  (      r  c                      .   e Zd ZdZdd fddZdddZ  ZS )AdjustSigmoida  Adjust the contrast of an image tensor or performs sigmoid correction on the input image tensor.

    The input image is expected to be in the range of [0, 1].

    Reference:
        [1]: Gustav J. Braun, "Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions",
             http://markfairchild.org/PDFs/PAP07.pdf

    Args:
        image: Image to be adjusted in the shape of :math:`(*, H, W)`.
        cutoff: The cutoff of sigmoid function.
        gain: The multiplier of sigmoid function.
        inv: If is set to True the function will return the negative sigmoid correction.

    Example:
        >>> x = torch.ones(1, 1, 2, 2)
        >>> AdjustSigmoid(gain=0)(x)
        tensor([[[[0.5000, 0.5000],
                  [0.5000, 0.5000]]]])

    rd   re   Frf   r)   rL   rg   rY   r   r   c                       t    || _|| _|| _d S r   )r   r   rf   rL   rg   )r   rf   rL   rg   r   r7   r8   r   d     

zAdjustSigmoid.__init__r   r   c                 C     t || j| j| jdS )N)rf   rL   rg   )ri   rf   rL   rg   r   r   r7   r7   r8   r   j     zAdjustSigmoid.forwardrd   re   F)rf   r)   rL   r)   rg   rY   r   r   r   r   r   r   r  r7   r7   r   r8   r  M  s    r  c                      r  )	AdjustLoga  Adjust log correction on the input image tensor.

    The input image is expected to be in the range of [0, 1].

    Reference:
    [1]: http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf

    Args:
        image: Image to be adjusted in the shape of :math:`(*, H, W)`.
        gain: The multiplier of logarithmic function.
        inv:  If is set to True the function will return the inverse logarithmic correction.
        clip_output: Whether to clip the output image with range of [0, 1].

    Example:
        >>> x = torch.zeros(1, 1, 2, 2)
        >>> AdjustLog(inv=True)(x)
        tensor([[[[0., 0.],
                  [0., 0.]]]])

    r#   FTrL   r)   rg   rY   rX   r   r   c                   r  r   )r   r   rL   rg   rX   )r   rL   rg   rX   r   r7   r8   r     r  zAdjustLog.__init__r   r   c                 C  r  )N)rL   rg   rX   )rk   rL   rg   rX   r  r7   r7   r8   r     r  zAdjustLog.forwardr#   FT)rL   r)   rg   rY   rX   rY   r   r   r  r  r7   r7   r   r8   r  n  s    r  c                      r  )AdjustBrightnessAccumulativea{  Adjust Brightness of an image accumulatively.

    This implementation aligns PIL. Hence, the output is close to TorchVision.
    The input image is expected to be in the range of [0, 1].

    Args:
        brightness_factor: Brightness adjust factor per element
          in the batch. 0 does not modify the input image while any other number modify the
          brightness.

    Shape:
        - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.
        - Output: Adjusted image in the shape of :math:`(*, N)`.

    Example:
        >>> x = torch.ones(1, 1, 3, 3)
        >>> AdjustBrightnessAccumulative(1.)(x)
        tensor([[[[1., 1., 1.],
                  [1., 1., 1.],
                  [1., 1., 1.]]]])

        >>> x = torch.ones(2, 5, 3, 3)
        >>> y = torch.ones(2)
        >>> AdjustBrightnessAccumulative(y)(x).shape
        torch.Size([2, 5, 3, 3])

    r  r   r   r   c                   r   r   r  r  r   r7   r8   r     r   z%AdjustBrightnessAccumulative.__init__rJ   r   c                 C  r   r   )rc   r  r   r7   r7   r8   r     r   z$AdjustBrightnessAccumulative.forwardr  r   r  r7   r7   r   r8   r    r  r  c                      s.   e Zd ZdZdd fddZdddZ  ZS )Inverta  Invert the values of an input tensor by its maximum value.

    Args:
        input: The input tensor to invert with an arbitatry shape.
        max_val: The expected maximum value in the input tensor. The shape has to
          according to the input tensor shape, or at least has to work with broadcasting. Default: 1.0.

    Example:
        >>> img = torch.rand(1, 2, 4, 4)
        >>> Invert()(img).shape
        torch.Size([1, 2, 4, 4])

        >>> img = 255. * torch.rand(1, 2, 3, 4, 4)
        >>> Invert(torch.as_tensor(255.))(img).shape
        torch.Size([1, 2, 3, 4, 4])

        >>> img = torch.rand(1, 3, 4, 4)
        >>> Invert(torch.as_tensor([[[[1.]]]]))(img).shape
        torch.Size([1, 3, 4, 4])

    Nr   r   r   r   c                   s@   t    |d u rtd}t|ts| d| d S || _d S )Nr;   r   )r   r   r*   r   r(   r   register_bufferr   )r   r   r   r7   r8   r     s   



zInvert.__init__rJ   r   c                 C  r   r   )r   r   r   r7   r7   r8   r     r   zInvert.forwardr   )r   r   r   r   r   r  r7   r7   r   r8   r    s    	r  )r   r   r   r   r   r   r  )rJ   r   rK   r   rL   r   r   r   )T)r   r   r   r   rX   rY   r   r   r  )
r   r   rf   r)   rL   r)   rg   rY   r   r   r  )
r   r   rL   r)   rg   rY   rX   rY   r   r   )rd   )rJ   r   rl   r   r   r   )rd   N)rJ   r   rl   r   r~   r   r   r   )rJ   r   r   r   r   r   )rJ   r   r   r   r   r   )r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   )=
__future__r   mathr   typingr   r   r   r*   kornia.colorr   r   r	   kornia.corer
   Moduler   r   r   kornia.core.checkr   r   r   kornia.utils.helpersr   kornia.utils.imager   r   r9   r>   rB   rH   rI   rW   r\   r`   rb   rc   ri   rk   r}   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r
  r  r  r  r  r  r7   r7   r7   r8   <module>   sb   


9
*
!+H
D:D5"&!EX
7

*%033'&'%! %