
    ڧg+N                       d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZm	Z	m
Z
 d dlZd dlmZ 	 d dlZn# e$ r dZY nw xY wddlmZ ddlmZ dd	lmZmZ g d
Z G d d          Z G d d          Z G d d          Z G d dej        j                  Z G d d          Z G d dej        j                  Z G d dej        j                  Z G d dej        j                  Z  G d dej        j                  Z! G d d          Z" G d d           Z# G d! d"ej        j                  Z$ G d# d$e#          Z% G d% d&e#          Z& G d' d(ej        j                  Z' G d) d*ej        j                  Z( G d+ d,ej        j                  Z) G d- d.ej        j                  Z* G d/ d0ej        j                  Z+ G d1 d2ej        j                  Z, G d3 d4ej        j                  Z- G d5 d6ej        j                  Z. G d7 d8ej        j                  Z/ G d9 d:ej        j                  Z0 G d; d<ej        j                  Z1 G d= d>ej        j                  Z2 G d? d@ej        j                  Z3 G dA dBej        j                  Z4 G dC dDej        j                  Z5dE Z6dF Z7dWdHZ8 G dI dJej        j                  Z9 G dK dLej        j                  Z: G dM dNej        j                  Z; G dO dPej        j                  Z< G dQ dRej        j                  Z= G dS dTej        j                  Z> G dU dVej        j                  Z?dS )X    N)Sequence)ListOptionalTupleUnion)Tensor   _log_api_usage_once   )
functional)_interpolation_modes_from_intInterpolationMode)$ComposeToTensorPILToTensorConvertImageDtype
ToPILImage	NormalizeResize
CenterCropPadLambdaRandomApplyRandomChoiceRandomOrder
RandomCropRandomHorizontalFlipRandomVerticalFlipRandomResizedCropFiveCropTenCropLinearTransformationColorJitterRandomRotationRandomAffine	GrayscaleRandomGrayscaleRandomPerspectiveRandomErasingGaussianBlurr   RandomInvertRandomPosterizeRandomSolarizeRandomAdjustSharpnessRandomAutocontrastRandomEqualizeElasticTransformc                   *    e Zd ZdZd Zd ZdefdZdS )r   a  Composes several transforms together. This transform does not support torchscript.
    Please, see the note below.

    Args:
        transforms (list of ``Transform`` objects): list of transforms to compose.

    Example:
        >>> transforms.Compose([
        >>>     transforms.CenterCrop(10),
        >>>     transforms.PILToTensor(),
        >>>     transforms.ConvertImageDtype(torch.float),
        >>> ])

    .. note::
        In order to script the transformations, please use ``torch.nn.Sequential`` as below.

        >>> transforms = torch.nn.Sequential(
        >>>     transforms.CenterCrop(10),
        >>>     transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
        >>> )
        >>> scripted_transforms = torch.jit.script(transforms)

        Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
        `lambda` functions or ``PIL.Image``.

    c                     t           j                                        s-t           j                                        st	          |            || _        d S N)torchjitis_scripting
is_tracingr   
transformsselfr:   s     ]/var/www/html/ai-engine/env/lib/python3.11/site-packages/torchvision/transforms/transforms.py__init__zCompose.__init__X   sF    y%%'' 	&	0D0D0F0F 	&%%%$    c                 0    | j         D ]} ||          }|S r5   )r:   r<   imgts      r=   __call__zCompose.__call__]   s'     	 	A!C&&CC
r?   returnc                 \    | j         j        dz   }| j        D ]}|dz  }|d| z  }|dz  }|S N(
    
)	__class____name__r:   r<   format_stringrC   s      r=   __repr__zCompose.__repr__b   N    /#5 	( 	(AT!MZAZZ'MMr?   NrN   
__module____qualname____doc__r>   rD   strrQ    r?   r=   r   r   <   sW         6% % %
  
#      r?   r   c                   ,    e Zd ZdZddZd ZdefdZdS )r   a   Convert a PIL Image or ndarray to tensor and scale the values accordingly.

    This transform does not support torchscript.

    Converts a PIL Image or numpy.ndarray (H x W x C) in the range
    [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
    if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)
    or if the numpy.ndarray has dtype = np.uint8

    In the other cases, tensors are returned without scaling.

    .. note::
        Because the input image is scaled to [0.0, 1.0], this transformation should not be used when
        transforming target image masks. See the `references`_ for implementing the transforms for image masks.

    .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation
    rE   Nc                 $    t          |            d S r5   r
   r<   s    r=   r>   zToTensor.__init__~       D!!!!!r?   c                 *    t          j        |          S )z
        Args:
            pic (PIL Image or numpy.ndarray): Image to be converted to tensor.

        Returns:
            Tensor: Converted image.
        )F	to_tensorr<   pics     r=   rD   zToTensor.__call__   s     {3r?   c                      | j         j         dS Nz()rM   rN   r[   s    r=   rQ   zToTensor.__repr__       .)----r?   rE   NrS   rX   r?   r=   r   r   k   s\         $" " " "     .# . . . . . .r?   r   c                   ,    e Zd ZdZddZd ZdefdZdS )r   zConvert a PIL Image to a tensor of the same type - this does not scale values.

    This transform does not support torchscript.

    Converts a PIL Image (H x W x C) to a Tensor of shape (C x H x W).
    rE   Nc                 $    t          |            d S r5   r
   r[   s    r=   r>   zPILToTensor.__init__   r\   r?   c                 *    t          j        |          S )z
        .. note::

            A deep copy of the underlying array is performed.

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

        Returns:
            Tensor: Converted image.
        )r^   pil_to_tensorr`   s     r=   rD   zPILToTensor.__call__   s     s###r?   c                      | j         j         dS rc   rd   r[   s    r=   rQ   zPILToTensor.__repr__   re   r?   rf   rS   rX   r?   r=   r   r      s\         " " " "$ $ $.# . . . . . .r?   r   c                   <     e Zd ZdZdej        ddf fdZd Z xZS )r   a%  Convert a tensor image to the given ``dtype`` and scale the values accordingly.

    This function does not support PIL Image.

    Args:
        dtype (torch.dtype): Desired data type of the output

    .. 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``.
    dtyperE   Nc                 t    t                                                       t          |            || _        d S r5   )superr>   r   rm   )r<   rm   rM   s     r=   r>   zConvertImageDtype.__init__   s2    D!!!


r?   c                 6    t          j        || j                  S r5   )r^   convert_image_dtyperm   )r<   images     r=   forwardzConvertImageDtype.forward   s    $UDJ777r?   )	rN   rT   rU   rV   r6   rm   r>   rs   __classcell__rM   s   @r=   r   r      sf         &ek d      
8 8 8 8 8 8 8r?   r   c                   ,    e Zd ZdZddZd ZdefdZdS )r   a  Convert a tensor or an ndarray to PIL Image

    This transform does not support torchscript.

    Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape
    H x W x C to a PIL Image while adjusting the value range depending on the ``mode``.

    Args:
        mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
            If ``mode`` is ``None`` (default) there are some assumptions made about the input data:

            - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``.
            - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``.
            - If the input has 2 channels, the ``mode`` is assumed to be ``LA``.
            - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, ``short``).

    .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes
    Nc                 2    t          |            || _        d S r5   )r   mode)r<   rx   s     r=   r>   zToPILImage.__init__   s    D!!!			r?   c                 6    t          j        || j                  S )z
        Args:
            pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.

        Returns:
            PIL Image: Image converted to PIL Image.

        )r^   to_pil_imagerx   r`   s     r=   rD   zToPILImage.__call__   s     ~c49---r?   rE   c                 V    | j         j        dz   }| j        |d| j         z  }|dz  }|S )NrH   zmode=))rM   rN   rx   r<   rP   s     r=   rQ   zToPILImage.__repr__   s>    /#59 0TY000Mr?   r5   rS   rX   r?   r=   r   r      s\         &   	. 	. 	.#      r?   r   c                   @     e Zd ZdZd fd	ZdedefdZdefdZ xZ	S )	r   a  Normalize a tensor image with mean and standard deviation.
    This transform does not support PIL Image.
    Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n``
    channels, this transform will normalize each channel of the input
    ``torch.*Tensor`` i.e.,
    ``output[channel] = (input[channel] - mean[channel]) / std[channel]``

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

    Args:
        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 in-place.

    Fc                     t                                                       t          |            || _        || _        || _        d S r5   )ro   r>   r   meanstdinplace)r<   r   r   r   rM   s       r=   r>   zNormalize.__init__  s@    D!!!	r?   tensorrE   c                 N    t          j        || j        | j        | j                  S )z
        Args:
            tensor (Tensor): Tensor image to be normalized.

        Returns:
            Tensor: Normalized Tensor image.
        )r^   	normalizer   r   r   )r<   r   s     r=   rs   zNormalize.forward  s      {649dhEEEr?   c                 @    | j         j         d| j         d| j         dS )Nz(mean=z, std=r|   )rM   rN   r   r   r[   s    r=   rQ   zNormalize.__repr__  s*    .)MMMM$(MMMMr?   F
rN   rT   rU   rV   r>   r   rs   rW   rQ   rt   ru   s   @r=   r   r      s         "     Ff F F F F FN# N N N N N N N Nr?   r   c                   F     e Zd ZdZej        ddf fd	Zd ZdefdZ	 xZ
S )r   a  Resize the input image to the given size.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means a maximum of two leading dimensions

    Args:
        size (sequence or int): Desired output size. If size is a sequence like
            (h, w), output size will be matched to this. If size is an int,
            smaller edge of the image will be matched to this number.
            i.e, if height > width, then image will be rescaled to
            (size * height / width, size).

            .. note::
                In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
        interpolation (InterpolationMode): Desired interpolation enum defined by
            :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
            If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
            ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
            The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
        max_size (int, optional): The maximum allowed for the longer edge of
            the resized image. If the longer edge of the image is greater
            than ``max_size`` after being resized according to ``size``,
            ``size`` will be overruled so that the longer edge is equal to
            ``max_size``.
            As a result, the smaller edge may be shorter than ``size``. This
            is only supported if ``size`` is an int (or a sequence of length
            1 in torchscript mode).
        antialias (bool, optional): Whether to apply antialiasing.
            It only affects **tensors** with bilinear or bicubic modes and it is
            ignored otherwise: on PIL images, antialiasing is always applied on
            bilinear or bicubic modes; on other modes (for PIL images and
            tensors), antialiasing makes no sense and this parameter is ignored.
            Possible values are:

            - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
              Other mode aren't affected. This is probably what you want to use.
            - ``False``: will not apply antialiasing for tensors on any mode. PIL
              images are still antialiased on bilinear or bicubic modes, because
              PIL doesn't support no antialias.
            - ``None``: equivalent to ``False`` for tensors and ``True`` for
              PIL images. This value exists for legacy reasons and you probably
              don't want to use it unless you really know what you are doing.

            The default value changed from ``None`` to ``True`` in
            v0.17, for the PIL and Tensor backends to be consistent.
    NTc                    t                                                       t          |            t          |t          t
          f          st          dt          |                     t          |t
                    r t          |          dvrt          d          || _
        || _        t          |t                    rt          |          }|| _        || _        d S )Nz$Size should be int or sequence. Got )r   r	   z3If size is a sequence, it should have 1 or 2 values)ro   r>   r   
