U
    h                    @   s  d dl Z d dlZd dlZd dlmZmZmZmZmZm	Z	m
Z
mZmZmZ d dlZd dlZd dlmZmZ d dlmZ d dlmZ d dlmZmZmZ d dlmZ dd	l m!Z! dd
l"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ G dd de!Z0G dd de!Z1G dd deZ2G dd deZ3G dd deZ4G dd deZ5G dd deZ6G dd deZ7G dd de!Z8G dd deZ9G dd  d eZ:G d!d" d"eZ;G d#d$ d$e!Z<G d%d& d&eZ=G d'd( d(eZ>G d)d* d*eZ?G d+d, d,eZ@G d-d. d.eZAdS )/    N)
AnyCallableDictListLiteralOptionalSequenceTupleTypeUnion)
transforms
tv_tensors)box_iou)_get_perspective_coeffs)
functionalInterpolationMode	Transform)	_FillType   )_RandomApplyTransform)_check_padding_arg_check_padding_mode_arg_check_sequence_input	_get_fill_setup_angle_setup_fill_arg_setup_number_or_seq_setup_sizeget_bounding_boxeshas_allhas_anyis_pure_tensor
query_sizec                   @   s0   e Zd ZdZejZeee	ef edddZ
dS )RandomHorizontalFlipa  Horizontally flip the input with a given probability.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        p (float, optional): probability of the input being flipped. Default value is 0.5
    inptparamsreturnc                 C   s   |  tj|S N)_call_kernelFZhorizontal_flipselfr%   r&    r-   U/var/www/html/venv/lib/python3.8/site-packages/torchvision/transforms/v2/_geometry.py
_transform/   s    zRandomHorizontalFlip._transformN)__name__
__module____qualname____doc___transformsr#   _v1_transform_clsr   r   strr/   r-   r-   r-   r.   r#   !   s   r#   c                   @   s0   e Zd ZdZejZeee	ef edddZ
dS )RandomVerticalFlipa  Vertically flip the input with a given probability.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        p (float, optional): probability of the input being flipped. Default value is 0.5
    r$   c                 C   s   |  tj|S r(   )r)   r*   vertical_flipr+   r-   r-   r.   r/   A   s    zRandomVerticalFlip._transformN)r0   r1   r2   r3   r4   r7   r5   r   r   r6   r/   r-   r-   r-   r.   r7   3   s   r7   c                       sv   e Zd ZdZejZejddfe	e
ee
 df e	ee
f ee
 ee dd fddZeeeef eddd	Z  ZS )
Resizea  Resize the input to the given size.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        size (sequence, int, or None): 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).
            - If size is None, the output shape is determined by the ``max_size``
              parameter.

            .. note::
                In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
        interpolation (InterpolationMode, optional): 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 ``size`` is an int: 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).
            - If ``size`` is None: the longer edge of the image will be matched
              to max_size.  i.e, if height > width, then image will be rescaled
              to (max_size, max_size * width / height).

            This should be left to ``None`` (default) when ``size`` is a
            sequence.

        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.
    NT)sizeinterpolationmax_size	antialiasr'   c                    s   t    t|tr|g}nTt|tr<t|dkr<t|}n4|d kr`t|tsptd| dntd| d|| _|| _	|| _
|| _d S )N>   r      z7max_size must be an integer when size is None, but got z	 instead.zLsize can be an integer, a sequence of one or two integers, or None, but got )super__init__
isinstanceintr   lenlist
ValueErrorr:   r;   r<   r=   )r,   r:   r;   r<   r=   	__class__r-   r.   r@      s    




zResize.__init__r$   c                 C   s    | j tj|| j| j| j| jdS )N)r;   r<   r=   )r)   r*   resizer:   r;   r<   r=   r+   r-   r-   r.   r/      s    zResize._transform)r0   r1   r2   r3   r4   r9   r5   r   BILINEARr   rB   r   r   boolr@   r   r   r6   r/   __classcell__r-   r-   rF   r.   r9   E   s   =
r9   c                       sR   e Zd ZdZejZeee	e f d fddZ
eeeef edddZ  ZS )
CenterCropa  Crop the input at the center.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    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]).
    r:   c                    s   t    t|dd| _d S N3Please provide only two dimensions (h, w) for size.	error_msgr?   r@   r   r:   r,   r:   rF   r-   r.   r@      s    
