3
Á3W^»z  ã               @   sº  d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	 yd dl
Z
W n ek
r`   dZ
Y nX d dlZd dlZd dlZd dlZejdBk ršejZejZnejjZejjZdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ ZdCdd„ZdDdd„Zejfdd„Zdd„ ZdEdd„Zdd„ Z dd„ Z!ejfdd „Z"d!d"„ Z#d#d$„ Z$ej%fd%d&„Z&d'd(„ Z'd)d*„ Z(dFd+d,„Z)d-d.„ Z*d/d0„ Z+d1d2„ Z,d3d4„ Z-dGd6d7„Z.dHd8d9„Z/d:d;„ Z0dId<d=„Z1dJd>d?„Z2dKd@dA„Z3dS )Lé    )ÚdivisionN)ÚImageÚImageOpsÚImageEnhanceÚPILLOW_VERSIONé   c             C   s*   t d k	rt| tjt jfƒS t| tjƒS d S )N)ÚaccimageÚ
isinstancer   )Úimg© r   úH/tmp/pip-build-7wfi2gtz/torchvision/torchvision/transforms/functional.pyÚ_is_pil_image   s    r   c             C   s   t j| ƒo| jƒ dkS )Nr   )ÚtorchZ	is_tensorÚ
ndimension)r
   r   r   r   Ú_is_tensor_image   s    r   c             C   s   t | tjƒS )N)r	   ÚnpÚndarray)r
   r   r   r   Ú	_is_numpy"   s    r   c             C   s
   | j dkS )Né   r   >   r   r   )Úndim)r
   r   r   r   Ú_is_numpy_image&   s    r   c             C   s  t | ƒpt| ƒs"tdjt| ƒƒƒ‚t| ƒrDt| ƒ rDtdj| jƒƒ‚t| t	j
ƒrž| jdkrp| dd…dd…df } tj| jdƒƒ}t|tjƒrš|jƒ jdƒS |S tdk	rât| tjƒrât	j| j| j| jgt	jd�}| j|ƒ tj|ƒS | jd	k�rtjt	j| t	jd
d�ƒ}nŒ| jdk�r.tjt	j| t	jd
d�ƒ}nf| jdk�rTtjt	j| t	jd
d�ƒ}n@| jdk�r~dtjt	j| t	jd
d�ƒ }ntjtjj| j ƒ ƒƒ}| jdk�r¦d}n| jdk�r¸d}n
t!| jƒ}|j"| j#d | j#d |ƒ}|jddƒjddƒj$ƒ }t|tjƒ�r|jƒ jdƒS |S dS )zéConvert a ``PIL Image`` or ``numpy.ndarray`` to tensor.

    See ``ToTensor`` for more details.

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

    Returns:
        Tensor: Converted image.
    z*pic should be PIL Image or ndarray. Got {}z1pic should be 2/3 dimensional. Got {} dimensions.r   Nr   é   éÿ   )ÚdtypeÚIF)ÚcopyzI;16ÚFÚ1ÚYCbCrr   )r   r   r   )%r   r   Ú	TypeErrorÚformatÚtyper   Ú
ValueErrorr   r	   r   r   r   Z
from_numpyÚ	transposeZ
ByteTensorÚfloatÚdivr   r   ÚzerosZchannelsÚheightÚwidthÚfloat32ZcopytoÚmodeÚarrayÚint32Úint16Úuint8ZByteStorageÚfrom_bufferÚtobytesÚlenÚviewÚsizeÚ
contiguous)Úpicr
   ZnppicZnchannelr   r   r   Ú	to_tensor*   sD    



r6   c             C   sÜ  t | tjƒpt | tjƒs,tdjt| ƒƒƒ‚n‚t | tjƒrp| jƒ dkrXt	dj| jƒ ƒƒ‚q®| jƒ dkr®| j
dƒ} n>t | tjƒr®| jdkr˜t	dj| jƒƒ‚n| jdkr®tj| dƒ} | }t | tjƒrÔ|dkrÔ| jdƒjƒ } t | tjƒ� ròtj| jƒ dƒ}t |tjƒ�std	d
jt|ƒƒ ƒ‚|jd dk�r¼d}|dd…dd…df }|jtjk�rTd}n:|jtjk�rhd}n&|jtjk�r|d}n|jtjk�rŽd}|dk	�r¶||k�r¶t	dj|tj|ƒƒ‚|}nø|jd dk�rdg}|dk	�rô||k�rôt	dj|ƒƒ‚|dk�r´|jtjk�r´d}n¢|jd dk�rldddg}|dk	�rN||k�rNt	dj|ƒƒ‚|dk�r´|jtjk�r´d}nHdddg}|dk	�r˜||k�r˜t	dj|ƒƒ‚|dk�r´|jtjk�r´d}|dk�rÎtdj|jƒƒ‚tj||d�S ) aË  Convert a tensor or an ndarray to PIL Image.

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

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

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

    Returns:
        PIL Image: Image converted to PIL Image.
    z(pic should be Tensor or ndarray. Got {}.r   r   z1pic should be 2/3 dimensional. Got {} dimensions.r   r   r   r   z3Input pic must be a torch.Tensor or NumPy ndarray, znot {}NÚLzI;16r   z<Incorrect mode ({}) supplied for input type {}. Should be {}ZLAz)Only modes {} are supported for 2D inputsé   ZRGBAZCMYKZRGBXz)Only modes {} are supported for 4D inputsÚRGBr   ÚHSVz)Only modes {} are supported for 3D inputszInput type {} is not supported)r*   >   r   r   >   r   r   )r   r   r   )r	   r   ÚTensorr   r   r   r    r!   r   r"   Z	unsqueezer   Zexpand_dimsZFloatTensorÚmulZbyter#   ÚnumpyÚshaper   r.   r-   r,   r)   r   Ú	fromarray)r5   r*   ZnpimgZexpected_modeZpermitted_2_channel_modesZpermitted_4_channel_modesZpermitted_3_channel_modesr   r   r   Úto_pil_imageh   sn    




r@   Fc             C   sv   t | ƒstdƒ‚|s| jƒ } | j}tj||| jd�}tj||| jd�}| j|dd…ddf ƒj|dd…ddf ƒ | S )aM  Normalize a tensor image with mean and standard deviation.

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

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

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

    Returns:
        Tensor: Normalized Tensor image.
    ztensor is not a torch image.)r   ÚdeviceN)	r   r   Úcloner   r   Z	as_tensorrA   Zsub_Zdiv_)ÚtensorZmeanZstdÚinplacer   r   r   r   Ú	normalize¿   s    ,rE   c             C   sì   t | ƒstdjt| ƒƒƒ‚t|tƒp8t|tƒo8t|ƒdksHtdj|ƒƒ‚t|tƒrÒ| j\}}||krl||ks|||kr€||kr€| S ||k r¬|}t|| | ƒ}| j	||f|ƒS |}t|| | ƒ}| j	||f|ƒS n| j	|ddd… |ƒS dS )a³  Resize the input PIL Image to the given size.

    Args:
        img (PIL Image): Image to be resized.
        size (sequence or int): Desired output size. If size is a sequence like
            (h, w), the output size will be matched to this. If size is an int,
            the smaller edge of the image will be matched to this number maintaing
            the aspect ratio. i.e, if height > width, then image will be rescaled to
            :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`
        interpolation (int, optional): Desired interpolation. Default is
            ``PIL.Image.BILINEAR``

    Returns:
        PIL Image: Resized image.
    zimg should be PIL Image. Got {}r   zGot inappropriate size arg: {}Nr   éÿÿÿÿ)
