a
    áñh<ª  ã                
   @   sâ  d dl Z d dlZd dlZd dlmZmZ d dlZd dlm	Z	 d dl
Z
d dl
mZ d dlmZmZ zd dlZW n ey‚   dZY n0 ddlmZ ddlmZ ejZejZeee d	œd
d„Zeed	œdd„Ze
jjeed	œdd„ƒZe
jjeed	œdd„ƒZdd„ Z dd„ Z!e
j"fe
je
j#e
jdœdd„Z$dedd„Z%dfeee" ee" eedœdd„Z&e	j'feee eedœd d!„Z(d"d#„ Z)dgeee ee*ed%œd&d'„Z+eeeeeed(œd)d*„Z,eee ed+œd,d-„Z-e	j'feeeeeee eed.œd/d0„Z.eed	œd1d2„Z/eee  eee  ee" d3œd4d5„Z0dheeee  eee  eee ed7œd8d9„Z1eed	œd:d;„Z2eee eeeeeef d<œd=d>„Z3dieee eee d?œd@dA„Z4ee"edBœdCdD„Z5ee"edEœdFdG„Z6ee"edHœdIdJ„Z7ee"edKœdLdM„Z8djee"e"edNœdOdP„Z9ee" e"ee" e"ee" ee" dQœdRdS„Z:dkee"eeeee  ee edTœdUdV„Z;dlee"ee e"ee" eee edWœdXdY„Z<e
jjdmdZd[„ƒZ=dneeed\œd]d^„Z>doeeeeeeeed_œd`da„Z?dpeee eee"  edbœdcdd„Z@dS )qé    N)ÚAnyÚOptional)ÚImage)ÚTensor)ÚListÚTupleé   )Úfunctional_pil)Úfunctional_tensor)ÚimgÚreturnc                 C   s    t | tjƒrt | ¡S t | ¡S )z"Returns image sizea as (w, h)
    )Ú
isinstanceÚtorchr   ÚF_tÚ_get_image_sizeÚF_pil©r   © r   úa/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchvision/transforms/functional.pyr      s    
r   c                 C   s    t | tjƒrt | ¡S t | ¡S ©N)r   r   r   r   Ú_get_image_num_channelsr   r   r   r   r   r   #   s    
r   c                 C   s   t | tjƒS r   )r   ÚnpÚndarrayr   r   r   r   Ú	_is_numpy*   s    r   c                 C   s
   | j dv S )N¾   é   é   )Úndimr   r   r   r   Ú_is_numpy_image/   s    r   c                 C   sì  t  | ¡s$t| ƒs$td t| ƒ¡ƒ‚t| ƒrDt| ƒsDtd | j¡ƒ‚t	| t
jƒr¢| jdkrp| dd…dd…df } t |  d¡¡ ¡ }t	|tjƒrž| ¡  d¡S |S tduræt	| tjƒræt
j| j| j| jgt
jd�}|  |¡ t |¡S | jdk�rt t
j| t
jd	d
�¡}nŒ| jdk�r2t t
j| t
jd	d
�¡}nf| jdk�rXt t
j| t
jd	d
�¡}n@| jdk�r‚dt t
j| t
jd	d
�¡ }nt tj  !|  "¡ ¡¡}| #| j$d | j$d t%|  &¡ ƒ¡}| 'd¡ ¡ }t	|tjƒ�rä| ¡  d¡S |S dS )zéConvert a ``PIL Image`` or ``numpy.ndarray`` to tensor.

    See ``ToTensor`` for more details.

    Args:
        pic (PIL Image or numpy.ndarray): Image to be converted to tensor.

    Returns:
        Tensor: Converted image.
    z*pic should be PIL Image or ndarray. Got {}ú1pic should be 2/3 dimensional. Got {} dimensions.r   N©r   r   r   éÿ   ©ÚdtypeÚIF)ÚcopyúI;16ÚFÚ1r   r   )(r   Ú_is_pil_imager   Ú	TypeErrorÚformatÚtyper   Ú
ValueErrorr   r   r   r   r   Z
from_numpyÚ	transposeÚ
contiguousZ
ByteTensorÚfloatÚdivÚaccimager   ÚzerosÚchannelsÚheightÚwidthÚfloat32ÚcopytoÚmodeÚarrayÚint32Úint16Úuint8ZByteStorageÚfrom_bufferÚtobytesÚviewÚsizeÚlenÚgetbandsÚpermute)Úpicr   Únppicr   r   r   Ú	to_tensor4   s:    


"rG   c                 C   s    t  | ¡std t| ƒ¡ƒ‚tdur`t| tjƒr`tj	| j
| j| jgtjd�}|  |¡ t |¡S t t | ¡¡}| | jd | jd t|  ¡ ƒ¡}| d¡}|S )zöConvert a ``PIL Image`` to a tensor of the same type.

    See :class:`~torchvision.transforms.PILToTensor` for more details.

    Args:
        pic (PIL Image): Image to be converted to tensor.

    Returns:
        Tensor: Converted image.
    zpic should be PIL Image. Got {}Nr"   r   r   r    )r   r)   r*   r+   r,   r2   r   r   r   r3   r4   r5   r6   r7   r8   r   Ú	as_tensorZasarrayr@   rA   rB   rC   rD   )rE   rF   r   r   r   r   Úpil_to_tensork   s    


"
rI   )Úimager#   r   c                 C   s    t | tjƒstdƒ‚t | |¡S )aW  Convert a tensor image to the given ``dtype`` and scale the values accordingly

    Args:
        image (torch.Tensor): Image to be converted
        dtype (torch.dtype): Desired data type of the output

    Returns:
        Tensor: Converted image

    .. note::

        When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly.
        If converted back and forth, this mismatch has no effect.

    Raises:
        RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as
            well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to
            overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range
            of the integer ``dtype``.
    z Input img should be Tensor Image)r   r   r   r*   r   Úconvert_image_dtype)rJ   r#   r   r   r   rK   †   s    rK   c                 C   sÖ  t | tjƒs,t | tjƒs,td t| ƒ¡ƒ‚n‚t | tjƒrp|  ¡ dvrXt	d |  ¡ ¡ƒ‚q®|  ¡ dkr®|  
d¡} n>t | tjƒr®| jdvr˜t	d | j¡ƒ‚n| jdkr®t | d¡} | }t | tjƒrð|  ¡ rÜ|dkrÜ|  d¡ ¡ } t |  ¡  ¡ d¡}t |tjƒ�std	d
 t|ƒ¡ ƒ‚|jd dk�rºd}|dd…dd…df }|jtjk�rRd}n:|jtjk�rfd}n&|jtjk�rzd}n|jtjk�rŒd}|du�r´||k�r´t	d |tj|¡ƒ‚|}nô|jd dk�rdg}|du�rò||v�ròt	d |¡ƒ‚|du �r®|jtjk�r®d}nž|jd dk�rhg d¢}|du�rJ||v�rJt	d |¡ƒ‚|du �r®|jtjk�r®d}nFg d¢}|du�r’||v�r’t	d |¡ƒ‚|du �r®|jtjk�r®d}|du �rÈtd |j¡ƒ‚tj||d�S )aË  Convert a tensor or an ndarray to PIL Image.

    See :class:`~torchvision.transforms.ToPILImage` for more details.

    Args:
        pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
        mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).

    .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes

    Returns:
        PIL Image: Image converted to PIL Image.
    z(pic should be Tensor or ndarray. Got {}.r   r   r   r   r'   r!   )r   r   r   z3Input pic must be a torch.Tensor or NumPy ndarray, znot {}r   NÚLr&   r$   z<Incorrect mode ({}) supplied for input type {}. Should be {}ZLAz)Only modes {} are supported for 2D inputsé   )ÚRGBAZCMYKZRGBXz)Only modes {} are supported for 4D inputsrN   )ÚRGBZYCbCrZHSVz)Only modes {} are supported for 3D inputsrO   zInput type {} is not supported)r9   )r   r   r   r   r   r*   r+   r,   Z
ndimensionr-   Z	unsqueezer   Zexpand_dimsZis_floating_pointÚmulÚbyter.   ÚcpuÚnumpyÚshaper#   r=   r<   r;   r7   r   Z	fromarray)rE   r9   ZnpimgZexpected_modeZpermitted_2_channel_modesZpermitted_4_channel_modesZpermitted_3_channel_modesr   r   r   Úto_pil_image¡   sr    

ÿÿ
rU   F)ÚtensorÚmeanÚstdÚinplacer   c                 C   sÎ   t | tjƒstd t| ƒ¡ƒ‚| jdk r:td |  ¡ ¡ƒ‚|sF|  	¡ } | j
}tj||| jd�}tj||| jd�}|dk ¡ rŠtd |¡ƒ‚|jdkr¢| ddd¡}|jdkrº| ddd¡}|  |¡ |¡ | S )	a]  Normalize a tensor image with mean and standard deviation.

    .. note::
        This transform acts out of place by default, i.e., it does not mutates the input tensor.

    See :class:`~torchvision.transforms.Normalize` for more details.

    Args:
        tensor (Tensor): Tensor image of size (C, H, W) or (B, C, H, W) to be normalized.
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channel.
        inplace(bool,optional): Bool to make this operation inplace.

    Returns:
        Tensor: Normalized Tensor image.
    z.Input tensor should be a torch tensor. Got {}.r   zTExpected tensor to be a tensor image of size (..., C, H, W). Got tensor.size() = {}.)r#   Údevicer   zJstd evaluated to zero after conversion to {}, leading to division by zero.r   éÿÿÿÿ)r   r   r   r*   r+   r,   r   r-   rA   Úcloner#   rH   rZ   Úanyr@   Zsub_Zdiv_)rV   rW   rX   rY   r#   r   r   r   Ú	normalizeø   s&    
ÿ

r^   )r   rA   Úinterpolationr   c                 C   s,   t | tjƒstj| ||d�S tj| ||d�S )aˆ  Resize the input image to the given size.
    The image can be a PIL Image or a torch Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    Args:
        img (PIL Image or Tensor): Image to be resized.
        size (sequence or int): Desired output size. If size is a sequence like
            (h, w), the output size will be matched to this. If size is an int,
            the smaller edge of the image will be matched to this number maintaining
            the aspect ratio. i.e, if height > width, then image will be rescaled to
            :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`.
            In torchscript mode size as single int is not supported, use a tuple or
            list of length 1: ``[size, ]``.
        interpolation (int, optional): Desired interpolation enum defined by `filters`_.
            Default is ``PIL.Image.BILINEAR``. If input is Tensor, only ``PIL.Image.NEAREST``, ``PIL.Image.BILINEAR``
            and ``PIL.Image.BICUBIC`` are supported.

    Returns:
        PIL Image or Tensor: Resized image.
    )rA   r_   )r   r   r   r   Úresizer   )r   rA   r_   r   r   r   r`      s    r`   c                  O   s   t  d¡ t| i |¤ŽS )Nz^The use of the transforms.Scale transform is deprecated, please use transforms.Resize instead.)ÚwarningsÚwarnr`   )ÚargsÚkwargsr   r   r   Úscale;  s    
re   Úconstant)r   ÚpaddingÚfillÚpadding_moder   c                 C   s0   t | tjƒstj| |||d�S tj| |||d�S )aÆ  Pad the given image on all sides with the given "pad" value.
    The image can be a PIL Image or a torch Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    Args:
        img (PIL Image or Tensor): Image to be padded.
        padding (int or tuple or list): Padding on each border. If a single int is provided this
            is used to pad all borders. If tuple of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a tuple of length 4 is provided
            this is the padding for the left, top, right and bottom borders respectively.
            In torchscript mode padding as single int is not supported, use a tuple or
            list of length 1: ``[padding, ]``.
        fill (int or str or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
            length 3, it is used to fill R, G, B channels respectively.
            This value is only used when the padding_mode is constant. Only int value is supported for Tensors.
        padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
            Mode symmetric is not yet supported for Tensor inputs.

            - constant: pads with a constant value, this value is specified with fill

            - edge: pads with the last value on the edge of the image

            - reflect: pads with reflection of image (without repeating the last value on the edge)

                       padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
                       will result in [3, 2, 1, 2, 3, 4, 3, 2]

            - symmetric: pads with reflection of image (repeating the last value on the edge)

                         padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
                         will result in [2, 1, 1, 2, 3, 4, 4, 3]

    Returns:
        PIL Image or Tensor: Padded image.
    )rg   rh   ri   )r   r   r   r   Úpadr   )r   rg   rh   ri   r   r   r   rj   A  s    $rj   )r   ÚtopÚleftr5   r6   r   c                 C   s0   t | tjƒst | ||||¡S t | ||||¡S )aŽ  Crop the given image at specified location and output size.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading
    dimensions

    Args:
        img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
        top (int): Vertical component of the top left corner of the crop box.
        left (int): Horizontal component of the top left corner of the crop box.
        height (int): Height of the crop box.
        width (int): Width of the crop box.

    Returns:
        PIL Image or Tensor: Cropped image.
    )r   r   r   r   Úcropr   )r   rk   rl   r5   r6   r   r   r   rm   k  s    rm   )r   Úoutput_sizer   c                 C   s”   t |tjƒrt|ƒt|ƒf}n*t |ttfƒrHt|ƒdkrH|d |d f}t| ƒ\}}|\}}t|| d d ƒ}t|| d d ƒ}t| ||||ƒS )aá  Crops the given image at the center.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    Args:
        img (PIL Image or Tensor): Image to be cropped.
        output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int
            it is used for both directions.

    Returns:
        PIL Image or Tensor: Cropped image.
    r   r   ç      à?)	r   ÚnumbersÚNumberÚintÚtupleÚlistrB   r   rm   )r   rn   Úimage_widthÚimage_heightÚcrop_heightÚ
crop_widthZcrop_topZ	crop_leftr   r   r   Úcenter_crop‚  s    ry   )r   rk   rl   r5   r6   rA   r_   r   c                 C   s    t | ||||ƒ} t| ||ƒ} | S )a!  Crop the given image and resize it to desired size.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    Notably used in :class:`~torchvision.transforms.RandomResizedCrop`.

    Args:
        img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
        top (int): Vertical component of the top left corner of the crop box.
        left (int): Horizontal component of the top left corner of the crop box.
        height (int): Height of the crop box.
        width (int): Width of the crop box.
        size (sequence or int): Desired output size. Same semantics as ``resize``.
        interpolation (int, optional): Desired interpolation enum defined by `filters`_.
            Default is ``PIL.Image.BILINEAR``. If input is Tensor, only ``PIL.Image.NEAREST``, ``PIL.Image.BILINEAR``
            and ``PIL.Image.BICUBIC`` are supported.
    Returns:
        PIL Image or Tensor: Cropped image.
    )rm   r`   )r   rk   rl   r5   r6   rA   r_   r   r   r   Úresized_crop¢  s    rz   c                 C   s    t | tjƒst | ¡S t | ¡S )al  Horizontally flip the given PIL Image or Tensor.

    Args:
        img (PIL Image or Tensor): Image to be flipped. If img
            is a Tensor, it is expected to be in [..., H, W] format,
            where ... means it can have an arbitrary number of trailing
            dimensions.

    Returns:
        PIL Image or Tensor:  Horizontally flipped image.
    )r   r   r   r   Úhflipr   r   r   r   r   r{   ½  s    
r{   )ÚstartpointsÚ	endpointsr   c           	      C   s  t jdt| ƒ dt jd�}tt|| ƒƒD ]¬\}\}}t  |d |d dddd|d  |d  |d  |d  g¡|d| dd…f< t  ddd|d |d d|d  |d  |d  |d  g¡|d| d dd…f< q(t j| t jd� d¡}t  ||¡d }| 	d¡ 
¡ }|S )a
  Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.

    In Perspective Transform each pixel (x, y) in the original image gets transformed as,
     (x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) )

    Args:
        startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
            ``[top-left, top-right, bottom-right, bottom-left]`` of the original image.
        endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
            ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image.

    Returns:
        octuple (a, b, c, d, e, f, g, h) for transforming each pixel.
    r   é   r"   r   r   N)r   r3   rB   r0   Ú	enumerateÚziprV   r@   ZlstsqZsqueezeÚtolist)	r|   r}   Za_matrixÚiÚp1Úp2Zb_matrixÚresÚoutputr   r   r   Ú_get_perspective_coeffsÏ  s    NTr‡   r   )r   r|   r}   r_   rh   r   c                 C   s:   t ||ƒ}t| tjƒs(tj| |||d�S tj| |||d�S )a@  Perform perspective transform of the given image.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.

    Args:
        img (PIL Image or Tensor): Image to be transformed.
        startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
            ``[top-left, top-right, bottom-right, bottom-left]`` of the original image.
        endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
            ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image.
        interpolation (int): Interpolation type. If input is Tensor, only ``PIL.Image.NEAREST`` and
            ``PIL.Image.BILINEAR`` are supported. Default, ``PIL.Image.BILINEAR`` for PIL images and Tensors.
        fill (n-tuple or int or float): Pixel fill value for area outside the rotated
            image. If int or float, the value is used for all bands respectively.
            This option is only available for ``pillow>=5.0.0``. This option is not supported for Tensor
            input. Fill value for the area outside the transform in the output image is always 0.

    Returns:
        PIL Image or Tensor: transformed Image.
    )r_   rh   )r‡   r   r   r   r   Úperspectiver   )r   r|   r}   r_   rh   Zcoeffsr   r   r   rˆ   í  s    