zCenterCrop.__init__r$   c                 C   s   | j tj|| jdS )N)Zoutput_size)r)   r*   Zcenter_cropr:   r+   r-   r-   r.   r/      s    zCenterCrop._transform)r0   r1   r2   r3   r4   rL   r5   r   rB   r   r@   r   r   r6   r/   rK   r-   r-   rF   r.   rL      s   rL   c                       s   e Zd ZdZejZddejdfe	e
ee
 f eeef eeef e	ee
f ee dd fddZee eeef d	d
dZeeeef edddZ  ZS )RandomResizedCropa&  Crop a random portion of the input and resize it to a given size.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    A crop of the original input 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, optional): 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, optional): lower and upper bounds for the random aspect ratio of the crop, before
            resizing.
        interpolation (InterpolationMode, optional): 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?TN)r:   scaleratior;   r=   r'   c                    s   t    t|dd| _t|ts*tdt|ts<td|d |d ks\|d |d krftd || _	|| _
|| _|| _tt| j
| _d S )NrO   rP   zScale should be a sequencezRatio should be a sequencer   r   z,Scale and ratio should be of kind (min, max))r?   r@   r   r:   rA   r   	TypeErrorwarningswarnrV   rW   r;   r=   torchlogtensor
_log_ratio)r,   r:   rV   rW   r;   r=   rF   r-   r.   r@      s    


 
zRandomResizedCrop.__init__flat_inputsr'   c                 C   s  t |\}}|| }| j}tdD ]}|td| jd | jd   }ttd|d |d  }t	t
t|| }	t	t
t|| }
d|	  k r|kr"n q"d|
  k r|kr"n q"tjd||
 d dd }tjd||	 d dd } qq"t|t| }|t| jk rH|}	t	t
|	t| j }
n4|t| jkrt|}
t	t
|
t| j }	n|}	|}
||
 d }||	 d }t|||
|	dS )N
   r   r   r   rM   r>   topleftheightwidth)r"   r^   ranger[   emptyuniform_rV   itemexprB   roundmathsqrtrandintfloatminrW   maxdict)r,   r`   rf   rg   ZareaZ	log_ratio_Ztarget_areaaspect_ratiowhijZin_ratior-   r-   r.   _get_params  s:    &
0zRandomResizedCrop._get_paramsr$   c                 C   s$   | j tj|f|| j| j| jdS )Nr:   r;   r=   )r)   r*   Zresized_cropr:   r;   r=   r+   r-   r-   r.   r/   5  s        zRandomResizedCrop._transform)r0   r1   r2   r3   r4   rT   r5   r   rI   r   rB   r   r	   rq   r   rJ   r@   r   r   r   r6   r{   r/   rK   r-   r-   rF   r.   rT      s    /


&rT   c                       s   e Zd ZdZejZeee	e f dd fddZ
eeeeed fddZeeeef ed	d
dZee ddddZ  ZS )FiveCropa  Crop the image or video into four corners and the central crop.

    If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a
    :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions.
    For example, the image can have ``[..., C, H, W]`` shape.

    .. 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:
        >>> class BatchMultiCrop(transforms.Transform):
        ...     def forward(self, sample: Tuple[Tuple[Union[tv_tensors.Image, tv_tensors.Video], ...], int]):
        ...         images_or_videos, labels = sample
        ...         batch_size = len(images_or_videos)
        ...         image_or_video = images_or_videos[0]
        ...         images_or_videos = tv_tensors.wrap(torch.stack(images_or_videos), like=image_or_video)
        ...         labels = torch.full((batch_size,), label, device=images_or_videos.device)
        ...         return images_or_videos, labels
        ...
        >>> image = tv_tensors.Image(torch.rand(3, 256, 256))
        >>> label = 3
        >>> transform = transforms.Compose([transforms.FiveCrop(224), BatchMultiCrop()])
        >>> images, labels = transform(image, label)
        >>> images.shape
        torch.Size([5, 3, 224, 224])
        >>> labels
        tensor([3, 3, 3, 3, 3])
    N)r:   r'   c                    s   t    t|dd| _d S rN   rR   rS   rF   r-   r.   r@   b  s    