r   r   r    r!   r	   ÚintÚIterabler1   r3   Úresize)r
   r3   ÚinterpolationÚwÚhZowZohr   r   r   rI   Ý   s      

 rI   c              O   s   t jdƒ t| |ŽS )Nz9The use of the transforms.Scale transform is deprecated, z%please use transforms.Resize instead.z^The use of the transforms.Scale transform is deprecated, please use transforms.Resize instead.)ÚwarningsÚwarnrI   )ÚargsÚkwargsr   r   r   Úscale  s    rQ   Úconstantc       
      C   s(  t | ƒstdjt| ƒƒƒ‚t|tjtfƒs2tdƒ‚t|tjttfƒsLtdƒ‚t|tƒs^tdƒ‚t|t	ƒrŠt
|ƒdkrŠtddjt
|ƒƒ ƒ‚|dksštdƒ‚|d	krâ| jdkrÒ| jƒ }tj| ||d�}|j|ƒ |S tj| ||d�S t|tƒ� rþ| } } }}	t|t	ƒ�r0t
|ƒdk�r0|d  }}|d  }}	t|t	ƒ�rjt
|ƒdk�rj|d }|d }|d }|d }	| jdk�rº| jƒ }tj| ƒ} tj| ||	f||ff|ƒ} tj| ƒ} | j|ƒ | S tj| ƒ} t
| jƒdk�rðtj| ||	f||fdf|ƒ} t
| jƒdk�rtj| ||	f||ff|ƒ} tj| ƒS dS )a  Pad the given PIL Image on all sides with specified padding mode and fill value.

    Args:
        img (PIL Image): Image to be padded.
        padding (int or tuple): Padding on each border. If a single int is provided this
            is used to pad all borders. If tuple of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a tuple of length 4 is provided
            this is the padding for the left, top, right and bottom borders
            respectively.
        fill: 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
        padding_mode: 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 on the edge of the image

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

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

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

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

    Returns:
        PIL Image: Padded image.
    zimg should be PIL Image. Got {}zGot inappropriate padding argzGot inappropriate fill argz"Got inappropriate padding_mode argr   r8   z9Padding must be an int or a 2, or 4 element tuple, not a z{} element tuplerR   ÚedgeÚreflectÚ	symmetriczBPadding mode should be either constant, edge, reflect or symmetricÚP)ZborderÚfillr   r   r   N)r   r8   )rR   rS   rT   rU   )r   r   )r   r   r    r!   r	   ÚnumbersÚNumberÚtupleÚstrÚSequencer1   r"   ÚAssertionErrorr*   Z