rˆ   c                 C   s    t | tjƒst | ¡S t | ¡S )ad  Vertically flip the given PIL Image or torch Tensor.

    Args:
        img (PIL Image or Tensor): Image to be flipped. If img
            is a Tensor, it is expected to be in [..., H, W] format,
            where ... means it can have an arbitrary number of trailing
            dimensions.

    Returns:
        PIL Image:  Vertically flipped image.
    )r   r   r   r   Úvflipr   r   r   r   r   r‰     s    
r‰   )r   rA   r   c                 C   s  t |tjƒrt|ƒt|ƒf}n*t |ttfƒrHt|ƒdkrH|d |d f}t|ƒdkr\tdƒ‚t| ƒ\}}|\}}||ks€||kr˜d}t| 	|||f¡ƒ‚t
| dd||ƒ}t
| d|| ||ƒ}t
| || d||ƒ}	t
| || || ||ƒ}
t| ||gƒ}|||	|
|fS )aj  Crop the given image into four corners and the central crop.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    .. Note::
        This transform returns a tuple of images and there may be a
        mismatch in the number of inputs and targets your ``Dataset`` returns.

    Args:
        img (PIL Image or Tensor): Image to be cropped.
        size (sequence or int): Desired output size of the crop. If size is an
            int instead of sequence like (h, w), a square crop (size, size) is
            made. If provided a tuple or list of length 1, it will be interpreted as (size[0], size[0]).

    Returns:
       tuple: tuple (tl, tr, bl, br, center)
                Corresponding top left, top right, bottom left, bottom right and center crop.
    r   r   r   ú3Please provide only two dimensions (h, w) for size.z3Requested crop size {} is bigger than input size {})r   rp   rq   rr   rs   rt   rB   r-   r   r+   rm   ry   )r   rA   ru   rv   rw   rx   ÚmsgÚtlÚtrÚblÚbrÚcenterr   r   r   Ú	five_crop#  s"    r‘   )r   rA   Úvertical_flipr   c                 C   sŽ   t |tjƒrt|ƒt|ƒf}n*t |ttfƒrHt|ƒdkrH|d |d f}t|ƒdkr\tdƒ‚t| |ƒ}|rtt	| ƒ} nt