zFiveCrop.__init__r   r%   argskwargsr'   c                    sJ   t |tjtjfr4tt| j dt|j d t j	||f||S Nz:() is currently passing through inputs of type tv_tensors.z(. This will likely change in the future.
rA   r   BoundingBoxesMaskrY   rZ   typer0   r?   r)   r,   r   r%   r   r   rF   r-   r.   r)   f  s
    zFiveCrop._call_kernelr$   c                 C   s   |  tj|| jS r(   )r)   r*   Z	five_cropr:   r+   r-   r-   r.   r/   n  s    zFiveCrop._transformr_   c                 C   s*   t |tjtjr&tdt| j dd S Nz1BoundingBoxes'es and Mask's are not supported by z()r    r   r   r   rX   r   r0   r,   r`   r-   r-   r.   _check_inputsq  s    zFiveCrop._check_inputs)r0   r1   r2   r3   r4   r}   r5   r   rB   r   r@   r   r   r)   r   r6   r/   r   r   rK   r-   r-   rF   r.   r}   ;  s   $ r}   c                       s   e Zd ZdZejZdeee	e f e
dd fddZeeeeed fdd	Zee dd
ddZeeeef edddZ  ZS )TenCropa  Crop the image or video into four corners and the central crop plus the flipped version of
    these (horizontal flipping is used by default).

    If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a
    :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions.
    For example, the image can have ``[..., C, H, W]`` shape.

    See :class:`~torchvision.transforms.v2.FiveCrop` for an example.

    .. 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, optional): Use vertical flipping instead of horizontal
    FN)r:   r8   r'   c                    s"   t    t|dd| _|| _d S rN   )r?   r@   r   r:   r8   )r,   r:   r8   rF   r-   r.   r@     s    
zTenCrop.__init__r~   c                    sJ   t |tjtjfr4tt| j dt|j d t j	||f||S r   r   r   rF   r-   r.   r)     s
    zTenCrop._call_kernelr_   c                 C   s*   t |tjtjr&tdt| j dd S r   r   r   r-   r-   r.   r     s    zTenCrop._check_inputsr$   c                 C   s   | j tj|| j| jdS )N)r8   )r)   r*   Zten_cropr:   r8   r+   r-   r-   r.   r/     s    zTenCrop._transform)F)r0   r1   r2   r3   r4   r   r5   r   rB   r   rJ   r@   r   r   r)   r   r   r   r6   r/   rK   r-   r-   rF   r.   r   v  s   $r   c                       s   e Zd ZdZejZeee	f d fddZ
deeee f eeeeeef ef f ed dd	 fd
dZe	eee	f e	dddZ  ZS )Pada  Pad the input on all sides with the given "pad" value.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    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 or dict, optional): Pixel fill value used when the  ``padding_mode`` is constant.
            Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
            Fill value can be also a dictionary mapping data type to the fill value, e.g.
            ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
            ``Mask`` will be filled with 0.
        padding_mode (str, optional): 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.

            - 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'   c                    sH   t   }|d d ksDt|d ttfsDtt| j d| j d|S )Nfill5() can only be scripted for a scalar `fill`, but got .)	r?    _extract_params_for_v1_transformrA   rB   rq   rE   r   r0   r   )r,   r&   rF   r-   r.   r     s    
z$Pad._extract_params_for_v1_transformr   constantr   edgeZreflectZ	symmetricN)paddingr   padding_moder'   c                    sL   t    t| t| t|ts,t|}|| _|| _t	|| _
|| _d S r(   )r?   r@   r   r   rA   rB   rD   r   r   r   _fillr   )r,   r   r   r   rF   r-   r.   r@     s    


zPad.__init__r$   c                 C   s*   t | jt|}| jtj|| j|| jdS )Nr   r   r   )r   r   r   r)   r*   padr   r   r,   r%   r&   r   r-   r-   r.   r/     s    zPad._transform)r   r   )r0   r1   r2   r3   r4   r   r5   r   r6   r   r   r   rB   r   r   r
   r   r@   r/   rK   r-   r-   rF   r.   r     s   %  r   c                       s   e Zd ZdZdeeeeeef ef f e	e
 e
dd fddZee eeef d	d
dZeeeef edddZ  ZS )RandomZoomOuta4   "Zoom out" transformation from
    `"SSD: Single Shot MultiBox Detector" <https://arxiv.org/abs/1512.02325>`_.

    This transformation randomly pads images, videos, bounding boxes and masks creating a zoom out effect.
    Output spatial size is randomly sampled from original size up to a maximum size configured
    with ``side_range`` parameter:

    .. code-block:: python

        r = uniform_sample(side_range[0], side_range[1])
        output_width = input_width * r
        output_height = input_height * r

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        fill (number or tuple or dict, optional): Pixel fill value used when the  ``padding_mode`` is constant.
            Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
            Fill value can be also a dictionary mapping data type to the fill value, e.g.
            ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
            ``Mask`` will be filled with 0.
        side_range (sequence of floats, optional): tuple of two floats defines minimum and maximum factors to
            scale the input size.
        p (float, optional): probability that the zoom operation will be performed.
    r   rU   g      @      ?N)r   