isinstanceintr   	TypeErrortypelen
ValueErrorsizemax_sizer   interpolation	antialias)r<   r   r   r   r   rM   s        r=   r>   zResize.__init__J  s    D!!!$h00 	QO4::OOPPPdH%% 	T#d))6*A*ARSSS	 mS)) 	I9-HHM*"r?   c                 Z    t          j        || j        | j        | j        | j                  S )z
        Args:
            img (PIL Image or Tensor): Image to be scaled.

        Returns:
            PIL Image or Tensor: Rescaled image.
        )r^   resizer   r   r   r   r<   rB   s     r=   rs   zResize.forwardZ  s%     xTY(:DM4>ZZZr?   rE   c           	      r    d| j          d| j        j         d| j         d| j         d	}| j        j         | S )N(size=, interpolation=z, max_size=, antialias=r|   )r   r   valuer   r   rM   rN   )r<   details     r=   rQ   zResize.__repr__d  sr     G$)  G  GT5G5M  G  GZ^Zg  G  Guy  vD  G  G  G.)36333r?   )rN   rT   rU   rV   r   BILINEARr>   rs   rW   rQ   rt   ru   s   @r=   r   r     s        , ,\ ,=+EPT`d # # # # # # [ [ [4# 4 4 4 4 4 4 4 4r?   r   c                   4     e Zd ZdZ fdZd ZdefdZ xZS )r   a/  Crops the given image at the center.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
    If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.

    Args:
        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 sequence of length 1, it will be interpreted as (size[0], size[0]).
    c                     t                                                       t          |            t          |d          | _        d S N3Please provide only two dimensions (h, w) for size.	error_msgro   r>   r   _setup_sizer   r<   r   rM   s     r=   r>   zCenterCrop.__init__u  @    D!!!0efff			r?   c                 6    t          j        || j                  S )
        Args:
            img (PIL Image or Tensor): Image to be cropped.

        Returns:
            PIL Image or Tensor: Cropped image.
        )r^   center_cropr   r   s     r=   rs   zCenterCrop.forwardz  s     }S$),,,r?   rE   c                 0    | j         j         d| j         dS Nr   r|   rM   rN   r   r[   s    r=   rQ   zCenterCrop.__repr__       .)======r?   	rN   rT   rU   rV   r>   rs   rW   rQ   rt   ru   s   @r=   r   r   i  sq        	 	g g g g g
- - -># > > > > > > > >r?   r   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )	r   aE  Pad the given image on all sides with the given "pad" value.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric,
    at most 3 leading dimensions for mode edge,
    and an arbitrary number of leading dimensions for mode constant

    Args:
        padding (int or sequence): Padding on each border. If a single int is provided this
            is used to pad all borders. If sequence of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a sequence of length 4 is provided
            this is the padding for the left, top, right and bottom borders respectively.

            .. note::
                In torchscript mode padding as single int is not supported, use a sequence of
                length 1: ``[padding, ]``.
        fill (number 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 number is supported for torch Tensor.
            Only int or tuple value is supported for PIL Image.
        padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
            Default is constant.

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

            - edge: pads with the last value at the edge of the image.
              If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2

            - reflect: pads with reflection of image without repeating the last value on the edge.
              For example, 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.
              For example, 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]
    r   constantc                    t                                                       t          |            t          |t          j        t          t          f          st          d          t          |t          j        t          t          f          st          d          |dvrt          d          t          |t                    r1t          |          dvr t          dt          |           d          || _        || _        || _        d S )NzGot inappropriate padding argzGot inappropriate fill arg)r   edgereflect	symmetriczBPadding mode should be either constant, edge, reflect or symmetric)r   r	      z<Padding must be an int or a 1, 2, or 4 element tuple, not a z element tuple)ro   r>   r   r   numbersNumbertuplelistr   r   r   r   paddingfillpadding_mode)r<   r   r   r   rM   s       r=   r>   zPad.__init__  s    D!!!'GNE4#@AA 	=;<<<$ =>> 	:8999KKKabbbgx(( 	S\\-J-JksSZ||kkk   	(r?   c                 N    t          j        || j        | j        | j                  S )z
        Args:
            img (PIL Image or Tensor): Image to be padded.

        Returns:
            PIL Image or Tensor: Padded image.
        )r^   padr   r   r   r   s     r=   rs   zPad.forward  s!     uS$,	43DEEEr?   rE   c                 P    | j         j         d| j         d| j         d| j         dS )Nz	(padding=, fill=z, padding_mode=r|   )rM   rN   r   r   r   r[   s    r=   rQ   zPad.__repr__  s6    .)wwDLwwwwcgctwwwwr?   )r   r   r   ru   s   @r=   r   r     s~        # #J) ) ) ) ) )*F F Fx# x x x x x x x xr?   r   c                   *    e Zd ZdZd Zd ZdefdZdS )r   zApply a user-defined lambda as a transform. This transform does not support torchscript.

    Args:
        lambd (function): Lambda/function to be used for transform.
    c                     t          |            t          |          s1t          dt          t	          |          j                             || _        d S )Nz'Argument lambd should be callable, got )r   callabler   reprr   rN   lambd)r<   r   s     r=   r>   zLambda.__init__  sS    D!!! 	dbd4PU;;K_F`F`bbccc


r?   c                 ,    |                      |          S r5   )r   r   s     r=   rD   zLambda.__call__  s    zz#r?   rE   c                      | j         j         dS rc   rd   r[   s    r=   rQ   zLambda.__repr__  re   r?   NrS   rX   r?   r=   r   r     sW             .# . . . . . .r?   r   c                   *    e Zd ZdZd Zd ZdefdZdS )RandomTransformszBase class for a list of transformations with randomness

    Args:
        transforms (sequence): list of transformations
    c                 z    t          |            t          |t                    st          d          || _        d S )Nz(Argument transforms should be a sequence)r   r   r   r   r:   r;   s     r=   r>   zRandomTransforms.__init__  s=    D!!!*h// 	HFGGG$r?   c                     t                      r5   )NotImplementedError)r<   argskwargss      r=   rD   zRandomTransforms.__call__  s    !###r?   rE   c                 \    | j         j        dz   }| j        D ]}|dz  }|d| z  }|dz  }|S rG   rL   rO   s      r=   rQ   zRandomTransforms.__repr__  rR   r?   NrS   rX   r?   r=   r   r     sW         % % %$ $ $#      r?   r   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r   a  Apply randomly a list of transformations with a given probability.

    .. note::
        In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of
        transforms as shown below:

        >>> transforms = transforms.RandomApply(torch.nn.ModuleList([
        >>>     transforms.ColorJitter(),
        >>> ]), p=0.3)
        >>> scripted_transforms = torch.jit.script(transforms)

        Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
        `lambda` functions or ``PIL.Image``.

    Args:
        transforms (sequence or torch.nn.Module): list of transformations
        p (float): probability
          ?c                     t                                                       t          |            || _        || _        d S r5   )ro   r>   r   r:   pr<   r:   r   rM   s      r=   r>   zRandomApply.__init__  s9    D!!!$r?   c                 n    | j         t          j        d          k     r|S | j        D ]} ||          }|S )Nr   )r   r6   randr:   rA   s      r=   rs   zRandomApply.forward  sA    6EJqMM!!J 	 	A!C&&CC
r?   rE   c                 v    | j         j        dz   }|d| j         z  }| j        D ]}|dz  }|d| z  }|dz  }|S )NrH   z
    p=rI   rJ   rK   )rM   rN   r   r:   rO   s      r=   rQ   zRandomApply.__repr__  sc    /#5,DF,,, 	( 	(AT!MZAZZ'MMr?   r   r   ru   s   @r=   r   r     sq         &       #        r?   r   c                       e Zd ZdZd ZdS )r   z_Apply a list of transformations in a random order. This transform does not support torchscript.c                     t          t          t          | j                                      }t	          j        |           |D ]} | j        |         |          }|S r5   )r   ranger   r:   randomshuffle)r<   rB   orderis       r=   rD   zRandomOrder.__call__,  s]    U3t//0011u 	* 	*A$$/!$S))CC
r?   N)rN   rT   rU   rV   rD   rX   r?   r=   r   r   )  s)        ii    r?   r   c                   :     e Zd ZdZd fd	Zd Zdef fdZ xZS )r   zeApply single transformation randomly picked from a list. This transform does not support torchscript.Nc                     t                                          |           |$t          |t                    st	          d          || _        d S )NzArgument p should be a sequence)ro   r>   r   r   r   r   r   s      r=   r>   zRandomChoice.__init__7  sH    $$$=Ax!8!8==>>>r?   c                 X    t          j        | j        | j                  d         } || S )N)weightsr   )r   choicesr:   r   )r<   r   rC   s      r=   rD   zRandomChoice.__call__=  s*    N4?DF;;;A>q$xr?   rE   c                 Z    t                                                       d| j         dS N(p=r|   )ro   rQ   r   )r<   rM   s    r=   rQ   zRandomChoice.__repr__A  s,    ''""$$222222r?   r5   )	rN   rT   rU   rV   r>   rD   rW   rQ   rt   ru   s   @r=   r   r   4  sw        oo       3# 3 3 3 3 3 3 3 3 3 3r?   r   c                   ~     e Zd ZdZededeeef         deeeeef         fd            Zd fd
	Z	d Z
defdZ xZS )r   a6
  Crop the given image at a random location.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions,
    but if non-constant padding is used, the input is expected to have at most 2 leading dimensions

    Args:
        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 sequence of length 1, it will be interpreted as (size[0], size[0]).
        padding (int or sequence, optional): Optional padding on each border
            of the image. Default is None. If a single int is provided this
            is used to pad all borders. If sequence of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a sequence of length 4 is provided
            this is the padding for the left, top, right and bottom borders respectively.

            .. note::
                In torchscript mode padding as single int is not supported, use a sequence of
                length 1: ``[padding, ]``.
        pad_if_needed (boolean): It will pad the image if smaller than the
            desired size to avoid raising an exception. Since cropping is done
            after padding, the padding seems to be done at a random offset.
        fill (number 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 number is supported for torch Tensor.
            Only int or tuple value is supported for PIL Image.
        padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
            Default is constant.

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

            - edge: pads with the last value at the edge of the image.
              If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2

            - reflect: pads with reflection of image without repeating the last value on the edge.
              For example, 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.
              For example, 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]
    rB   output_sizerE   c                 r   t          j        |           \  }}}|\  }}||k     s||k     rt          d||f d||f           ||k    r||k    rdd||fS t          j        d||z
  dz   d                                          }t          j        d||z
  dz   d                                          }||||fS )a(  Get parameters for ``crop`` for a random crop.

        Args:
            img (PIL Image or Tensor): Image to be cropped.
            output_size (tuple): Expected output size of the crop.

        Returns:
            tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
        zRequired crop size z! is larger than input image size r   r   r   r   )r^   get_dimensionsr   r6   randintitem)	rB   r   _hwthtwr   js	            r=   
get_paramszRandomCrop.get_paramsq  s     "3''1aBr66QVVfB8ff_`bc^dffggg77qBwwaA:M!QVaZd33388::M!QVaZd33388::!R|r?   NFr   r   c                     t                                                       t          |            t          t	          |d                    | _        || _        || _        || _        || _	        d S r   )
ro   r>   r   r   r   r   r   pad_if_neededr   r   )r<   r   r   r   r   r   rM   s         r=   r>   zRandomCrop.__init__  sh    D!!!+d6klllmm	*	(r?   c                 (   | j         &t          j        || j         | j        | j                  }t          j        |          \  }}}| j        rD|| j        d         k     r3| j        d         |z
  dg}t          j        ||| j        | j                  }| j        rD|| j        d         k     r3d| j        d         |z
  g}t          j        ||| j        | j                  }|                     || j                  \  }}}}	t          j	        |||||	          S )r   Nr   r   )