| ƒ} t| |ƒ}|| S )a’  Generate ten cropped images from the given image.
    Crop the given image into four corners and the central crop plus the
    flipped version of these (horizontal flipping is used by default).
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    .. Note::
        This transform returns a tuple of images and there may be a
        mismatch in the number of inputs and targets your ``Dataset`` returns.

    Args:
        img (PIL Image or Tensor): Image to be cropped.
        size (sequence or int): Desired output size of the crop. If size is an
            int instead of sequence like (h, w), a square crop (size, size) is
            made. If provided a tuple or list of length 1, it will be interpreted as (size[0], size[0]).
        vertical_flip (bool): Use vertical flipping instead of horizontal

    Returns:
        tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip)
            Corresponding top left, top right, bottom left, bottom right and
            center crop and same for the flipped image.
    r   r   r   rŠ   )r   rp   rq   rr   rs   rt   rB   r-   r‘   r‰   r{   )r   rA   r’   Z
first_fiveZsecond_fiver   r   r   Úten_cropN  s    


r“   )r   Úbrightness_factorr   c                 C   s$   t | tjƒst | |¡S t | |¡S )a‘  Adjust brightness of an Image.

    Args:
        img (PIL Image or Tensor): Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL Image or Tensor: Brightness adjusted image.
    )r   r   r   r   Úadjust_brightnessr   )r   r”   r   r   r   r•   x  s    r•   )r   Úcontrast_factorr   c                 C   s$   t | tjƒst | |¡S t | |¡S )a‹  Adjust contrast of an Image.

    Args:
        img (PIL Image or Tensor): Image to be adjusted.
        contrast_factor (float): How much to adjust the contrast. Can be any
            non negative number. 0 gives a solid gray image, 1 gives the
            original image while 2 increases the contrast by a factor of 2.

    Returns:
        PIL Image or Tensor: Contrast adjusted image.
    )r   r   r   r   Úadjust_contrastr   )r   r–   r   r   r   r—   Š  s    r—   )r   Úsaturation_factorr   c                 C   s$   t | tjƒst | |¡S t | |¡S )aŒ  Adjust color saturation of an image.

    Args:
        img (PIL Image or Tensor): Image to be adjusted.
        saturation_factor (float):  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.

    Returns:
        PIL Image or Tensor: Saturation adjusted image.
    )r   r   r   r   Úadjust_saturationr   )r   r˜   r   r   r   r™   œ  s    r™   )r   Ú