side_rangepr'   c                    sb   t  j|d || _t|| _t|ddd || _|d dk sN|d |d kr^td| d	d S )
Nr   r   r>   	req_sizesr   rU   r   zInvalid side range provided r   )r?   r@   r   r   r   r   r   rE   )r,   r   r   r   rF   r-   r.   r@   	  s    
zRandomZoomOut.__init__r_   c                 C   s   t |\}}| jd td| jd | jd    }t|| }t|| }td}t|| |d  }t|| |d  }|||  }	|||  }
|||	|
g}t|dS )Nr   r   r>   )r   )r"   r   r[   randrB   rt   )r,   r`   orig_horig_wrZcanvas_widthZcanvas_heightre   rd   rightbottomr   r-   r-   r.   r{     s    (
zRandomZoomOut._get_paramsr$   c                 C   s*   t | jt|}| jtj|f|d|iS )Nr   )r   r   r   r)   r*   r   r   r-   r-   r.   r/   *  s    zRandomZoomOut._transform)r   r   r   )r0   r1   r2   r3   r   r   r   r
   r6   r   rq   r@   r   r   r{   r/   rK   r-   r-   rF   r.   r     s      r   c                       s   e Zd ZdZejZejdddfe	e
jef e	eef eeee  e	eee	eef ef f dd fddZee eeef dd	d
Zeeeef edddZ  ZS )RandomRotationa	  Rotate the input by angle.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    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, optional): 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 (see note below) 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.

            .. note::

                In theory, setting ``center`` has no effect if ``expand=True``, since the image center will become the
                center of rotation. In practice however, due to numerical precision, this can lead to off-by-one
                differences of the resulting image size compared to using the image center in the first place. Thus, when
                setting ``expand=True``, it's best to leave ``center=None`` (default).
        fill (number or tuple or dict, optional): Pixel fill value used when the  ``padding_mode`` is constant.
            Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
            Fill value can be also a dictionary mapping data type to the fill value, e.g.
            ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
            ``Mask`` will be filled with 0.

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

    FNr   )degreesr;   expandcenterr   r'   c                    sV   t    t|ddd| _|| _|| _|| _t|| _|d k	rLt	|ddd || _
d S )Nr   r   namer   r   r   )r?   r@   r   r   r;   r   r   r   r   r   r   )r,   r   r;   r   r   r   rF   r-   r.   r@   X  s    