r   r^   r   r   r   r   r   r   r   crop)
r<   rB   r   heightwidthr   r   r   r   r   s
             r=   rs   zRandomCrop.forward  s
    <#%T\49d6GHHC+C0065 	D%$)A,"6"6y|e+Q/G%Wdi1BCCC 	D&49Q<"7"7$)A,/0G%Wdi1BCCC__S$)44
1avc1aA&&&r?   c                 @    | j         j         d| j         d| j         dS )Nr   z
, padding=r|   )rM   rN   r   r   r[   s    r=   rQ   zRandomCrop.__repr__  s*    .)UUUUdlUUUUr?   )NFr   r   )rN   rT   rU   rV   staticmethodr   r   r   r   r>   rs   rW   rQ   rt   ru   s   @r=   r   r   E  s        ) )V  U38_ sCQTVYGYAZ    \.	) 	) 	) 	) 	) 	)' ' '2V# V V V V V V V Vr?   r   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r   a2  Horizontally flip the given image randomly with a given probability.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading
    dimensions

    Args:
        p (float): probability of the image being flipped. Default value is 0.5
    r   c                 t    t                                                       t          |            || _        d S r5   ro   r>   r   r   r<   r   rM   s     r=   r>   zRandomHorizontalFlip.__init__  2    D!!!r?   c                 h    t          j        d          | j        k     rt          j        |          S |S z
        Args:
            img (PIL Image or Tensor): Image to be flipped.

        Returns:
            PIL Image or Tensor: Randomly flipped image.
        r   )r6   r   r   r^   hflipr   s     r=   rs   zRandomHorizontalFlip.forward  ,     :a==46!!73<<
r?   rE   c                 0    | j         j         d| j         dS r   rM   rN   r   r[   s    r=   rQ   zRandomHorizontalFlip.__repr__       .)77df7777r?   r   r   ru   s   @r=   r   r     q              

 
 
8# 8 8 8 8 8 8 8 8r?   r   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r   a0  Vertically flip the given image randomly with a given probability.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading
    dimensions

    Args:
        p (float): probability of the image being flipped. Default value is 0.5
    r   c                 t    t                                                       t          |            || _        d S r5   r  r  s     r=   r>   zRandomVerticalFlip.__init__  r  r?   c                 h    t          j        d          | j        k     rt          j        |          S |S r  )r6   r   r   r^   vflipr   s     r=   rs   zRandomVerticalFlip.forward  r	  r?   rE   c                 0    | j         j         d| j         dS r   r  r[   s    r=   rQ   zRandomVerticalFlip.__repr__  r  r?   r   r   ru   s   @r=   r   r     r  r?   r   c                        e Zd ZdZddej        df fd	Zd Zede	de	de
d	eeee	                  eee	                  f         fd
            Zd	efdZ xZS )r)   a  Performs a random perspective transformation of the given image with a given probability.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.

    Args:
        distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1.
            Default is 0.5.
        p (float): probability of the image being transformed. Default is 0.5.
        interpolation (InterpolationMode): Desired interpolation enum defined by
            :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
            If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
            The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
        fill (sequence or number): Pixel fill value for the area outside the transformed
            image. Default is ``0``. If given a number, the value is used for all bands respectively.
    r   r   c                 P   t                                                       t          |            || _        t	          |t
                    rt          |          }|| _        || _        |d}n0t	          |t          t          j        f          st          d          || _        d S )Nr   -Fill should be either a sequence or a number.)ro   r>   r   r   r   r   r   r   distortion_scaler   r   r   r   r   )r<   r  r   r   r   rM   s        r=   r>   zRandomPerspective.__init__   s    D!!!mS)) 	I9-HHM* 0<DDD8W^"<== 	MKLLL			r?   c                    | j         }t          j        |          \  }}}t          |t                    r<t          |t
          t          f          rt          |          g|z  }nd |D             }t          j        d          | j	        k     r<| 
                    ||| j                  \  }}t          j        |||| j        |          S |S )z
        Args:
            img (PIL Image or Tensor): Image to be Perspectively transformed.

        Returns:
            PIL Image or Tensor: Randomly transformed image.
        c                 ,    g | ]}t          |          S rX   float.0fs     r=   
<listcomp>z-RandomPerspective.forward.<locals>.<listcomp>!      ///Qa///r?   r   )r   r^   r   r   r   r   r  r6   r   r   r   r  perspectiver   )r<   rB   r   channelsr   r   startpoints	endpointss           r=   rs   zRandomPerspective.forward  s     y"#"23"7"7&%c6"" 	0$e-- 0d}x///$///:a==46!!%)__UFDDY%Z%Z"K=k9d>PRVWWW
r?   r   r   r  rE   c           
         |dz  }| dz  }t          t          j        dt          ||z            dz   d                                                    t          t          j        dt          ||z            dz   d                                                    g}t          t          j        | t          ||z            z
  dz
  | d                                                    t          t          j        dt          ||z            dz   d                                                    g}t          t          j        | t          ||z            z
  dz
  | d                                                    t          t          j        |t          ||z            z
  dz
  |d                                                    g}t          t          j        dt          ||z            dz   d                                                    t          t          j        |t          ||z            z
  dz
  |d                                                    g}ddg| dz
  dg| dz
  |dz
  gd|dz
  gg}	||||g}
|	|
fS )a  Get parameters for ``perspective`` for a random perspective transform.

        Args:
            width (int): width of the image.
            height (int): height of the image.
            distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1.

        Returns:
            List containing [top-left, top-right, bottom-right, bottom-left] of the original image,
            List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image.
        r	   r   r   r   r   )r   r6   r   r   )r   r   r  half_height
half_widthtoplefttoprightbotrightbotleftr"  r#  s              r=   r   zRandomPerspective.get_params(  su    kaZ
a%5
%B!C!Ca!GdSSSXXZZ[[a%5%C!D!Dq!HtTTTYY[[\\

 ec*:Z*G&H&HH1LeZ^___ddffgga%5%C!D!Dq!HtTTTYY[[\\

 ec*:Z*G&H&HH1LeZ^___ddffggfs+;k+I'J'JJQNPV]abbbggiijj

 a%5
%B!C!Ca!GdSSSXXZZ[[fs+;k+I'J'JJQNPV]abbbggiijj
 1v	1~	6A:/FFUVJXh':	I%%r?   c                 0    | j         j         d| j         dS r   r  r[   s    r=   rQ   zRandomPerspective.__repr__K  r  r?   )rN   rT   rU   rV   r   r   r>   rs   r   r   r  r   r   r   rW   rQ   rt   ru   s   @r=   r)   r)     s           ),sBSB\cd      $  ,  &#  &s  &e  &dSWX[S\o_cdhildm_nNnHo  &  &  & \ &D8# 8 8 8 8 8 8 8 8r?   r)   c                        e Zd ZdZddej        dfdee         f fdZe	de
dee         d	ee         d
eeeeef         fd            Zd Zd
efdZ xZS )r    a  Crop a random portion of image and resize it to a given size.

    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions

    A crop of the original image is made: the crop has a random area (H * W)
    and a random aspect ratio. This crop is finally resized to the given
    size. This is popularly used to train the Inception networks.

    Args:
        size (int or sequence): expected output size of the crop, for each edge. If size is an
            int instead of sequence like (h, w), a square output size ``(size, size)`` is
            made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).

            .. note::
                In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
        scale (tuple of float): Specifies the lower and upper bounds for the random area of the crop,
            before resizing. The scale is defined with respect to the area of the original image.
        ratio (tuple of float): lower and upper bounds for the random aspect ratio of the crop, before
            resizing.
        interpolation (InterpolationMode): Desired interpolation enum defined by
            :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
            If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
            ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
            The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
        antialias (bool, optional): Whether to apply antialiasing.
            It only affects **tensors** with bilinear or bicubic modes and it is
            ignored otherwise: on PIL images, antialiasing is always applied on
            bilinear or bicubic modes; on other modes (for PIL images and
            tensors), antialiasing makes no sense and this parameter is ignored.
            Possible values are:

            - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
              Other mode aren't affected. This is probably what you want to use.
            - ``False``: will not apply antialiasing for tensors on any mode. PIL
              images are still antialiased on bilinear or bicubic modes, because
              PIL doesn't support no antialias.
            - ``None``: equivalent to ``False`` for tensors and ``True`` for
              PIL images. This value exists for legacy reasons and you probably
              don't want to use it unless you really know what you are doing.

            The default value changed from ``None`` to ``True`` in
            v0.17, for the PIL and Tensor backends to be consistent.
    )g{Gz?      ?)g      ?gUUUUUU?Tr   c                    t                                                       t          |            t          |d          | _        t          |t                    st          d          t          |t                    st          d          |d         |d         k    s|d         |d         k    rt          j	        d           t          |t                    rt          |          }|| _        || _        || _        || _        d S )Nr   r   Scale should be a sequenceRatio should be a sequencer   r   ,Scale and ratio should be of kind (min, max))ro   r>   r   r   r   r   r   r   warningswarnr   r   r   r   scaleratio)r<   r   r4  r5  r   r   rM   s         r=   r>   zRandomResizedCrop.__init__}  s     	D!!!0efff	%** 	:8999%** 	:8999!HuQxU1Xa%8%8MHIIImS)) 	I9-HHM*"