hue_factorr   c                 C   s$   t | tjƒst | |¡S t | |¡S )aŽ  Adjust hue of an image.

    The image hue is adjusted by converting the image to HSV and
    cyclically shifting the intensities in the hue channel (H).
    The image is then converted back to original image mode.

    `hue_factor` is the amount of shift in H channel and must be in the
    interval `[-0.5, 0.5]`.

    See `Hue`_ for more details.

    .. _Hue: https://en.wikipedia.org/wiki/Hue

    Args:
        img (PIL Image or Tensor): Image to be adjusted.
        hue_factor (float):  How much to shift the hue channel. Should be in
            [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in
            HSV space in positive and negative direction respectively.
            0 means no shift. Therefore, both -0.5 and 0.5 will give an image
            with complementary colors while 0 gives the original image.

    Returns:
        PIL Image or Tensor: Hue adjusted image.
    )r   r   r   r   Ú
adjust_huer   )r   rš   r   r   r   r›   ®  s    r›   )r   ÚgammaÚgainr   c                 C   s(   t | tjƒst | ||¡S t | ||¡S )a!  Perform gamma correction on an image.

    Also known as Power Law Transform. Intensities in RGB mode are adjusted
    based on the following equation:

    .. math::
        I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma}

    See `Gamma Correction`_ for more details.

    .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction

    Args:
        img (PIL Image or Tensor): PIL Image to be adjusted.
        gamma (float): Non negative real number, same as :math:`\gamma` in the equation.
            gamma larger than 1 make the shadows darker,
            while gamma smaller than 1 make dark regions lighter.
        gain (float): The constant multiplier.
    Returns:
        PIL Image or Tensor: Gamma correction adjusted image.
    )r   r   r   r   Úadjust_gammar   )r   rœ   r�   r   r   r   rž   Í  s    rž   )r�   ÚangleÚ	translatere   Úshearr   c                    sb  t  |¡}dd„ |D ƒ\}}| \}}	|\}
}t  || ¡t  |¡ }t  || ¡ t  |¡ t  |¡ t  |¡ }t  || ¡t  |¡ }t  || ¡ t  |¡ t  |¡ t  |¡ }|| d| |dg}‡ fdd„|D ƒ}|d  |d | |
  |d |	 |   7  < |d  |d	 | |
  |d
 |	 |   7  < |d  |7  < |d  |	7  < |S )Nc                 S   s   g | ]}t  |¡‘qS r   )ÚmathÚradians)Ú.0Úsr   r   r   Ú