zRandomRotation.__init__r_   c                 C   s,   t d| jd | jd  }t|dS )Nr   r   )angle)r[   ri   rj   r   rk   rt   )r,   r`   r   r-   r-   r.   r{   m  s    "zRandomRotation._get_paramsr$   c                 C   s6   t | jt|}| jtj|f|| j| j| j|dS )N)r;   r   r   r   )	r   r   r   r)   r*   rotater;   r   r   r   r-   r-   r.   r/   q  s    zRandomRotation._transform)r0   r1   r2   r3   r4   r   r5   r   NEARESTr   numbersNumberr   rB   rJ   r   r   rq   r   r   r
   r6   r@   r   r{   r/   rK   r-   r-   rF   r.   r   /  s    &

r   c                       s   e Zd ZdZejZdddejddfe	e
jef eee  eee  ee	eeee f  e	eef e	eee	eef ef f eee  dd fddZee eeef ddd	Zeeeef ed
ddZ  ZS )RandomAffineaf  Random affine transformation the input keeping center invariant.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    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, optional): 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 (number or tuple or dict, optional): Pixel fill value used when the  ``padding_mode`` is constant.
            Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
            Fill value can be also a dictionary mapping data type to the fill value, e.g.
            ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
            ``Mask`` will be filled with 0.
        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   )r   	translaterV   shearr;   r   r   r'   c           
         s   t    t|ddd| _|d k	rXt|ddd |D ]"}d|  krLdks4n tdq4|| _|d k	rt|d	dd |D ]}	|	d
krxtdqx|| _|d k	rt|ddd| _n|| _|| _	|| _
t|| _|d k	rt|ddd || _d S )Nr   r   r   r   r           rU   z,translation values should be between 0 and 1rV   r   zscale values should be positiver   )r>      r   )r?   r@   r   r   r   rE   r   rV   r   r;   r   r   r   r   )
r,   r   r   rV   r   r;   r   r   tsrF   r-   r.   r@     s.    




zRandomAffine.__init__r_   c                 C   s\  t |\}}td| jd | jd  }| jd k	rt| jd | }t| jd | }tt	td| | }tt	td| | }||f}	nd}	| j
d k	rtd| j
d | j
d  }
nd}
d }}| jd k	rDtd| jd | jd  }t| jdkrDtd| jd | jd  }||f}t||	|
|d	S )
Nr   r   )r   r   rU   r   r   r>      )r   r   rV   r   )r"   r[   ri   rj   r   rk   r   rq   rB   rm   rV   r   rC   rt   )r,   r`   rf   rg   r   Zmax_dxZmax_dyZtxtyr   rV   Zshear_xZshear_yr   r-   r-   r.   r{     s&    "
  

$""zRandomAffine._get_paramsr$   c                 C   s2   t | jt|}| jtj|f|| j|| jdS )N)r;   r   r   )r   r   r   r)   r*   Zaffiner;   r   r   r-   r-   r.   r/     s    zRandomAffine._transform)r0   r1   r2   r3   r4   r   r5   r   r   r   r   r   r   r   rq   rB   r   r   r
   r6   r   r@   r   r{   r/   rK   r-   r-   rF   r.   r   ~  s(   '



'r   c                
       s   e Zd ZdZejZeee	f d fddZ
deeee f eeeee f  eeeeeeef ef f ed	 dd
 fddZee	 eee	f dddZe	eee	f e	dddZ  ZS )
RandomCropa
  Crop the input at a random location.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    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, optional): 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 or dict, optional): Pixel fill value used when the  ``padding_mode`` is constant.
            Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
            Fill value can be also a dictionary mapping data type to the fill value, e.g.
            ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
            ``Mask`` will be filled with 0.
        padding_mode (str, optional): 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.

            - 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   c                    sv   t   }|d d ksDt|d ttfsDtt| j d| j d| j	}|d k	rj|\}}}}||||g}||d< |S )Nr   r   r   r   )
r?   r   rA   rB   rq   rE   r   r0   r   r   )r,   r&   r   pad_left	pad_rightpad_top
pad_bottomrF   r-   r.   r   %  s    
z+RandomCrop._extract_params_for_v1_transformNFr   r   r   )r:   r   pad_if_neededr   r   r'   c                    sr   t    t|dd| _|s$|d k	r<|d k	r4t| t| |rLtj|nd | _	|| _
|| _t|| _|| _d S rN   )r?   r@   r   r:   r   r   r*   Z	_geometryZ_parse_pad_paddingr   r   r   r   r   r   )r,   r:   r   r   r   r   rF   r-   r.   r@   3  s    

zRandomCrop.__init__r_   c              	   C   s  t |\}}| jd k	r>| j\}}}}||| 7 }||| 7 }nd } } }}| j\}}	| jr||k r|| }
||
7 }||
7 }|d|
 7 }||	k r|	| }
||
7 }||
7 }|d|
 7 }||k s||	k rtd||	f d| jd k	rdnd d||f d||||g}t|}||kr6d	ttjd|| d
 ddfnd\}}||	krhd	ttjd||	 d
 ddfnd\}}t	|pz|||||	||dS )Nr   r>   zRequired crop size z is larger than zpadded  zinput image size r   Tr   r-   rM   )Fr   )
needs_croprd   re   rf   rg   	needs_padr   )
r"   r   r:   r   rE   anyrB   r[   rp   rt   )r,   r`   Zpadded_heightZpadded_widthr   r   r   r   Zcropped_heightZcropped_widthdiffr   r   Zneeds_vert_croprd   Zneeds_horz_cropre   r-   r-   r.   r{   J  sR    