r?   rB   r4  r5  rE   c           	      @   t          j        |           \  }}}||z  }t          j        t          j        |                    }t          d          D ]}|t          j        d                              |d         |d                                                   z  }t          j	        t          j        d                              |d         |d                                                             }	t          t          t          j        ||	z                                }
t          t          t          j        ||	z                                }d|
cxk     r|k    r{n d|cxk     r|k    rjn (t          j        d||z
  dz   d                                          }t          j        d||
z
  dz   d                                          }||||
fc S t          |          t          |          z  }|t!          |          k     r/|}
t          t          |
t!          |          z                      }nF|t#          |          k    r/|}t          t          |t#          |          z                      }
n|}
|}||z
  dz  }||
z
  dz  }||||
fS )a  Get parameters for ``crop`` for a random sized crop.

        Args:
            img (PIL Image or Tensor): Input image.
            scale (list): range of scale of the origin size cropped
            ratio (list): range of aspect ratio of the origin aspect ratio cropped

        Returns:
            tuple: params (i, j, h, w) to be passed to ``crop`` for a random
            sized crop.
        
   r   r   r   r   r	   )r^   r   r6   logr   r   emptyuniform_r   expr   roundmathsqrtr   r  minmax)rB   r4  r5  r   r   r   area	log_ratiotarget_areaaspect_ratior   r   r   r   in_ratios                  r=   r   zRandomResizedCrop.get_params  s`    +C0065~Iel51122	r 
	" 
	"AQ!8!8q58!L!L!Q!Q!S!SSK 9U[^^%<%<Yq\9UV<%X%XYY^^``LE$)K,$>??@@AAAE$)K,$>??@@AAA1~~~~~~~~~!a////6/////M!VaZ!^$???DDFFM!UQY]>>>CCEE!Qz!!! <<%--/c%jj  AE!c%jj.))**AAE

""AE!c%jj.))**AAAAaZAQY1!Qzr?   c           
          |                      || j        | j                  \  }}}}t          j        |||||| j        | j        | j                  S )z
        Args:
            img (PIL Image or Tensor): Image to be cropped and resized.

        Returns:
            PIL Image or Tensor: Randomly cropped and resized image.
        )r   )r   r4  r5  r^   resized_cropr   r   r   )r<   rB   r   r   r   r   s         r=   rs   zRandomResizedCrop.forward  sO     __S$*djAA
1a~c1aAty$:LX\Xfggggr?   c                    | j         j        }| j        j        d| j         z   }|dt          d | j        D                        z  }|dt          d | j        D                        z  }|d| z  }|d| j         dz  }|S )	Nr   , scale=c              3   6   K   | ]}t          |d           V  dS r   Nr<  r  ss     r=   	<genexpr>z-RandomResizedCrop.__repr__.<locals>.<genexpr>  *      )J)J!%1++)J)J)J)J)J)Jr?   , ratio=c              3   6   K   | ]}t          |d           V  dS rK  rL  )r  rs     r=   rO  z-RandomResizedCrop.__repr__.<locals>.<genexpr>  rP  r?   r   r   r|   )	r   r   rM   rN   r   r   r4  r5  r   r<   interpolate_strrP   s      r=   rQ   zRandomResizedCrop.__repr__  s    ,2/2F492F2FFLE)J)Jtz)J)J)J$J$JLLLLE)J)Jtz)J)J)J$J$JLLL=O===99999r?   )rN   rT   rU   rV   r   r   r   boolr>   r   r   r   r  r   r   r   rs   rW   rQ   rt   ru   s   @r=   r    r    O  s        + +` $'0$(  D>     6 ) )tE{ )4; )5QTVY[^`cQcKd ) ) ) \)V	h 	h 	h#        r?   r    c                   4     e Zd ZdZ fdZd ZdefdZ xZS )r!   a	  Crop the given image into four corners and the central crop.
    If the image is torch Tensor, 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. See below for an example of how to deal with
         this.

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

    Example:
         >>> transform = Compose([
         >>>    FiveCrop(size), # this is a list of PIL Images
         >>>    Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor
         >>> ])
         >>> #In your test loop you can do the following:
         >>> input, target = batch # input is a 5d tensor, target is 2d
         >>> bs, ncrops, c, h, w = input.size()
         >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
         >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
    c                     t                                                       t          |            t          |d          | _        d S r   r   r   s     r=   r>   zFiveCrop.__init__  r   r?   c                 6    t          j        || j                  S )z
        Args:
            img (PIL Image or Tensor): Image to be cropped.

        Returns:
            tuple of 5 images. Image can be PIL Image or Tensor
        )r^   	five_cropr   r   s     r=   rs   zFiveCrop.forward  s     {3	***r?   rE   c                 0    | j         j         d| j         dS r   r   r[   s    r=   rQ   zFiveCrop.__repr__  r   r?   r   ru   s   @r=   r!   r!     sq         6g g g g g
+ + +># > > > > > > > >r?   r!   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r"   a  Crop the given image into four corners and the central crop plus the flipped version of
    these (horizontal flipping is used by default).
    If the image is torch Tensor, 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. See below for an example of how to deal with
         this.

    Args:
        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 sequence of length 1, it will be interpreted as (size[0], size[0]).
        vertical_flip (bool): Use vertical flipping instead of horizontal

    Example:
         >>> transform = Compose([
         >>>    TenCrop(size), # this is a tuple of PIL Images
         >>>    Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor
         >>> ])
         >>> #In your test loop you can do the following:
         >>> input, target = batch # input is a 5d tensor, target is 2d
         >>> bs, ncrops, c, h, w = input.size()
         >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
         >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
    Fc                     t                                                       t          |            t          |d          | _        || _        d S r   )ro   r>   r   r   r   vertical_flip)r<   r   r^  rM   s      r=   r>   zTenCrop.__init__&  sJ    D!!!0efff	*r?   c                 B    t          j        || j        | j                  S )z
        Args:
            img (PIL Image or Tensor): Image to be cropped.

        Returns:
            tuple of 10 images. Image can be PIL Image or Tensor
        )r^   ten_cropr   r^  r   s     r=   rs   zTenCrop.forward,  s     z#ty$*<===r?   rE   c                 @    | j         j         d| j         d| j         dS )Nr   z, vertical_flip=r|   )rM   rN   r   r^  r[   s    r=   rQ   zTenCrop.__repr__6  s+    .)aaaaDL^aaaar?   r   r   ru   s   @r=   r"   r"     sz         :+ + + + + +> > >b# b b b b b b b br?   r"   c                   >     e Zd ZdZ fdZdedefdZdefdZ xZ	S )r#   a&  Transform a tensor image with a square transformation matrix and a mean_vector computed
    offline.
    This transform does not support PIL Image.
    Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and
    subtract mean_vector from it which is then followed by computing the dot
    product with the transformation matrix and then reshaping the tensor to its
    original shape.

    Applications:
        whitening transformation: Suppose X is a column vector zero-centered data.
        Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X),
        perform SVD on this matrix and pass it as transformation_matrix.

    Args:
        transformation_matrix (Tensor): tensor [D x D], D = C x H x W
        mean_vector (Tensor): tensor [D], D = C x H x W
    c           	         t                                                       t          |            |                    d          |                    d          k    r2t	          dt          |                                           d          |                    d          |                    d          k    rHt	          d|                    d           dt          |                                           d          |j        |j        k    rt	          d|j         d	|j                   |j        |j        k    rt	          d
|j         d	|j                   || _        || _	        d S )Nr   r   z,transformation_matrix should be square. Got z rectangular matrix.z(mean_vector should have the same length z< as any one of the dimensions of the transformation_matrix []z0Input tensors should be on the same device. Got z and z.Input tensors should have the same dtype. Got )
ro   r>   r   r   r   r   devicerm   transformation_matrixmean_vector)r<   rf  rg  rM   s      r=   r>   zLinearTransformation.__init__M  s   D!!! %%a((,A,F,Fq,I,IIIM.335566M M M  
 A"7"<"<Q"?"???v;;K;KA;N;N v vOTUjUoUoUqUqOrOrv v v  
 !';+===zCXC_zzfqfxzz   !&+*;;;vAVA\vvcnctvv   &;"&r?   r   rE   c           
      L   |j         }|d         |d         z  |d         z  }|| j        j         d         k    rBt          dd|d          d|d          d|d          dz   | j        j         d          z             |j        j        | j        j        j        k    r$t          d	|j         d
| j        j                   |                    d|          | j        z
  }| j                            |j                  }t          j
        ||          }|                    |          }|S )z
        Args:
            tensor (Tensor): Tensor image to be whitened.

        Returns:
            Tensor: Transformed image.
        r   z?Input tensor and transformation matrix have incompatible shape.[z x z] != zXInput tensor should be on the same device as transformation matrix and mean vector. Got z vs )shaperf  r   re  r   rg  viewtorm   r6   mm)r<   r   rm  nflat_tensorrf  transformed_tensors          r=   rs   zLinearTransformation.forwardi  sR    "Ib	!E"I-*0333QBeBiBBE"IBB%)BBBC/5a8:;   =!1!8!===D}D D*.*:*AD D  
 kk"a((4+;; $ : = =k>O P P"Xk3HII#((//r?   c                     | j         j         d| j                                         d| j                                         d}|S )Nz(transformation_matrix=z, mean_vector=r|   )rM   rN   rf  tolistrg  r<   rN  s     r=   rQ   zLinearTransformation.__repr__  s]    ~& : :)0022: :!-4466: : : 	

 r?   r   ru   s   @r=   r#   r#   :  s         $' ' ' ' '8f     :#        r?   r#   c                       e Zd ZdZ	 	 	 	 ddeeeeef         f         deeeeef         f         deeeeef         f         deeeeef         f         ddf
 fd	Zej	        j
        d