<listcomp>   ó    z._get_inverse_affine_matrix.<locals>.<listcomp>ç        c                    s   g | ]}|ˆ  ‘qS r   r   )r¤   Úx©re   r   r   r¦     r§   r   r   r   é   r   rM   )r¢   r£   ÚcosÚtanÚsin)r�   rŸ   r    re   r¡   ZrotZsxZsyZcxÚcyZtxÚtyÚaÚbÚcÚdÚmatrixr   rª   r   Ú_get_inverse_affine_matrixé  s    
..00r¶   )r   rŸ   ÚresampleÚexpandr�   rh   r   c           	      C   s°   t |ttfƒstdƒ‚|dur4t |ttfƒs4tdƒ‚t | tjƒsVtj	| |||||d�S ddg}|dur‚t
| ƒ}dd„ t||ƒD ƒ}t|| ddgdddgƒ}tj	| ||||d	�S )
a‘  Rotate the image by angle.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.

    Args:
        img (PIL Image or Tensor): image to be rotated.
        angle (float or int): rotation angle value in degrees, counter-clockwise.
        resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC``, optional):
            An optional resampling filter. See `filters`_ for more information.
            If omitted, or if the image has mode "1" or "P", it is set to ``PIL.Image.NEAREST``.
        expand (bool, optional): Optional expansion flag.
            If true, expands the output image to make it large enough to hold the entire rotated image.
            If false or omitted, make the output image the same size as the input image.
            Note that the expand flag assumes rotation around the center and no translation.
        center (list or tuple, optional): Optional center of rotation. Origin is the upper left corner.
            Default is the center of the image.
        fill (n-tuple or int or float): Pixel fill value for area outside the rotated
            image. If int or float, the value is used for all bands respectively.
            Defaults to 0 for all bands. This option is only available for ``pillow>=5.2.0``.
            This option is not supported for Tensor input. Fill value for the area outside the transform in the output
            image is always 0.

    Returns:
        PIL Image or Tensor: Rotated image.

    .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters

    ú%Argument angle should be int or floatNz$Argument center should be a sequence)rŸ   r·   r¸   r�   rh   r¨   c                 S   s    g | ]\}}d ||d   ‘qS )ç      ð?ro   r   )r¤   r³   r¥   r   r   r   r¦   H  r§   zrotate.<locals>.<listcomp>rº   )rµ   r·   r¸   rh   )r   rr   r0   r*   rt   rs   r   r   r   Úrotater   r€   r¶   r   )	r   rŸ   r·   r¸   r�   rh   Zcenter_fÚimg_sizerµ   r   r   r   r»     s     r»   )r   rŸ   r    re   r¡   r·   Ú	fillcolorr   c                 C   sp  t |ttfƒstdƒ‚t |ttfƒs,tdƒ‚t|ƒdkr@tdƒ‚|dkrPtdƒ‚t |tj	ttffƒsltdƒ‚t |tƒr~t|ƒ}t |tƒr�t|ƒ}t |tj	ƒr¤|dg}t |tƒr¶t|ƒ}t|ƒdkrÒ|d	 |d	 g}t|ƒdkrìtd
 