,$$zRandomCrop._get_paramsr$   c                 C   sh   |d r4t | jt|}| jtj||d || jd}|d rd| jtj||d |d |d |d d	}|S )
Nr   r   r   r   rd   re   rf   rg   rc   )r   r   r   r)   r*   r   r   cropr   r-   r-   r.   r/     s         zRandomCrop._transform)NFr   r   )r0   r1   r2   r3   r4   r   r5   r   r6   r   r   r   rB   r   r   rJ   r   r
   r   r@   r   r{   r/   rK   r-   r-   rF   r.   r     s"   ,    :r   c                
       s   e Zd ZdZejZddejdfe	e	e
eef e
eee
eef ef f dd fddZee eeef dd	d
Zeeeef edddZ  ZS )RandomPerspectivea&  Perform a random perspective transformation of the input with a given probability.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        distortion_scale (float, optional): argument to control the degree of distortion and ranges from 0 to 1.
            Default is 0.5.
        p (float, optional): probability of the input being transformed. Default is 0.5.
        interpolation (InterpolationMode, optional): 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 (number or tuple or dict, optional): Pixel fill value used when the  ``padding_mode`` is constant.
            Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
            Fill value can be also a dictionary mapping data type to the fill value, e.g.
            ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
            ``Mask`` will be filled with 0.
    r   r   N)distortion_scaler   r;   r   r'   c                    sL   t  j|d d|  kr"dks,n td|| _|| _|| _t|| _d S )Nr   r   r   z9Argument distortion_scale value should be between 0 and 1)r?   r@   rE   r   r;   r   r   r   )r,   r   r   r;   r   rF   r-   r.   r@     s    zRandomPerspective.__init__r_   c                 C   s>  t |\}}| j}|d }|d }t|| d }t|| d }ttjd|ddttjd|ddg}	ttj|| |ddttjd|ddg}
ttj|| |ddttj|| |ddg}ttjd|ddttj|| |ddg}ddg|d dg|d |d gd|d gg}|	|
||g}t||}t|dS )Nr>   r   r   rb   rM   )Zcoefficients)r"   r   rB   r[   rp   r   rt   )r,   r`   rf   rg   r   Zhalf_heightZ
half_widthZbound_heightZbound_widthZtopleftZtoprightZbotrightZbotleftstartpoints	endpointsZperspective_coeffsr-   r-   r.   r{     s,    ,
zRandomPerspective._get_paramsr$   c                 C   s2   t | jt|}| jtj|fd d || jd|S )N)r   r   r   r;   )r   r   r   r)   r*   Zperspectiver;   r   r-   r-   r.   r/     s    zRandomPerspective._transform)r0   r1   r2   r3   r4   r   r5   r   rI   rq   r   rB   r   r   r
   r6   r@   r   r   r{   r/   rK   r-   r-   rF   r.   r     s   
r   c                
       s   e Zd ZdZejZddejdfe	e
ee
 f e	e
ee
 f e	eef e	eee	eef ef f dd fddZee eeef d	d
dZeeeef edddZ  ZS )ElasticTransforma	  Transform the input with elastic transformations.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    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 transform the input.

    .. note::
        Implementation to transform bounding boxes is approximative (not exact).
        We construct an approximation of the inverse grid as ``inverse_grid = identity - displacement``.
        This is not an exact inverse of the grid used to transform images, i.e. ``grid = identity + displacement``.
        Our assumption is that ``displacement * displacement`` is small and can be ignored.
        Large displacements would lead to large errors in the approximation.

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

    Args:
        alpha (float or sequence of floats, optional): Magnitude of displacements. Default is 50.0.
        sigma (float or sequence of floats, optional): Smoothness of displacements. Default is 5.0.
        interpolation (InterpolationMode, optional): 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 (number or tuple or dict, optional): Pixel fill value used when the  ``padding_mode`` is constant.
            Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
            Fill value can be also a dictionary mapping data type to the fill value, e.g.
            ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
            ``Mask`` will be filled with 0.
    g      I@g      @r   N)alphasigmar;   r   r'   c                    s<   t    t|d| _t|d| _|| _|| _t|| _d S )Nr   r   )	r?   r@   r   r   r   r;   r   r   r   )r,   r   r   r;   r   rF   r-   r.   r@     s    