d ed          fdfd            Zedeee                  deee                  deee                  deee                  deeee         ee         ee         ee         f         f
d            Zd ZdefdZ xZS )r$   a]  Randomly change the brightness, contrast, saturation and hue of an image.
    If the image is torch Tensor, it is expected
    to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
    If img is PIL Image, mode "1", "I", "F" and modes with transparency (alpha channel) are not supported.

    Args:
        brightness (float or tuple of float (min, max)): How much to jitter brightness.
            brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]
            or the given [min, max]. Should be non negative numbers.
        contrast (float or tuple of float (min, max)): How much to jitter contrast.
            contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]
            or the given [min, max]. Should be non-negative numbers.
        saturation (float or tuple of float (min, max)): How much to jitter saturation.
            saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]
            or the given [min, max]. Should be non negative numbers.
        hue (float or tuple of float (min, max)): How much to jitter hue.
            hue_factor is chosen uniformly from [-hue, hue] or the given [min, max].
            Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5.
            To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space;
            thus it does not work if you normalize your image to an interval with negative values,
            or use an interpolation that generates negative values before using this function.
    r   
brightnesscontrast
saturationhuerE   Nc                 F   t                                                       t          |            |                     |d          | _        |                     |d          | _        |                     |d          | _        |                     |dddd          | _        d S )	Nrx  ry  rz  r{  r   )g      r   F)centerboundclip_first_on_zero)ro   r>   r   _check_inputrx  ry  rz  r{  )r<   rx  ry  rz  r{  rM   s        r=   r>   zColorJitter.__init__  s     	D!!!++JEE))(J??++JEE$$S%af$ggr?   r   infTc                    t          |t          j                  rY|dk     rt          d| d          |t	          |          z
  |t	          |          z   g}|rt          |d         d          |d<   nlt          |t          t          f          r>t          |          dk    r+t	          |d                   t	          |d                   g}nt          | d          |d         |d         cxk    r|d         cxk    r|d         k    sn t          | d| d	| d
          |d         |d         cxk    r|k    rn nd S t          |          S )Nr   If z- is a single number, it must be non negative.        r	   r   z9 should be a single number or a list/tuple with length 2.z values should be between z