getpaletter   ÚexpandZ
putpaletterG   r   ZasarrayÚpadr   r?   r>   )
r
   ÚpaddingrW   Zpadding_modeZpaletteÚimageZpad_leftZ	pad_rightZpad_topZ
pad_bottomr   r   r   r_     sV     







r_   c             C   s4   t | ƒstdjt| ƒƒƒ‚| j|||| || fƒS )an  Crop the given PIL Image.

    Args:
        img (PIL Image): Image to be cropped.
        i (int): i in (i,j) i.e coordinates of the upper left corner.
        j (int): j in (i,j) i.e coordinates of the upper left corner.
        h (int): Height of the cropped image.
        w (int): Width of the cropped image.

    Returns:
        PIL Image: Cropped image.
    zimg should be PIL Image. Got {})r   r   r    r!   Úcrop)r
   ÚiÚjrL   rK   r   r   r   rb   `  s    rb   c             C   sf   t |tjƒrt|ƒt|ƒf}| j\}}|\}}tt|| d ƒƒ}tt|| d ƒƒ}t| ||||ƒS )Ng       @)r	   rX   rY   rG   r3   Úroundrb   )r
   Úoutput_sizerK   rL   ÚthZtwrc   rd   r   r   r   Úcenter_crops  s    
rh   c             C   s0   t | ƒstdƒ‚t| ||||ƒ} t| ||ƒ} | S )a’  Crop the given PIL Image and resize it to desired size.

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

    Args:
        img (PIL Image): Image to be cropped.
        i (int): i in (i,j) i.e coordinates of the upper left corner
        j (int): j in (i,j) i.e coordinates of the upper left corner
        h (int): Height of the cropped image.
        w (int): Width of the cropped image.
        size (sequence or int): Desired output size. Same semantics as ``resize``.
        interpolation (int, optional): Desired interpolation. Default is
            ``PIL.Image.BILINEAR``.
    Returns:
        PIL Image: Cropped image.
    zimg should be PIL Image)r   r]   rb   rI   )r
   rc   rd   rL   rK   r3   rJ   r   r   r   Úresized_crop}  s    ri   c             C   s&   t | ƒstdjt| ƒƒƒ‚| jtjƒS )z¡Horizontally flip the given PIL Image.

    Args:
        img (PIL Image): Image to be flipped.

    Returns:
        PIL Image:  Horizontall flipped image.
    zimg should be PIL Image. Got {})r   r   r    r!   r#   r   ZFLIP_LEFT_RIGHT)r
   r   r   r   Úhflip”  s    	rj   c             C   sÜ   g }x’t || ƒD ]„\}}|j|d |d dddd|d  |d  |d  |d  gƒ |jddd|d |d d|d  |d  |d  |d  gƒ qW tj|tjd�}tj| tjd�jdƒ}tj||ƒd }|jdƒjƒ S )aA  Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.

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

    Args:
        List containing [top-left, top-right, bottom-right, bottom-left] of the orignal image,
        List containing [top-left, top-right, bottom-right, bottom-left] of the transformed
                   image
    Returns:
        octuple (a, b, c, d, e, f, g, h) for transforming each pixel.
    r   r   )r   é   )	ÚzipÚappendr   rC   r$   r2   ZlstsqZsqueeze_Útolist)ÚstartpointsÚ	endpointsÚmatrixÚp1Úp2ÚAÚBÚresr   r   r   Ú_get_perspective_coeffs£  s    >Brw   c             C   s8   t | ƒstdjt| ƒƒƒ‚t||ƒ}| j| jtj||ƒS )a¿  Perform perspective transform of the given PIL Image.

    Args:
        img (PIL Image): Image to be transformed.
        startpoints: List containing [top-left, top-right, bottom-right, bottom-left] of the orignal image
        endpoints: List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image
        interpolation: Default- Image.BICUBIC
    Returns:
        PIL Image:  Perspectively transformed Image.
    zimg should be PIL Image. Got {})	r   r   r    r!   rw   Ú	transformr3   r   ZPERSPECTIVE)r
   ro   rp   rJ   Zcoeffsr   r   r   Úperspective¼  s    
ry   c             C   s&   t | ƒstdjt| ƒƒƒ‚| jtjƒS )zžVertically flip the given PIL Image.

    Args:
        img (PIL Image): Image to be flipped.

    Returns:
        PIL Image:  Vertically flipped image.
    zimg should be PIL Image. Got {})r   r   r    r!   r#   r   ZFLIP_TOP_BOTTOM)r
   r   r   r   ÚvflipÎ  s    	rz   c             C   sÜ   t |tjƒrt|ƒt|ƒf}nt|ƒdks2tdƒ‚| j\}}|\}}||ksT||krhtdj|||fƒƒ‚| j	dd||fƒ}| j	|| d||fƒ}| j	d|| ||fƒ}| j	|| || ||fƒ}	t
| ||fƒ}
||||	|
fS )a8  Crop the given PIL Image into four corners and the central crop.

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

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

    Returns:
       tuple: tuple (tl, tr, bl, br, center)
                Corresponding top left, top right, bottom left, bottom right and center crop.
    r   z3Please provide only two dimensions (h, w) for size.z3Requested crop size {} is bigger than input size {}r   )r	   rX   rY   rG   r1   r]   r3   r"   r    rb   rh   )r
   r3   rK   rL   Zcrop_hZcrop_wÚtlÚtrÚblÚbrÚcenterr   r   r   Ú	five_cropÝ  s    
r€   c             C   sd   t |tjƒrt|ƒt|ƒf}nt|ƒdks2tdƒ‚t| |ƒ}|rJt| ƒ} nt| ƒ} t| |ƒ}|| S )a6  Crop the given PIL Image into four corners and the central crop plus the
        flipped version of these (horizontal flipping is used by default).

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

    Args:
       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.
       vertical_flip (bool): Use vertical flipping instead of horizontal

    Returns:
       tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip)
                Corresponding top left, top right, bottom left, bottom right and center crop
                and same for the flipped image.
    r   z3Please provide only two dimensions (h, w) for size.)	r	   rX   rY   rG   r1   r]   r€   rz   rj   )r
   r3   Zvertical_flipZ
first_fiveZsecond_fiver   r   r   Úten_cropÿ  s    


r�   c             C   s2   t | ƒstdjt| ƒƒƒ‚tj| ƒ}|j|ƒ} | S )a�  Adjust brightness of an Image.

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

    Returns:
        PIL Image: Brightness adjusted image.
    zimg should be PIL Image. Got {})r   r   r    r!   r   Z
BrightnessÚenhance)r
   Zbrightness_factorÚenhancerr   r   r   Úadjust_brightness"  s
    

r„   c             C   s2   t | ƒstdjt| ƒƒƒ‚tj| ƒ}|j|ƒ} | S )a{  Adjust contrast of an Image.

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

    Returns:
        PIL Image: Contrast adjusted image.
    zimg should be PIL Image. Got {})r   r   r    r!   r   ZContrastr‚   )r
   Zcontrast_factorrƒ   r   r   r   Úadjust_contrast6  s
    

r…   c             C   s2   t | ƒstdjt| ƒƒƒ‚tj| ƒ}|j|ƒ} | S )a|  Adjust color saturation of an image.

    Args:
        img (PIL Image): PIL Image to be adjusted.
        saturation_factor (float):  How much to adjust the saturation. 0 will
            give a black and white image, 1 will give the original image while
            2 will enhance the saturation by a factor of 2.

    Returns:
        PIL Image: Saturation adjusted image.
    zimg should be PIL Image. Got {})r   r   r    r!   r   ZColorr‚   )r
   Zsaturation_factorrƒ   r   r   r   Úadjust_saturationJ  s
    

r†   c             C   sÈ   d|  kodkn  s&t dj|ƒƒ‚t| ƒs@tdjt| ƒƒƒ‚| j}|dkrR| S | jdƒjƒ \}}}tj	|tj
d	�}tjd
d�� |tj
|d ƒ7 }W dQ R X tj|dƒ}tjd|||fƒj|ƒ} | S )a~  Adjust hue of an image.

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

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

    See `Hue`_ for more details.

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

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

    Returns:
        PIL Image: Hue adjusted image.
    g      à?z!hue_factor is not in [-0.5, 0.5].zimg should be PIL Image. Got {}r7   r   r   r   r:   )r   Úignore)Zoverr   Ng      à¿>   r7   r   r   r   )r"   r    r   r   r!   r*   ÚconvertÚsplitr   r+   r.   Zerrstater   r?   Úmerge)r
   Z
hue_factorÚ
input_moderL   ÚsÚvZnp_hr   r   r   Ú
adjust_hue^  s    rŽ   r   c                sn   t | ƒstdjt| ƒƒƒ‚ˆdk r*tdƒ‚| j}| jdƒ} ‡ ‡fdd„tdƒD ƒd }| j|ƒ} | j|ƒ} | S )	aÌ  Perform gamma correction on an image.

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

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

    See `Gamma Correction`_ for more details.

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

    Args:
        img (PIL Image): PIL Image to be adjusted.
        gamma (float): Non negative real number, same as :math:`\gamma` in the equation.
            gamma larger than 1 make the shadows darker,
            while gamma smaller than 1 make dark regions lighter.
        gain (float): The constant multiplier.
    zimg should be PIL Image. Got {}r   z*Gamma should be a non-negative real numberr9   c                s"   g | ]}d ˆ  t |d ˆƒ ‘qS )r   g     ào@)Úpow)Ú.0Zele)ÚgainÚgammar   r   ú
<listcomp>ª  s    z adjust_gamma.<locals>.<listcomp>é   r   )	r   r   r    r!   r"   r*   rˆ   ÚrangeZpoint)r
   r’   r‘   r‹   Z	gamma_mapr   )r‘   r’   r   Úadjust_gamma�  s    


r–   c             C   s*   t | ƒstdjt| ƒƒƒ‚| j||||ƒS )a  Rotate the image by angle.


    Args:
        img (PIL Image): PIL Image to be rotated.
        angle (float or int): In degrees degrees counter clockwise order.
        resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC``, optional):
            An optional resampling filter. See `filters`_ for more information.
            If omitted, or if the image has mode "1" or "P", it is set to ``PIL.Image.NEAREST``.
        expand (bool, optional): Optional expansion flag.
            If true, expands the output image to make it large enough to hold the entire rotated image.
            If false or omitted, make the output image the same size as the input image.
            Note that the expand flag assumes rotation around the center and no translation.
        center (2-tuple, optional): Optional center of rotation.
            Origin is the upper left corner.
            Default is the center of the image.

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

    zimg should be PIL Image. Got {})r   r   r    r!   Úrotate)r
   ÚangleÚresampler^   r   r   r   r   r—   ±  s    r—   c                sÀ  t j|ƒ}t|ttfƒr4t|ƒdkr4dd„ |D ƒ}n2t|tjƒrTt j|ƒ}|dg}ntddj	|ƒ ƒ‚dˆ ‰t j
||d  ƒt j
||d  ƒ t j||d  ƒt j||d  ƒ  ‰ t j
||d  ƒt j||d  ƒdt j||d  ƒ t j
||d  ƒdg}‡ ‡fd	d„|D ƒ}|d  |d | d  |d   |d | d  |d    7  < |d
  |d | d  |d   |d | d  |d    7  < |d  | d 7  < |d
  | d 7  < |S )Nr   c             S   s   g | ]}t j|ƒ‘qS r   )ÚmathÚradians)r�   rŒ   r   r   r   r“   Ü  s    z._get_inverse_affine_matrix.<locals>.<listcomp>r   z:Shear should be a single value or a tuple/list containing ztwo values. Got {}g      ð?r   c                s   g | ]}ˆˆ  | ‘qS r   r   )r�   Úm)ÚdrQ   r   r   r“   í  s    é   r   r8   )rš   r›   r	   rZ   Úlistr1   rX   rY   r"   r    ÚcosÚsin)r   r˜   Ú	translaterQ   Úshearrq   r   )r�   rQ   r   Ú_get_inverse_affine_matrixÍ  s(    


"&"(@@r¤   c             C   s´   t | ƒstdjt| ƒƒƒ‚t|ttfƒr4t|ƒdks<tdƒ‚|dksLtdƒ‚| j	}| j	d d d | j	d d d f}t
|||||ƒ}	td d	kršd
|ini }
| j|tj|	|f|
ŽS )a?  Apply affine transformation on the image keeping image center invariant

    Args:
        img (PIL Image): PIL Image to be rotated.
        angle (float or int): rotation angle in degrees between -180 and 180, clockwise direction.
        translate (list or tuple of integers): horizontal and vertical translations (post-rotation translation)
        scale (float): overall scale
        shear (float or tuple or list): shear angle value in degrees between -180 to 180, clockwise direction.
        If a tuple of list is specified, the first value corresponds to a shear parallel to the x axis, while
        the second value corresponds to a shear parallel to the y axis.
        resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC``, optional):
            An optional resampling filter.
            See `filters`_ for more information.
            If omitted, or if the image has mode "1" or "P", it is set to ``PIL.Image.NEAREST``.
        fillcolor (int): Optional fill color for the area outside the transform in the output image. (Pillow>=5.0.0)
    zimg should be PIL Image. Got {}r   z8Argument translate should be a list or tuple of length 2g        z!Argument scale should be positiver   g      à?r   Ú5Ú	fillcolor)r   r   r    r!   r	   rZ   rŸ   r1   r]   r3   r¤   r   rx   r   ZAFFINE)r
   r˜   r¢   rQ   r£   r™   r¦   rf   r   rq   rP   r   r   r   Úaffineù  s    $r§   c             C   sz   t | ƒstdjt| ƒƒƒ‚|dkr.| jdƒ} nH|dkrn| jdƒ} tj| tjd�}tj|||gƒ}t	j
|dƒ} ntdƒ‚| S )aY  Convert image to grayscale version of image.

    Args:
        img (PIL Image): Image to be converted to grayscale.

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

            if num_output_channels = 3 : returned image is 3 channel with r = g = b
    zimg should be PIL Image. Got {}r   r7   r   )r   r9   z+num_output_channels should be either 1 or 3)r   r   r    r!   rˆ   r   r+   r.   Zdstackr   r?   r"   )r
   Znum_output_channelsZnp_imgr   r   r   Úto_grayscale  s    
r¨   c             C   sP   t | tjƒstdjt| ƒƒƒ‚|s*| jƒ } || dd…||| …||| …f< | S )a   Erase the input Tensor Image with given value.

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

    Returns:
        Tensor Image: Erased image.
    z"img should be Tensor Image. Got {}N)r	   r   r;   r   r    r!   rB   )r
   rc   rd   rL   rK   r�   rD   r   r   r   Úerase5  s    "r©   )r   r   )N)F)r   rR   )F)r   )FFN)r   N)r   )F)4Ú
__future__r   r   Úsysrš   ZPILr   r   r   r   r   ÚImportErrorr=   r   rX   ÚcollectionsrM   Úversion_infor\   rH   Úabcr   r   r   r   r6   r@   rE   ZBILINEARrI   rQ   r_   rb   rh   ri   rj   rw   ZBICUBICry   rz   r€   r�   r„   r…   r†   rŽ   r–   r—   r¤   r§   r¨   r©   r   r   r   r   Ú<module>   s\   

>
W
%
X
"
#/
$
,
 