zElasticTransform.__init__r_   c                 C   s<  t t|}tddg| d d }| jd dkrztd| jd  d }|d dkr^|d7 }| tj|||gt | j}|| j	d  |d  }tddg| d d }| jd dkrtd| jd  d }|d dkr|d7 }| tj|||gt | j}|| j	d  |d  }t
||gdddddg}t|dS )Nr   r>   r   r      r   )displacement)rD   r"   r[   r   r   rB   r)   r*   Zgaussian_blurr   concatZpermutert   )r,   r`   r:   ZdxZkxZdykyr   r-   r-   r.   r{     s"    zElasticTransform._get_paramsr$   c                 C   s.   t | jt|}| jtj|f||| jdS )N)r   r;   )r   r   r   r)   r*   Zelasticr;   r   r-   r-   r.   r/   5  s    zElasticTransform._transform)r0   r1   r2   r3   r4   r   r5   r   rI   r   rq   r   rB   r   r   r
   r6   r@   r   r   r{   r/   rK   r-   r-   rF   r.   r     s   &
r   c                       s   e Zd ZdZdeeeeeee  ed fd	d
Zee	 ddddZ
ee	 eee	f dddZe	eee	f e	dddZ  ZS )RandomIoUCropaC  Random IoU crop transformation from
    `"SSD: Single Shot MultiBox Detector" <https://arxiv.org/abs/1512.02325>`_.

    This transformation requires an image or video data and ``tv_tensors.BoundingBoxes`` in the input.

    .. warning::
        In order to properly remove the bounding boxes below the IoU threshold, `RandomIoUCrop`
        must be followed by :class:`~torchvision.transforms.v2.SanitizeBoundingBoxes`, either immediately
        after or later in the transforms pipeline.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        min_scale (float, optional): Minimum factors to scale the input size.
        max_scale (float, optional): Maximum factors to scale the input size.
        min_aspect_ratio (float, optional): Minimum aspect ratio for the cropped image or video.
        max_aspect_ratio (float, optional): Maximum aspect ratio for the cropped image or video.
        sampler_options (list of float, optional): List of minimal IoU (Jaccard) overlap between all the boxes and
            a cropped image or video. Default, ``None`` which corresponds to ``[0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]``
        trials (int, optional): Number of trials to find a crop for a given value of minimal IoU (Jaccard) overlap.
            Default, 40.
    333333?rU   r          @N(   )	min_scale	max_scalemin_aspect_ratiomax_aspect_ratiosampler_optionstrialsc                    sL   t    || _|| _|| _|| _|d kr<dddddddg}|| _|| _d S )Nr   皙?r   r   gffffff?g?rU   )r?   r@   r   r   r   r   optionsr   )r,   r   r   r   r   r   r   rF   r-   r.   r@   [  s    	
zRandomIoUCrop.__init__r_   c                 C   s8   t |tjr t|tjjtjts4tt| j	 dd S )Nzk() requires input sample to contain tensor or PIL images and bounding boxes. Sample can also contain masks.)
r   r   r   r    PILZImager!   rX   r   r0   r   r-   r-   r.   r   o  s    
zRandomIoUCrop._check_inputsc                 C   s  t |\}}t|}ttjdt| jdd}| j| }|dkrFt S t| j	D ]z}| j
| j| j
 td  }t||d  }	t||d  }
|	|
 }| j|  kr| jksqP qPtd}t||	 |d  }t||
 |d  }||	 }||
 }||ksP||krqPt|tj|jtjj}d|d |d	   }d|d
 |d   }||k ||k @ ||k @ ||k @ }| s|qP|| }t|tj||||gg|j|jd}| |k rqPt|||
|	|d  S qd S )Nr   rb   )lowhighr:   rU   r>   r   r   ).r   ).r>   ).r   ).r   )dtypedevice)rd   re   rf   rg   is_within_crop_area)r"   r   rB   r[   rp   rC   r   rt   rh   r   r   r   r   r   r   r*   Zconvert_bounding_box_formatZas_subclassZTensorformatr   ZBoundingBoxFormatZXYXYr   r   r]   r   r   rs   )r,   r`   r   r   ZbboxesidxZmin_jaccard_overlapru   r   Znew_wZnew_hrv   re   rd   r   r   Zxyxy_bboxesZcxcyr   Ziousr-   r-   r.   r{   y  sL    


 
zRandomIoUCrop._get_paramsr$   c                 C   sV   t |dk r|S | jtj||d |d |d |d d}t|tjrRd||d  < |S )	Nr   rd   re   rf   rg   rc   r   r   )rC   r)   r*   r   rA   r   r   )r,   r%   r&   outputr-   r-   r.   r/     s         zRandomIoUCrop._transform)r   rU   r   r   Nr   )r0   r1   r2   r3   rq   r   r   rB   r@   r   r   r   r6   r{   r/   rK   r-   r-   rF   r.   r   @  s$         

4r   c                       s   e Zd ZdZdejdfeeef eeef e	eef e
e d fddZee eeef ddd	Zeeeef ed
ddZ  ZS )ScaleJittera	  Perform Large Scale Jitter on the input according to
    `"Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation" <https://arxiv.org/abs/2012.07177>`_.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        target_size (tuple of int): Target size. This parameter defines base scale for jittering,
            e.g. ``min(target_size[0] / width, target_size[1] / height)``.
        scale_range (tuple of float, optional): Minimum and maximum of the scale range. Default, ``(0.1, 2.0)``.
        interpolation (InterpolationMode, optional): 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.
    )r   r   T)target_sizescale_ranger;   r=   c                    s&   t    || _|| _|| _|| _d S r(   )r?   r@   r   r   r;   r=   )r,   r   r   r;   r=   rF   r-   r.   r@     s
    