, but got .)
r   r   r   r   r  r@  r   r   r   r   )r<   r   namer}  r~  r  s         r=   r  zColorJitter._check_input  sx   eW^,, 		`qyy !Zt!Z!Z!Z[[[eEll*FU5\\,ABE! .uQx--at}-- 	`#e**//58__eE!Hoo6EEt^^^___Qx58;;;;uQx;;;;58;;;;YYYYQVYYYZZZ 8uQx))))6)))))4<<r?   c                 `   t          j        d          }| dn@t          t          j        d                              | d         | d                             }|dn@t          t          j        d                              |d         |d                             }|dn@t          t          j        d                              |d         |d                             }|dn@t          t          j        d                              |d         |d                             }|||||fS )a  Get the parameters for the randomized transform to be applied on image.

        Args:
            brightness (tuple of float (min, max), optional): The range from which the brightness_factor is chosen
                uniformly. Pass None to turn off the transformation.
            contrast (tuple of float (min, max), optional): The range from which the contrast_factor is chosen
                uniformly. Pass None to turn off the transformation.
            saturation (tuple of float (min, max), optional): The range from which the saturation_factor is chosen
                uniformly. Pass None to turn off the transformation.
            hue (tuple of float (min, max), optional): The range from which the hue_factor is chosen uniformly.
                Pass None to turn off the transformation.

        Returns:
            tuple: The parameters used to apply the randomized transform
            along with their random order.
        r   Nr   r   )r6   randpermr  r9  r:  )	rx  ry  rz  r{  fn_idxbcrN  r   s	            r=   r   zColorJitter.get_params  s   . ""&DDE%+a..2I2I*UV-YcdeYf2g2g,h,h$DD%A0G0GQRU]^_U`0a0a*b*b&DDE%+a..2I2I*UV-YcdeYf2g2g,h,hKDDU5;q>>+B+B3q63q6+R+R%S%Sq!Q!!r?   c                 b   |                      | j        | j        | j        | j                  \  }}}}}|D ]y}|dk    r|t          j        ||          } |dk    r|t          j        ||          }>|dk    r|t          j        ||          }\|dk    r|t          j	        ||          }z|S )z
        Args:
            img (PIL Image or Tensor): Input image.

        Returns:
            PIL Image or Tensor: Color jittered image.
        r   Nr   r	      )
r   rx  ry  rz  r{  r^   adjust_brightnessadjust_contrastadjust_saturation
adjust_hue)r<   rB   r  brightness_factorcontrast_factorsaturation_factor
hue_factorfn_ids           r=   rs   zColorJitter.forward  s     UYTcTcOT]DOTXU
 U
Q!?4Ez  	4 	4Ezz/;)#/@AA! ;'_==! 1 =)#/@AA!
 6l3
33
r?   c           
      d    | j         j         d| j         d| j         d| j         d| j         d
}|S )Nz(brightness=z, contrast=z, saturation=z, hue=r|   )rM   rN   rx  ry  rz  r{  rv  s     r=   rQ   zColorJitter.__repr__  se    ~& ! !/! !-! ! !O! ! X	! ! ! 	
 r?   )r   r   r   r   )rN   rT   rU   rV   r   r  r   r>   r6   r7   unusedr  r   r   r   r   r   rs   rW   rQ   rt   ru   s   @r=   r$   r$     s        2 9:678912h h%ue|!445h uUE\223h %ue|!445	h
 5%u--.h 
h h h h h h Y/0EE%LL8I^b        , "T%[)"4;'" T%[)" d5k"	"
 
vx%(SX/Y	Z" " " \">  0#        r?   r$   c                   t     e Zd ZdZej        dddf fd	Zedee	         de	fd            Z
d	 Zdefd
Z xZS )r%   a  Rotate the image by angle.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.

    Args:
        degrees (sequence or number): Range of degrees to select from.
            If degrees is a number instead of sequence like (min, max), the range of degrees
            will be (-degrees, +degrees).
        interpolation (InterpolationMode): Desired interpolation enum defined by
            :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
            If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
            The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
        expand (bool, optional): Optional expansion flag.
            If true, expands the output 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 (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
            Default is the center of the image.
        fill (sequence or number): Pixel fill value for the area outside the rotated
            image. Default is ``0``. If given a number, the value is used for all bands respectively.

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

    FNr   c                    t                                                       t          |            t          |t                    rt          |          }t          |dd          | _        |t          |dd           || _	        || _
        || _        |d}n0t          |t          t          j        f          st          d          || _        d S )Ndegreesr	   r  	req_sizesr}  r  r   r  )ro   r>   r   r   r   r   _setup_angler  _check_sequence_inputr}  r   expandr   r   r   r   r   )r<   r  r   r  r}  r   rM   s         r=   r>   zRandomRotation.__init__)  s    D!!!mS)) 	I9-HHM#G)tLLL!&(dCCCC*<DDD8W^"<== 	MKLLL			r?   r  rE   c           	          t          t          j        d                              t          | d                   t          | d                                                                       }|S )zGet parameters for ``rotate`` for a random rotation.

        Returns:
            float: angle parameter to be passed to ``rotate`` for random rotation.
        r   r   )r  r6   r9  r:  r   )r  angles     r=   r   zRandomRotation.get_paramsA  sR     ek!nn--eGAJ.?.?wqzARARSSXXZZ[[r?   c                 f   | j         }t          j        |          \  }}}t          |t                    r<t          |t
          t          f          rt          |          g|z  }nd |D             }|                     | j                  }t          j	        ||| j
        | j        | j        |          S )z
        Args:
            img (PIL Image or Tensor): Image to be rotated.

        Returns:
            PIL Image or Tensor: Rotated image.
        c                 ,    g | ]}t          |          S rX   r  r  s     r=   r  z*RandomRotation.forward.<locals>.<listcomp>Y  r  r?   )r   r^   r   r   r   r   r  r   r  rotater   r  r}  )r<   rB   r   r!  r   r  s         r=   rs   zRandomRotation.forwardK  s     y)#..!Qc6"" 	0$e-- 0d}x///$///--xUD$6T[RVWWWr?   c                     | j         j        }| j        j        d| j         z   }|d| z  }|d| j         z  }| j        |d| j         z  }| j        |d| j         z  }|dz  }|S )N	(degrees=r   z	, expand=	, center=r   r|   )r   r   rM   rN   r  r  r}  r   rT  s      r=   rQ   zRandomRotation.__repr__^  s    ,2/2Ldl2L2LL=O===2T[222;"6666M9 2ty222Mr?   )rN   rT   rU   rV   r   NEARESTr>   r   r   r  r   rs   rW   rQ   rt   ru   s   @r=   r%   r%     s         2 /@.GPU^bij      0 DK E    \X X X&
# 
 
 
 
 
 
 
 
r?   r%   c                       e Zd ZdZdddej        ddf fd	Zedee	         de
ee	                  de
ee	                  de
ee	                  d	ee         d
ee	eeef         e	ee	e	f         f         fd            Zd Zd
efdZ xZS )r&   al	  Random affine transformation of the image keeping center invariant.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.

    Args:
        degrees (sequence or number): Range of degrees to select from.
            If degrees is a number instead of sequence like (min, max), the range of degrees
            will be (-degrees, +degrees). Set to 0 to deactivate rotations.
        translate (tuple, optional): tuple of maximum absolute fraction for horizontal
            and vertical translations. For example translate=(a, b), then horizontal shift
            is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
            randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
        scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
            randomly sampled from the range a <= scale <= b. Will keep original scale by default.
        shear (sequence or number, optional): Range of degrees to select from.
            If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear)
            will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the
            range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values,
            an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
            Will not apply shear by default.
        interpolation (InterpolationMode): Desired interpolation enum defined by
            :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
            If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
            The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
        fill (sequence or number): Pixel fill value for the area outside the transformed
            image. Default is ``0``. If given a number, the value is used for all bands respectively.
        center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
            Default is the center of the image.

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

    Nr   c                    t                                                       t          |            t          |t                    rt          |          }t          |dd          | _        |5t          |dd           |D ] }d|cxk    rdk    sn t          d          !|| _
        |,t          |d	d           |D ]}	|	d
k    rt          d          || _        |t          |dd          | _        n|| _        || _        |d
}n0t          |t          t          j        f          st#          d          || _        |t          |dd           || _        d S )Nr  r  r  	translater  r  r-  z,translation values should be between 0 and 1r4  r   zscale values should be positiveshear)r	   r   r  r}  )ro   r>   r   r   r   r   r  r  r  r   r  r4  r  r   r   r   r   r   r   r}  )r<   r  r  r4  r  r   r   r}  rC   rN  rM   s             r=   r>   zRandomAffine.__init__  s    	D!!!mS)) 	I9-HHM#G)tLLL !)[DIIII U UqC$%STTT ("!%DAAAA H H66$%FGGG 
%e'VLLLDJJDJ*<DDD8W^"<== 	MKLLL	!&(dCCCCr?   r  r  scale_rangesshearsimg_sizerE   c           	         t          t          j        d                              t          | d                   t          | d                                                                       }|t          |d         |d         z            }t          |d         |d         z            }t          t          t          j        d                              | |                                                              }t          t          t          j        d                              | |                                                              }	||	f}
nd}
|Tt          t          j        d                              |d         |d                                                             }nd}dx}}|t          t          j        d                              |d         |d                                                             }t          |          dk    rSt          t          j        d                              |d         |d	                                                             }||f}||
||fS )
zGet parameters for affine transformation

        Returns:
            params to be passed to the affine transformation
        r   r   N)r   r   r-  r  r   r	   r  )r  r6   r9  r:  r   r   r<  r   )r  r  r  r  r  r  max_dxmax_dytxtytranslationsr4  shear_xshear_yr  s                  r=   r   zRandomAffine.get_params  s     ek!nn--eGAJ.?.?wqzARARSSXXZZ[[ 9Q<(1+566F9Q<(1+566FU5;q>>22F7FCCHHJJKKLLBU5;q>>22F7FCCHHJJKKLLB8LL!L#%+a..11,q/<PQ?SSXXZZ[[EEE'EKNN33F1IvayIINNPPQQG6{{aA 7 7q	6!9 M M R R T TUU'"lE500r?   c                    | j         }t          j        |          \  }}}t          |t                    r<t          |t
          t          f          rt          |          g|z  }nd |D             }||g}|                     | j        | j	        | j
        | j        |          }t          j        |g|R | j        || j        dS )z
            img (PIL Image or Tensor): Image to be transformed.

        Returns:
            PIL Image or Tensor: Affine transformed image.
        c                 ,    g | ]}t          |          S rX   r  r  s     r=   r  z(RandomAffine.forward.<locals>.<listcomp>  r  r?   )r   r   r}  )r   r^   r   r   r   r   r  r   r  r  r4  r  affiner   r}  )r<   rB   r   r!  r   r   r  rets           r=   rs   zRandomAffine.forward  s     y"#"23"7"7&%c6"" 	0$e-- 0d}x///$///6?oodlDNDJ
T\]]xcccc1C$W[Wbccccr?   c                 r   | j         j         d| j         }|| j        
d| j         ndz  }|| j        
d| j         ndz  }|| j        
d| j         ndz  }|| j        t          j        k    rd| j        j	         ndz  }|| j
        dk    r
d| j
         ndz  }|| j        
d	| j         ndz  }|d
z  }|S )Nr  z, translate= rI  z, shear=r   r   r   r  r|   )rM   rN   r  r  r4  r  r   r   r  r   r   r}  rv  s     r=   rQ   zRandomAffine.__repr__  s   ~&????	0J,DN,,,PRR	
(>$
$$$BF	
(>$
$$$BF	d>PTeTm>m>m: 2 8:::suu	di1nn"ty""""<	$+*A&&&&rI	Sr?   )rN   rT   rU   rV   r   r  r>   r   r   r  r   r   r   r   rs   rW   rQ   rt   ru   s   @r=   r&   r&   k  s(        H '/1 1 1 1 1 1f #1e#1DK(#1 tE{+#1 e%	#1
 s)#1 
ueCHoueE5L.AA	B#1 #1 #1 \#1Jd d d*
# 
 
 
 
 
 
 
 
r?   r&   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r'   a  Convert image to grayscale.
    If the image is torch Tensor, it is expected
    to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions

    Args:
        num_output_channels (int): (1 or 3) number of channels desired for output image

    Returns:
        PIL Image: Grayscale version of the input.

        - 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   c                 t    t                                                       t          |            || _        d S r5   )ro   r>   r   num_output_channels)r<   r  rM   s     r=   r>   zGrayscale.__init__  s5    D!!!#6   r?   c                 8    t          j        || j                  S )z
        Args:
            img (PIL Image or Tensor): Image to be converted to grayscale.

        Returns:
            PIL Image or Tensor: Grayscaled image.
        r  )r^   rgb_to_grayscaler  r   s     r=   rs   zGrayscale.forward  s     !#4;STTTTr?   rE   c                 0    | j         j         d| j         dS )Nz(num_output_channels=r|   )rM   rN   r  r[   s    r=   rQ   zGrayscale.__repr__'  s!    .)[[@X[[[[r?   r   r   ru   s   @r=   r'   r'     s}         7 7 7 7 7 7
U U U\# \ \ \ \ \ \ \ \r?   r'   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r(   ab  Randomly convert image to grayscale with a probability of p (default 0.1).
    If the image is torch Tensor, it is expected
    to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions

    Args:
        p (float): probability that image should be converted to grayscale.

    Returns:
        PIL Image or Tensor: Grayscale version of the input image with probability p and unchanged
        with probability (1-p).
        - If input image is 1 channel: grayscale version is 1 channel
        - If input image is 3 channel: grayscale version is 3 channel with r == g == b

    皙?c                 t    t                                                       t          |            || _        d S r5   r  r  s     r=   r>   zRandomGrayscale.__init__;  r  r?   c                     t          j        |          \  }}}t          j        d          | j        k     rt          j        ||          S |S )z
        Args:
            img (PIL Image or Tensor): Image to be converted to grayscale.

        Returns:
            PIL Image or Tensor: Randomly grayscaled image.
        r   r  )r^   r   r6   r   r   r  )r<   rB   r  r   s       r=   rs   zRandomGrayscale.forward@  sM     %&$4S$9$9!Q:a==46!!%c?RSSSS
r?   rE   c                 0    | j         j         d| j         dS r   r  r[   s    r=   rQ   zRandomGrayscale.__repr__M  r  r?   )r  r   ru   s   @r=   r(   r(   +  sq              
  8# 8 8 8 8 8 8 8 8r?   r(   c                        e Zd ZdZd fd	Ze	 dd	ed
eeef         deeef         de	e
e                  deeeeeef         f
d            Zd ZdefdZ xZS )r*   a  Randomly selects a rectangle region in a torch.Tensor image and erases its pixels.
    This transform does not support PIL Image.
    'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896

    Args:
         p: probability that the random erasing operation will be performed.
         scale: range of proportion of erased area against input image.
         ratio: range of aspect ratio of erased area.
         value: erasing value. Default is 0. If a single int, it is used to
            erase all pixels. If a tuple of length 3, it is used to erase
            R, G, B channels respectively.
            If a str of 'random', erasing each pixel with random values.
         inplace: boolean to make this transform inplace. Default set to False.

    Returns:
        Erased Image.

    Example:
        >>> transform = transforms.Compose([
        >>>   transforms.RandomHorizontalFlip(),
        >>>   transforms.PILToTensor(),
        >>>   transforms.ConvertImageDtype(torch.float),
        >>>   transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
        >>>   transforms.RandomErasing(),
        >>> ])
    r   g{Gz?gQ?g333333?gffffff
@r   Fc                    t                                                       t          |            t          |t          j        t          t          t          f          st          d          t          |t                    r|dk    rt          d          t          |t                    st          d          t          |t                    st          d          |d         |d         k    s|d         |d         k    rt          j        d           |d         dk     s|d         dk    rt          d	          |dk     s|dk    rt          d
          || _        || _        || _        || _        || _        d S )Nz=Argument value should be either a number or str or a sequencer   z&If value is str, it should be 'random'r/  r0  r   r   r1  zScale should be between 0 and 1z4Random erasing probability should be between 0 and 1)ro   r>   r   r   r   r   rW   r   r   r   r   r   r2  r3  r   r4  r5  r   r   )r<   r   r4  r5  r   r   rM   s         r=   r>   zRandomErasing.__init__m  sg   D!!!%'.#ud!CDD 	][\\\eS!! 	Gex&7&7EFFF%** 	:8999%** 	:8999!HuQxU1Xa%8%8MHIII8a<<58a<<>???q55AEESTTT


r?   NrB   r4  r5  r   rE   c           	      v   | j         d         | j         d         | j         d         }}}||z  }t          j        t          j        |                    }t	          d          D ]}	|t          j        d                              |d         |d                                                   z  }
t          j        t          j        d                              |d         |d                                                             }t          t          t          j        |
|z                                }t          t          t          j        |
|z                                }||k     r||k     s|6t          j        |||gt          j                                                  }nt          j        |          ddddf         }t          j        d||z
  dz   d	
                                          }t          j        d||z
  dz   d	
                                          }|||||fc S dd||| fS )ap  Get parameters for ``erase`` for a random erasing.

        Args:
            img (Tensor): Tensor image to be erased.
            scale (sequence): range of proportion of erased area against input image.
            ratio (sequence): range of aspect ratio of erased area.
            value (list, optional): erasing value. If None, it is interpreted as "random"
                (erasing each pixel with random values). If ``len(value)`` is 1, it is interpreted as a number,
                i.e. ``value[0]``.

        Returns:
            tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erasing.
        ri  rj  rk  r7  r   r   N)rm   r   r   )rm  r6   r8  r   r   r9  r:  r   r;  r   r<  r=  r>  float32normal_r   )rB   r4  r5  r   img_cimg_himg_wrA  rB  r   
erase_arearD  r   r   vr   r   s                    r=   r   zRandomErasing.get_params  s   " "imSYr]CIbMeuu}Iel51122	r 	! 	!AA 7 7a%( K K P P R RRJ 9U[^^%<%<Yq\9UV<%X%XYY^^``LE$)J$=>>??@@AE$)J$=>>??@@AII!e))}K1U]CCCKKMML''46aQT:::??AAAaQT:::??AAAaAq=    !UE3&&r?   c           	      j   t          j        d          | j        k     rt          | j        t
          t          f          rt          | j                  g}nWt          | j        t                    rd}n:t          | j        t          t          f          rd | j        D             }n| j        }|<t          |          d|j        d         fvrt          d|j        d          d          |                     || j        | j        |          \  }}}}}t!          j        ||||||| j                  S |S )z
        Args:
            img (Tensor): Tensor image to be erased.

        Returns:
            img (Tensor): Erased Tensor image.
        r   Nc                 ,    g | ]}t          |          S rX   r  )r  r  s     r=   r  z)RandomErasing.forward.<locals>.<listcomp>  s    666aq666r?   ri  z@If value is a sequence, it should have either a single value or z (number of input channels))r4  r5  r   )r6   r   r   r   r   r   r  rW   r   r   r   rm  r   r   r4  r5  r^   eraser   )r<   rB   r   xyr   r   r  s           r=   rs   zRandomErasing.forward  s9    :a==46!! $*sEl33 #tz**+DJ,, #DJu66 #664:666
 #e**CIbM8J*J*J By}B B B  
 !OOCtz[`OaaMAq!Q731aAt|<<<