|¡ƒ‚t| ƒ}t | tjƒ�s<|d	 d |d d g}t|||||ƒ}	tj| |	||d�S dd„ |D ƒ}
tddg||
||ƒ}	tj| |	||d�S )a0  Apply affine transformation on the image keeping image center invariant.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.

    Args:
        img (PIL Image or Tensor): image to transform.
        angle (float or int): rotation angle in degrees between -180 and 180, clockwise direction.
        translate (list or tuple of integers): horizontal and vertical translations (post-rotation translation)
        scale (float): overall scale
        shear (float or tuple or list): shear angle value in degrees between -180 to 180, clockwise direction.
            If a tuple of list is specified, the first value corresponds to a shear parallel to the x axis, while
            the second value corresponds to a shear parallel to the y axis.
        resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC``, optional):
            An optional resampling filter. See `filters`_ for more information.
            If omitted, or if the image is PIL Image and has mode "1" or "P", it is set to ``PIL.Image.NEAREST``.
            If input is Tensor, only ``PIL.Image.NEAREST`` and ``PIL.Image.BILINEAR`` are supported.
        fillcolor (int): Optional fill color for the area outside the transform in the output image (Pillow>=5.0.0).
            This option is not supported for Tensor input. Fill value for the area outside the transform in the output
            image is always 0.

    Returns:
        PIL Image or Tensor: Transformed image.
    r¹   z'Argument translate should be a sequencer   z3Argument translate should be a sequence of length 2r¨   z!Argument scale should be positivezAShear should be either a single value or a sequence of two valuesr   r   z8Shear should be a sequence containing two values. Got {}ro   )rµ   r·   r½   c                 S   s   g | ]}d | ‘qS )rº   r   )r¤   Útr   r   r   r¦   –  r§   zaffine.<locals>.<listcomp>)r   rr   r0   r*   rt   rs   rB   r-   rp   rq   r+   r   r   r   r¶   r   Úaffiner   )r   rŸ   r    re   r¡   r·   r½   r¼   r�   rµ   Ztranslate_fr   r   r   r¿   P  s<    