zScaleJitter.__init__r_   c                 C   s|   t |\}}| jd td| jd | jd    }t| jd | | jd | | }t|| }t|| }t||fdS )Nr   r   rM   )r"   r   r[   r   rr   r   rB   rt   )r,   r`   orig_height
orig_widthrV   r   	new_width
new_heightr-   r-   r.   r{     s    ("zScaleJitter._get_paramsr$   c                 C   s   | j tj||d | j| jdS Nr:   r|   r)   r*   rH   r;   r=   r+   r-   r-   r.   r/     s        zScaleJitter._transform)r0   r1   r2   r3   r   rI   r	   rB   rq   r   r   rJ   r@   r   r   r   r6   r{   r/   rK   r-   r-   rF   r.   r     s   (



r   c                       s   e Zd ZdZdejdfeee e	e ef e
e eeef e
e d fddZee eeef ddd	Zeeeef ed
ddZ  ZS )RandomShortestSizea  Randomly resize the input.

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        min_size (int or sequence of int): Minimum spatial size. Single integer value or a sequence of integer values.
        max_size (int, optional): Maximum spatial size. Default, None.
        interpolation (InterpolationMode, optional): 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.
    NT)min_sizer<   r;   r=   c                    s:   t    t|tr|gnt|| _|| _|| _|| _d S r(   )	r?   r@   rA   rB   rD   r   r<   r;   r=   r,   r   r<   r;   r=   rF   r-   r.   r@   %  s
    
zRandomShortestSize.__init__r_   c                 C   s|   t |\}}| jttt| jd }|t|| }| jd k	rVt|| jt|| }t|| }t|| }t	||fdS Nr-   rM   )
r"   r   rB   r[   rp   rC   rr   r<   rs   rt   )r,   r`   r   r   r   r   r   r   r-   r-   r.   r{   2  s    
zRandomShortestSize._get_paramsr$   c                 C   s   | j tj||d | j| jdS r   r   r+   r-   r-   r.   r/   ?  s        zRandomShortestSize._transform)r0   r1   r2   r3   r   rI   r   r   rB   r	   r   rJ   r@   r   r   r6   r{   r/   rK   r-   r-   rF   r.   r     s   &
r   c                       sx   e Zd ZdZejdfeeeeef ee	 dd fddZ
ee eeef ddd	Zeeeef ed
ddZ  ZS )RandomResizea
  Randomly resize the input.

    This transformation can be used together with ``RandomCrop`` as data augmentations to train
    models on image segmentation task.

    Output spatial size is randomly sampled from the interval ``[min_size, max_size]``:

    .. code-block:: python

        size = uniform_sample(min_size, max_size)
        output_width = size
        output_height = size

    If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
    :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
    it can have arbitrary number of leading batch dimensions. For example,
    the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.

    Args:
        min_size (int): Minimum output size for random sampling
        max_size (int): Maximum output size for random sampling
        interpolation (InterpolationMode, optional): 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.
    TN)r   r<   r;   r=   r'   c                    s&   t    || _|| _|| _|| _d S r(   )r?   r@   r   r<   r;   r=   r   rF   r-   r.   r@   t  s
    
zRandomResize.__init__r_   c                 C   s"   t t| j| jd}t|gdS r   )rB   r[   rp   r   r<   rt   )r,   r`   r:   r-   r-   r.   r{     s    zRandomResize._get_paramsr$   c                 C   s   | j tj||d | j| jdS )Nr:   )r;   r=   r   r+   r-   r-   r.   r/     s        zRandomResize._transform)r0   r1   r2   r3   r   rI   rB   r   r   rJ   r@   r   r   r   r6   r{   r/   rK   r-   r-   rF   r.   r   E  s   2
r   )Brn   r   rY   typingr   r   r   r   r   r   r   r	   r
   r   Z	PIL.Imager   r[   Ztorchvisionr   r4   r   Ztorchvision.ops.boxesr   Z!torchvision.transforms.functionalr   Ztorchvision.transforms.v2r   r*   r   r   Z+torchvision.transforms.v2.functional._utilsr   r/   r   Z_utilsr   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r7   r9   rL   rT   r}   r   r   r   r   r   r   r   r   r   r   r   r   r-   r-   r-   r.   <module>   s>   0<ew;-HDOx UZ~CD