r?   c                 t    | j         j         d| j         d| j         d| j         d| j         d| j         d}|S )Nr   rI  rQ  z, value=z
, inplace=r|   )rM   rN   r   r4  r5  r   r   rv  s     r=   rQ   zRandomErasing.__repr__  sv    ~& ' '&' 'Z' ' Z' ' Z	' '
 |' ' ' 	
 r?   )r   r  r  r   Fr5   )rN   rT   rU   rV   r>   r   r   r   r  r   r   r   r   rs   rW   rQ   rt   ru   s   @r=   r*   r*   Q  s         6     0 lp'' ''''!%,/''8=eUl8K''T\]abg]hTi''	sCc6)	*'' '' '' \''R  <	# 	 	 	 	 	 	 	 	r?   r*   c                   d     e Zd ZdZd fd	Zedededefd            Zdedefd	Z	de
fd
Z xZS )r+   az  Blurs image with randomly chosen Gaussian blur.
    If the image is torch Tensor, it is expected
    to have [..., C, H, W] shape, where ... means at most one leading dimension.

    Args:
        kernel_size (int or sequence): Size of the Gaussian kernel.
        sigma (float or tuple of float (min, max)): Standard deviation to be used for
            creating kernel to perform blurring. If float, sigma is fixed. If it is tuple
            of float (min, max), sigma is chosen uniformly at random to lie in the
            given range.

    Returns:
        PIL Image or Tensor: Gaussian blurred version of the input image.

    r  g       @c                    t                                                       t          |            t          |d          | _        | j        D ] }|dk    s	|dz  dk    rt          d          !t          |t          j                  r|dk    rt          d          ||f}nbt          |t                    r>t          |          dk    r+d|d         cxk     r|d         k    sn t          d          nt          d	          || _        d S )
Nz2Kernel size should be a tuple/list of two integersr   r	   z7Kernel size value should be an odd and positive number.z1If sigma is a single number, it must be positive.r  r   z;sigma values should be positive and of the form (min, max).z>sigma should be a single number or a list/tuple with length 2.)ro   r>   r   r   kernel_sizer   r   r   r   r   r   sigma)r<   r  r  ksrM   s       r=   r>   zGaussianBlur.__init__  s)   D!!!&{4hii" 	\ 	\BQww"q&A++ !Z[[[ & eW^,, 	_zz !TUUUENEEx(( 	_SZZ1__q----U1X---- !^___ . ]^^^


r?   	sigma_min	sigma_maxrE   c                 v    t          j        d                              | |                                          S )av  Choose sigma for random gaussian blurring.

        Args:
            sigma_min (float): Minimum standard deviation that can be chosen for blurring kernel.
            sigma_max (float): Maximum standard deviation that can be chosen for blurring kernel.

        Returns:
            float: Standard deviation to be passed to calculate kernel for gaussian blurring.
        r   )r6   r9  r:  r   )r  r  s     r=   r   zGaussianBlur.get_params  s.     {1~~&&y)<<AACCCr?   rB   c                     |                      | j        d         | j        d                   }t          j        || j        ||g          S )z
        Args:
            img (PIL Image or Tensor): image to be blurred.

        Returns:
            PIL Image or Tensor: Gaussian blurred image
        r   r   )r   r  r^   gaussian_blurr  )r<   rB   r  s      r=   rs   zGaussianBlur.forward  s>     
1tz!}==sD$4uenEEEr?   c                 D    | j         j         d| j         d| j         d}|S )Nz(kernel_size=, sigma=r|   )rM   rN   r  r  rv  s     r=   rQ   zGaussianBlur.__repr__  s/    ~&\\T5E\\tz\\\r?   )r  )rN   rT   rU   rV   r>   r   r  r   r   rs   rW   rQ   rt   ru   s   @r=   r+   r+     s               ( 
De 
D 
D% 
D 
D 
D \
D	F6 	Ff 	F 	F 	F 	F#        r?   r+   c                 *   t          | t          j                  rt          |           t          |           fS t          | t                    r#t          |           dk    r| d         | d         fS t          |           dk    rt          |          | S )Nr   r   r	   )r   r   r   r   r   r   r   )r   r   s     r=   r   r     s    $'' $4yy#d))##$!!  c$ii1nnAwQ
4yyA~~###Kr?   c                    t          |          dk     r|d         nd                    d |D                       }t          | t                    st	          | d| d          t          |           |vrt          | d| d          d S )Nr	   r   z or c                 ,    g | ]}t          |          S rX   )rW   rM  s     r=   r  z)_check_sequence_input.<locals>.<listcomp>)  s    >Y>Y>Y!s1vv>Y>Y>Yr?   z  should be a sequence of length r  )r   joinr   r   r   r   )r  r  r  msgs       r=   r  r  (  s    i..1,,)A,,&++>Y>Yy>Y>Y>Y2Z2ZCa"" I4GGGGGHHH
1vvYDHH#HHHIII r?   r  c                     t          | t          j                  r| dk     rt          d| d          |  | g} nt	          | ||           d | D             S )Nr   r  z) is a single number, it must be positive.c                 ,    g | ]}t          |          S rX   r  )r  ds     r=   r  z _setup_angle.<locals>.<listcomp>8  s       E!HH   r?   )r   r   r   r   r  )r  r  r  s      r=   r  r  0  sl    !W^$$ 2q55R4RRRSSSRGay111  a    r?   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r,   a  Inverts the colors of the given image randomly with a given probability.
    If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format,
    where ... means it can have an arbitrary number of leading dimensions.
    If img is PIL Image, it is expected to be in mode "L" or "RGB".

    Args:
        p (float): probability of the image being color inverted. Default value is 0.5
    r   c                 t    t                                                       t          |            || _        d S r5   r  r  s     r=   r>   zRandomInvert.__init__E  r  r?   c                     t          j        d                                          | j        k     rt	          j        |          S |S )z
        Args:
            img (PIL Image or Tensor): Image to be inverted.

        Returns:
            PIL Image or Tensor: Randomly color inverted image.
        r   )r6   r   r   r   r^   invertr   s     r=   rs   zRandomInvert.forwardJ  s8     :a==$&((8C== 
r?   rE   c                 0    | j         j         d| j         dS r   r  r[   s    r=   rQ   zRandomInvert.__repr__V  r  r?   r   r   ru   s   @r=   r,   r,   ;  r  r?   r,   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r-   a  Posterize the image randomly with a given probability by reducing the
    number of bits for each color channel. If the image is torch Tensor, it should be of type torch.uint8,
    and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
    If img is PIL Image, it is expected to be in mode "L" or "RGB".

    Args:
        bits (int): number of bits to keep for each channel (0-8)
        p (float): probability of the image being posterized. Default value is 0.5
    r   c                     t                                                       t          |            || _        || _        d S r5   )ro   r>   r   bitsr   )r<   r  r   rM   s      r=   r>   zRandomPosterize.__init__e  s9    D!!!	r?   c                     t          j        d                                          | j        k     rt	          j        || j                  S |S )z
        Args:
            img (PIL Image or Tensor): Image to be posterized.

        Returns:
            PIL Image or Tensor: Randomly posterized image.
        r   )r6   r   r   r   r^   	posterizer  r   s     r=   rs   zRandomPosterize.forwardk  s>     :a==$&((;sDI...
r?   rE   c                 @    | j         j         d| j         d| j         dS )Nz(bits=,p=r|   )rM   rN   r  r   r[   s    r=   rQ   zRandomPosterize.__repr__w  s*    .)HHHHtvHHHHr?   r   r   ru   s   @r=   r-   r-   Z  sz              
 
 
I# I I I I I I I Ir?   r-   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r.   a  Solarize the image randomly with a given probability by inverting all pixel
    values above a threshold. If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format,
    where ... means it can have an arbitrary number of leading dimensions.
    If img is PIL Image, it is expected to be in mode "L" or "RGB".

    Args:
        threshold (float): all pixels equal or above this value are inverted.
        p (float): probability of the image being solarized. Default value is 0.5
    r   c                     t                                                       t          |            || _        || _        d S r5   )ro   r>   r   	thresholdr   )r<   r  r   rM   s      r=   r>   zRandomSolarize.__init__  s9    D!!!"r?   c                     t          j        d                                          | j        k     rt	          j        || j                  S |S )z
        Args:
            img (PIL Image or Tensor): Image to be solarized.

        Returns:
            PIL Image or Tensor: Randomly solarized image.
        r   )r6   r   r   r   r^   solarizer  r   s     r=   rs   zRandomSolarize.forward  s>     :a==$&((:c4>222
r?   rE   c                 @    | j         j         d| j         d| j         dS )Nz(threshold=r  r|   )rM   rN   r  r   r[   s    r=   rQ   zRandomSolarize.__repr__  s*    .)RRdnRRRRRRr?   r   r   ru   s   @r=   r.   r.   {  sz              
 
 
S# S S S S S S S Sr?   r.   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r/   a  Adjust the sharpness of the image randomly with a given probability. If the image is torch Tensor,
    it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.

    Args:
        sharpness_factor (float):  How much to adjust the sharpness. Can be
            any non-negative number. 0 gives a blurred image, 1 gives the
            original image while 2 increases the sharpness by a factor of 2.
        p (float): probability of the image being sharpened. Default value is 0.5
    r   c                     t                                                       t          |            || _        || _        d S r5   )ro   r>   r   sharpness_factorr   )r<   r  r   rM   s      r=   r>   zRandomAdjustSharpness.__init__  s:    D!!! 0r?   c                     t          j        d                                          | j        k     rt	          j        || j                  S |S )z
        Args:
            img (PIL Image or Tensor): Image to be sharpened.

        Returns:
            PIL Image or Tensor: Randomly sharpened image.
        r   )r6   r   r   r   r^   adjust_sharpnessr  r   s     r=   rs   zRandomAdjustSharpness.forward  s@     :a==$&((%c4+@AAA
r?   rE   c                 @    | j         j         d| j         d| j         dS )Nz(sharpness_factor=r  r|   )rM   rN   r  r   r[   s    r=   rQ   zRandomAdjustSharpness.__repr__  s-    .)``T=R``W[W]````r?   r   r   ru   s   @r=   r/   r/     sz              
 
 
a# a a a a a a a ar?   r/   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r0   a  Autocontrast the pixels of the given image randomly with a given probability.
    If the image is torch Tensor, it is expected
    to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
    If img is PIL Image, it is expected to be in mode "L" or "RGB".

    Args:
        p (float): probability of the image being autocontrasted. Default value is 0.5
    r   c                 t    t                                                       t          |            || _        d S r5   r  r  s     r=   r>   zRandomAutocontrast.__init__  r  r?   c                     t          j        d                                          | j        k     rt	          j        |          S |S )z
        Args:
            img (PIL Image or Tensor): Image to be autocontrasted.

        Returns:
            PIL Image or Tensor: Randomly autocontrasted image.
        r   )r6   r   r   r   r^   autocontrastr   s     r=   rs   zRandomAutocontrast.forward  s:     :a==$&((>#&&&
r?   rE   c                 0    | j         j         d| j         dS r   r  r[   s    r=   rQ   zRandomAutocontrast.__repr__  r  r?   r   r   ru   s   @r=   r0   r0     r  r?   r0   c                   6     e Zd ZdZd fd	Zd ZdefdZ xZS )r1   a  Equalize the histogram of the given image randomly with a given probability.
    If the image is torch Tensor, it is expected
    to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
    If img is PIL Image, it is expected to be in mode "P", "L" or "RGB".

    Args:
        p (float): probability of the image being equalized. Default value is 0.5
    r   c                 t    t                                                       t          |            || _        d S r5   r  r  s     r=   r>   zRandomEqualize.__init__  r  r?   c                     t          j        d                                          | j        k     rt	          j        |          S |S )z
        Args:
            img (PIL Image or Tensor): Image to be equalized.

        Returns:
            PIL Image or Tensor: Randomly equalized image.
        r   )r6   r   r   r   r^   equalizer   s     r=   rs   zRandomEqualize.forward  s8     :a==$&((:c??"
r?   rE   c                 0    | j         j         d| j         dS r   r  r[   s    r=   rQ   zRandomEqualize.__repr__  r  r?   r   r   ru   s   @r=   r1   r1     r  r?   r1   c            	            e Zd ZdZddej        df fd	Zedee	         dee	         dee
         d	efd
            Zded	efdZd Z xZS )r2   a  Transform a tensor image with elastic transformations.
    Given alpha and sigma, it will generate displacement
    vectors for all pixels based on random offsets. Alpha controls the strength
    and sigma controls the smoothness of the displacements.
    The displacements are added to an identity grid and the resulting grid is
    used to grid_sample from the image.

    Applications:
        Randomly transforms the morphology of objects in images and produces a
        see-through-water-like effect.

    Args:
        alpha (float or sequence of floats): Magnitude of displacements. Default is 50.0.
        sigma (float or sequence of floats): Smoothness of displacements. Default is 5.0.
        interpolation (InterpolationMode): Desired interpolation enum defined by
            :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
            If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
            The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
        fill (sequence or number): Pixel fill value for the area outside the transformed
            image. Default is ``0``. If given a number, the value is used for all bands respectively.

    g      I@g      @r   c                    t                                                       t          |            t          |t          t
          f          st          dt          |                     t          |t
                    r2t          |          dk    rt          dt          |                     t          |t
                    r9|D ]6}t          |t                    st          dt          |                     7t          |t                    rt	          |          t	          |          g}t          |t          t          f          r#t          |          dk    r|d         |d         g}|| _        t          |t          t
          f          st          dt          |                     t          |t
                    r2t          |          dk    rt          dt          |                     t          |t
                    r9|D ]6}t          |t                    st          d	t          |                     7t          |t                    rt	          |          t	          |          g}t          |t          t          f          r#t          |          dk    r|d         |d         g}|| _        t          |t                    rt          |          }|| _        t          |t          t          f          rt	          |          g}nHt          |t          t          f          rd
 |D             }nt          dt          |                     || _        d S )Nz3alpha should be float or a sequence of floats. Got r	   z3If alpha is a sequence its length should be 2. Got z*alpha should be a sequence of floats. Got r   r   z3sigma should be float or a sequence of floats. Got z3If sigma is a sequence its length should be 2. Got z*sigma should be a sequence of floats. Got c                 ,    g | ]}t          |          S rX   r  r  s     r=   r  z-ElasticTransform.__init__.<locals>.<listcomp>=  s    +++E!HH+++r?   z<fill should be int or float or a list or tuple of them. Got )ro   r>   r   r   r  r   r   r   r   r   r   r   alphar  r   r   r   r   )r<   r  r  r   r   elementrM   s         r=   r>   zElasticTransform.__init__  sM   D!!!%%!233 	a_RVW\R]R]__```eX&& 	a3u::??_SVW\S]S]__```eX&& 	b  b b!'511 b#$`QUV]Q^Q^$`$`aaab eU## 	15\\5<<0EedE]++ 	)E

a1XuQx(E
%%!233 	a_RVW\R]R]__```eX&& 	a3u::??_SVW\S]S]__```eX&& 	b  b b!'511 b#$`QUV]Q^Q^$`$`aaab eU## 	15\\5<<0EedE]++ 	)E

a1XuQx(E
mS)) 	I9-HHM*dS%L)) 	i$KK=DDtUm,, 	i++d+++DDg[_`d[e[egghhh			r?   r  r  r   rE   c                 Z   t          j        ddg|z             dz  dz
  }|d         dk    rAt          d|d         z  dz             }|dz  dk    r|dz  }t          j        |||g|          }|| d         z  |d         z  }t          j        ddg|z             dz  dz
  }|d         dk    rAt          d|d         z  dz             }|dz  dk    r|dz  }t          j        |||g|          }|| d         z  |d         z  }t          j        ||gd                              g d          S )Nr   r	   r   r     )r   r	   r  r   )r6   r   r   r^   r  concatpermute)r  r  r   dxkxdykys          r=   r   zElasticTransform.get_paramsB  s@   ZA&&*Q.8c>>Qq\A%&&BAv{{ab"Xu55B%(]T!W$ZA&&*Q.8c>>Qq\A%&&BAv{{ab"Xu55B%(]T!W$|RHa((00>>>r?   r   c                     t          j        |          \  }}}|                     | j        | j        ||g          }t          j        ||| j        | j                  S )z
        Args:
            tensor (PIL Image or Tensor): Image to be transformed.

        Returns:
            PIL Image or Tensor: Transformed image.
        )r^   r   r   r  r  elastic_transformr   r   )r<   r   r   r   r   displacements         r=   rs   zElasticTransform.forwardW  sT     +F3365tz4:OO"6<9KTYWWWr?   c                     | j         j        }|d| j         z  }|d| j         z  }|d| j         z  }|d| j         dz  }|S )Nz(alpha=r  r   r   r|   )rM   rN   r  r  r   r   r}   s     r=   rQ   zElasticTransform.__repr__c  sj    //4:///0DJ000@D,>@@@/49////r?   )rN   rT   rU   rV   r   r   r>   r   r   r  r   r   r   rs   rQ   rt   ru   s   @r=   r2   r2     s         . "<M<V]^ - - - - - -^ ?$u+ ?d5k ?c ?v ? ? ? \?(
Xf 
X 
X 
X 
X 
X      r?   r2   )r  )@r=  r   r   r2  collections.abcr   typingr   r   r   r   r6   r   accimageImportErrorutilsr   r  r   r^   r   r   __all__r   r   r   nnModuler   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.   r/   r0   r1   r2   rX   r?   r=   <module>r/     s<       $ $ $ $ $ $ / / / / / / / / / / / /       OOOO   HHH ( ' ' ' ' '       H H H H H H H H% % %P, , , , , , , ,^!. !. !. !. !. !. !. !.H. . . . . . . .:8 8 8 8 8 8 8 8:( ( ( ( ( ( ( (V$N $N $N $N $N $N $N $NNK4 K4 K4 K4 K4UX_ K4 K4 K4\> > > > > > > >>Fx Fx Fx Fx Fx%(/ Fx Fx FxR. . . . . . . .(       2( ( ( ( (%(/ ( ( (V    "   3 3 3 3 3# 3 3 3"iV iV iV iV iV iV iV iVX8 8 8 8 858? 8 8 8>8 8 8 8 8 8 8 8>]8 ]8 ]8 ]8 ]8 ]8 ]8 ]8@G G G G G G G GT,> ,> ,> ,> ,>ux ,> ,> ,>^/b /b /b /b /beho /b /b /bdR R R R R58? R R Rj} } } } }%(/ } } }@Y Y Y Y YUX_ Y Y YxZ Z Z Z Z58? Z Z Zz \  \  \  \  \  \  \  \F#8 #8 #8 #8 #8eho #8 #8 #8LE E E E EEHO E E EP? ? ? ? ?58? ? ? ?D
 
 
J J J! ! ! !8 8 8 8 858? 8 8 8>I I I I Ieho I I IBS S S S SUX_ S S SBa a a a aEHO a a aB8 8 8 8 8 8 8 8>8 8 8 8 8UX_ 8 8 8>n n n n nux n n n n ns   3 ==