r¿   c                 C   s$   t | tjƒrt | |¡S tdƒ‚dS )aî  Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image.

    Args:
        img (PIL Image): PIL Image to be converted to grayscale.
        num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default, 1.

    Returns:
        PIL Image: Grayscale version of the image.
            if num_output_channels = 1 : returned image is single channel

            if num_output_channels = 3 : returned image is 3 channel with r = g = b
    zInput should be PIL ImageN)r   r   r   Úto_grayscaler*   ©r   Únum_output_channelsr   r   r   rÀ   ›  s    rÀ   )r   rÂ   r   c                 C   s$   t | tjƒst | |¡S t | |¡S )aa  Convert RGB image to grayscale version of image.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    Note:
        Please, note that this method supports only RGB images as input. For inputs in other color spaces,
        please, consider using meth:`~torchvision.transforms.functional.to_grayscale` with PIL Image.

    Args:
        img (PIL Image or Tensor): RGB Image to be converted to grayscale.
        num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default, 1.

    Returns:
        PIL Image or Tensor: Grayscale version of the image.
            if num_output_channels = 1 : returned image is single channel

            if num_output_channels = 3 : returned image is 3 channel with r = g = b
    )r   r   r   r   rÀ   r   Úrgb_to_grayscalerÁ   r   r   r   rÃ   ¯  s    rÃ   )r   r‚   ÚjÚhÚwÚvrY   r   c                 C   sL   t | tjƒstd t| ƒ¡ƒ‚|s*|  ¡ } || d||| …||| …f< | S )a   Erase the input Tensor Image with given value.

    Args:
        img (Tensor Image): Tensor image of size (C, H, W) to be erased
        i (int): i in (i,j) i.e coordinates of the upper left corner.
        j (int): j in (i,j) i.e coordinates of the upper left corner.
        h (int): Height of the erased region.
        w (int): Width of the erased region.
        v: Erasing value.
        inplace(bool, optional): For in-place operations. By default is set False.

    Returns:
        Tensor Image: Erased image.
    z"img should be Tensor Image. Got {}.)r   r   r   r*   r+   r,   r\   )r   r‚   rÄ   rÅ   rÆ   rÇ   rY   r   r   r   ÚeraseÈ  s    rÈ   )r   Úkernel_sizeÚsigmar   c                 C   s°  t |tttfƒs"td t|ƒ¡ƒ‚t |tƒr4||g}t|ƒdkrRtd t|ƒ¡ƒ‚|D ]&}|d dksn|dk rVtd |¡ƒ‚qV|du r”dd„ |D ƒ}|durÀt |tt	ttfƒsÀtd	 t|ƒ¡ƒ‚t |tt	fƒrÞt	|ƒt	|ƒg}t |ttfƒ�rt|ƒd
k�r|d |d g}t|ƒdk�r,td t|ƒ¡ƒ‚|D ]}|dk�r0td |¡ƒ‚�q0| }t | t
jƒ�sˆt | ¡�s€td t| ƒ¡ƒ‚t| ƒ}t |||¡}t | t
jƒ�s¬t|ƒ}|S )až  Performs Gaussian blurring on the img by given kernel.
    The image can be a PIL Image or a Tensor, in which case it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    Args:
        img (PIL Image or Tensor): Image to be blurred
        kernel_size (sequence of ints or int): Gaussian kernel size. Can be a sequence of integers
            like ``(kx, ky)`` or a single integer for square kernels.
            In torchscript mode kernel_size as single int is not supported, use a tuple or
            list of length 1: ``[ksize, ]``.
        sigma (sequence of floats or float, optional): Gaussian kernel standard deviation. Can be a
            sequence of floats like ``(sigma_x, sigma_y)`` or a single float to define the
            same sigma in both X/Y directions. If None, then it is computed using
            ``kernel_size`` as ``sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8``.
            Default, None. In torchscript mode sigma as single float is
            not supported, use a tuple or list of length 1: ``[sigma, ]``.

    Returns:
        PIL Image or Tensor: Gaussian Blurred version of the image.
    z;kernel_size should be int or a sequence of integers. Got {}r   z;If kernel_size is a sequence its length should be 2. Got {}r   z9kernel_size should have odd and positive integers. Got {}Nc                 S   s   g | ]}|d  d ‘qS )g333333Ã?gffffffÖ?r   )r¤   Úksizer   r   r   r¦     r§   z!gaussian_blur.<locals>.<listcomp>z:sigma should be either float or sequence of floats. Got {}r   z6If sigma is a sequence, its length should be 2. Got {}r¨   z)sigma should have positive values. Got {}z)img should be PIL Image or Tensor. Got {})r   rr   rt   rs   r*   r+   r,   rB   r-   r0   r   r   r   r)   rG   r   Úgaussian_blurrU   )r   rÉ   rÊ   rË   r¥   Zt_imgr†   r   r   r   rÌ   á  s>    

rÌ   )N)F)r   rf   )r   N)F)r   )r   FNN)r   N)r   )r   )F)N)Ar¢   rp   ra   Útypingr   r   rS   r   ZPILr   r   r   Ztorch.jit.annotationsr   r   r2   ÚImportErrorÚ r	   r   r
   r   r)   Z_parse_fillrr   r   r   ZjitZunusedÚboolr   r   rG   rI   r0   r#   rK   rU   r^   ZBILINEARr`   re   Ústrrj   rm   ry   rz   r{   r‡   rˆ   r‰   r‘   r“   r•   r—   r™   r›   rž   r¶   r»   r¿   rÀ   rÃ   rÈ   rÌ   r   r   r   r   Ú<module>   s    
	7
W (*!ÿþþ"  û

ú$$+*þ3  þý7 þýK