o
    #jw                     @   sj  d dl Z d dlZd dlZd dlZd dlm  mZ ddl	m
Z
 g Zdd Zdd Zdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdJdd ZdKd"d#Zd$d% Zd&d' ZdLd)d*Z	(	+			dMd,d-Zd.d/ Z	dLd0d1Z dJd2d3Z!dJd4d5Z"dJd6d7Z#dNd8d9Z$dJd:d;Z%dOd=d>Z&dPd@dAZ'dBdC Z(dDdE Z)dFdG Z*dHdI Z+dS )Q    N   )Variablec                 C   sL   t | tjtfr| jdk s| jdks| dvr$tdt| | j|d S )Nr      )chwhwcz;not support [type={}, ndim={}, data_format={}] paddle image)	
isinstancepaddleZTensorr   ndimlowerRuntimeErrorformattypeimgdata_format r   k/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/vision/transforms/functional_tensor.py_assert_image_tensor   s   

r   c                 C   $   |   dkrdS |   dkrdS d S )Nr   r   r
   r   r   r   r   _get_image_h_axis*   
   r   c                 C   r   )Nr   r   r   r   r   r   r   r   _get_image_w_axis1   r   r   c                 C   r   )Nr   r   r   r   r   r   r   r   r   _get_image_c_axis8   r   r   c                 C   s$   t | dkrd S t | dkrdS d S )Nr   r   r   )lenr   r   r   r   _get_image_n_axis?   r   r   c                 C      t | dkS )Nr   r   r   r   r   r   _is_channel_lastF      r"   c                 C   r    )Nr   r!   r   r   r   r   _is_channel_firstJ   r#   r$   c                 C   s   t |r| jt | S d S N)r   shaper   r   r   r   _get_image_num_batchesN   s   r'   c                 C   s   | j t| S r%   )r&   r   r   r   r   r   _get_image_num_channelsT   s   r(   c                 C   s   | j t| | j t| fS r%   )r&   r   r   r   r   r   r   _get_image_sizeX   s   r)   c                 C   s   | j dd}| jdd}t||}t|}|| }|t||| }| jdd\}}}	t|||}
|| |
 }|| |
 }||	 |
 }||k|j||  }||k||k@ |j|| d  }||k||k@ |j|| d  }|| | d d }||	  }tj
|||gddS )zConvert a image Tensor from RGB to HSV. This implementation is based on Pillow (
    https://github.com/python-pillow/Pillow/blob/main/src/libImaging/Convert.c)
    r   axis       @g      @      @      ?)maxminr   equal	ones_likewhereunbindastypedtypetruncstack)r   maxcmincZis_equalZone_divisorZc_deltasrgbZc_delta_divisorrcgcbchrhgZhbhr   r   r   _rgb_to_hsv_   s"   
$$rE   c              
   C   s  | j dd\}}}|d }t|}|| }|tjd }t|d|  dd}t|d||   dd}t|d|d|    dd}t|jddtjd|j	d
d| j	}	tjtj||||||gddtj||||||gddtj||||||gddgd	d}
td
|	|
S )z'Convert a image Tensor from HSV to RGB.r   r*   r-      r.           r6   r      rJ   z...ijk, ...xijk -> ...xjk)r4   r   floorr5   int32clipr1   	unsqueezeZaranger6   reshaper8   Zeinsum)r   rD   r;   vfipqtmaskmatrixr   r   r   _hsv_to_rgb{   s,   

rY   c                 C   s4   t | rdnd}t || t|d|| jS )Nr.        o@r   )r   is_floating_pointZlerpfloatrN   r5   r6   )Zimg1Zimg2ratioZ	max_valuer   r   r   _blend_images   s
   r^   CHWc                 C   sZ   t | | tj|| jd}tj|| jd}t|r'|g d}|g d}| | | S )a  Normalizes a tensor image given mean and standard deviation.

    Args:
        img (paddle.Tensor): input data to be normalized.
        mean (list|tuple): Sequence of means for each channel.
        std (list|tuple): Sequence of standard deviations for each channel.
        data_format (str, optional): Data format of img, should be 'HWC' or
            'CHW'. Default: 'CHW'.

    Returns:
        Tensor: Normalized mage.

    placerI   )r   r   	to_tensorra   r$   rP   )r   meanZstdr   r   r   r   	normalize   s   
rd   rJ   c                 C   sz   t | | |dvrtdtjg d| jd| j}t|r$|d}t	|}| | j
|dd} | j}|||< | |S )a  Converts image to grayscale version of image.

    Args:
        img (paddel.Tensor): Image to be converted to grayscale.
        num_output_channels (int, optionl[1, 3]):
            if num_output_channels = 1 : returned image is single channel
            if num_output_channels = 3 : returned image is 3 channel
        data_format (str, optional): Data format of img, should be 'HWC' or
            'CHW'. Default: 'CHW'.

    Returns:
        paddle.Tensor: Grayscale version of the image.
    rJ   r   z+num_output_channels should be either 1 or 3)gŏ1w-!?gbX9?gv/?r`   rI   Tr+   Zkeepdim)r   
ValueErrorr   rb   ra   r5   r6   r$   rP   r   sumr&   expand)r   Znum_output_channelsr   Zrgb_weightsZ_c_index_shaper   r   r   to_grayscale   s   



rk   c                 C   s>  d}t jd||df| jd}t | d | |d | d |}t  rMt | d | |d | d |d}||d< ||d< t d| d| g}	n5t | d | |d | d |d}t j	|d|}t j	|d|}t 
tjd| d| gdd}	| d	|	 }
|d|| df|
}|d||d
fS )N      ?rJ   r   rH   r   .r   .rJ   float32r      rJ   rq   )r   onesr6   linspacein_dynamic_mode
unsqueeze_rb   rO   staticsetitemassignnparray	transposerP   bmm)thetawrD   owohd	base_gridx_gridy_gridtmpZscaled_thetaoutput_gridr   r   r   _affine_grid   s*   $$ r   c                 C   s  | j d dkr|j| j d |j d |j d |j d gd}|d ur?tj| j d d| j d | j d f| jd}tj| |fdd} tj| ||dd	d
} |d ur| d d dd d d d d f }| d d d dd d d d f } |d| j d ddg}t	|t
tfrt|nd}t rt|d|ddf| j| }nt||d}t| t|d|ddg }|dkrt|dk | j}| d|  ||  } | S | | d| |  } | S )Nr   rJ   rq   r   )r&   rH   r*   zerosF)modepadding_modeZalign_cornersr   ro   nearestrl   r.   )r&   ri   r   rr   r6   concatFZgrid_sampletiler   tuplelistr   rt   rb   rP   r5   Z	expand_asry   rz   r2   rx   cast)r   gridr   filldummyrW   Zlen_fillZfill_imgr   r   r   _grid_transform   sB   " 
  
r   r   c           	      C   s   t | j}|dkr| d} | dkr| n| d} tj|| jd}|d}| j}t	||d |d |d |d d	}t
|trHt|gd }t| |||d
}| dkrX|n|d}|dkrh|d}|S |}|S )a  Affine to the image by matrix.

    Args:
        img (paddle.Tensor): Image to be rotated.
        matrix (float or int): Affine matrix.
        interpolation (str, optional): Interpolation method. If omitted, or if the
            image has only one channel, it is set NEAREST . when use pil backend,
            support method are as following:
            - "nearest"
            - "bilinear"
            - "bicubic"
        fill (3-tuple or int): RGB pixel fill value for area outside the rotated image.
            If int, it is used for all channels respectively.
        data_format (str, optional): Data format of img, should be 'HWC' or
            'CHW'. Default: 'CHW'.

    Returns:
        paddle.Tensor: Affined image.

    r   r   r   r   r   rJ   rq   r`   rJ   rq   r   r   r   )r~   rD   r   r   r   r   r   rq   r   rJ   )r   r&   rO   r
   r{   r   rb   ra   rP   r   r   intr   r   squeeze)	r   rX   interpolationr   r   r	   r&   r   outr   r   r   affine&  s$   



r   Fc              
   C   s  | d }|  d} t| |d\}}| dkr| n| d} ddg}	|du r,ddg}
ndd t|||gD }
t rt|}t	|t
|d	t
| t	|d	g}tj|| jd
}|d  |d |
d  |	d   |d |
d  |	d    |
d  7  < |d  |d |
d  |	d   |d |
d  |	d    |
d  7  < nw|d tj }tt	|t
|tdgt
| t	|tdgg}tj|d|d |d |
d  |	d    |d |
d  |	d    |
d  }tj|d|d |d |
d  |	d    |d |
d  |	d    |
d  }|d}|rt rXtjd| d| dgd| d| dgd| d| dgd| d| dgg|jd
|j}n)td| d| dgd| d| dgd| d| dgd| d| dgg|j}|d|dd}|jdd }|jdd }|| }|d d }|d d }t rt|t|}}n|d|d}}n||}}t|||||}t| |||d}| dkr|n|d}|dS )a  Rotates the image by angle.

    Args:
        img (paddle.Tensor): Image to be rotated.
        angle (float or int): In degrees degrees counter clockwise order.
        interpolation (str, optional): Interpolation method. If omitted, or if the
            image has only one channel, it is set NEAREST . when use pil backend,
            support method are as following:
            - "nearest"
            - "bilinear"
            - "bicubic"
        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.
        fill (3-tuple or int): RGB pixel fill value for area outside the rotated image.
            If int, it is used for all channels respectively.

    Returns:
        paddle.Tensor: Rotated image.

    ih  r   r   r   r   Nc                 S   s   g | ]
\}}||d   qS )rl   r   ).0rT   r;   r   r   r   
<listcomp>  s    zrotate.<locals>.<listcomp>rG   r`   rq   rJ      r   r      r         r.   rl   )rJ   r   r   rp   )rJ   r   rq   r   r*   rM   r   r   )rO   r)   r
   r{   zipr   rt   mathradianscossinrb   ra   pir   r   rv   rw   rP   r5   r6   rx   r|   r0   rL   r/   ceilr   r   r   r   )r   Zangler   ri   centerr   r   r~   rD   Z
post_transZrotn_centerrX   Zcorners_pos_min_maxZnposnwZnhr   r   r   r   r   r   r   rotateT  s   
#








	





r   c                 C   s<  |d d  g d}tj|dd   ddgddgd}tjd|d}tj||fddd	}d
}	tjd||df|d}
t|	|d |	 d |}||
d< t|	|d |	 d |d}||
d< |dt	d
| d
| g }|
 d|| df
|}|
 d|| df
|d}|| d }| d||dfS )NrF   r   rJ   rq   )Zrepeat_times)rq   rJ   rH   r*   r   rl   r   r.   rm   r   rn   rp   )rP   r   r   rr   r   rO   rs   ru   r{   rb   r|   )r   coeffsr   r   r6   Ztheta1r   r   Ztheta2r   r   r   r   Zscaled_theta1Zoutput_grid1Zoutput_grid2r   r   r   r   _perspective_grid  s&   $ r   c                 C   s   t | j}|dkr| d} | dkr| n| d} | jd | jd }}t| r.| jntj}tj	|| j
d}t| ||||d}	t| |	||d	}
| dkrR|
n|
d
}
|dkrb|
d}
|
S |
}
|
S )a  Perspective the image.

    Args:
        img (paddle.Tensor): Image to be rotated.
        coeffs (list[float]): coefficients (a, b, c, d, e, f, g, h) of the perspective transforms.
        interpolation (str, optional): Interpolation method. If omitted, or if the
            image has only one channel, it is set NEAREST. When use pil backend,
            support method are as following:
            - "nearest"
            - "bilinear"
            - "bicubic"
        fill (3-tuple or int): RGB pixel fill value for area outside the rotated image.
            If int, it is used for all channels respectively.

    Returns:
        paddle.Tensor: Perspectived image.

    r   r   r   r   r   r   r`   )r   r   r6   r   r   )r   r&   rO   r
   r{   r   r[   r6   ro   rb   ra   r   r   r   )r   r   r   r   r   r	   r   r   r6   r   r   r   r   r   perspective  s   

r   c                 C       t | | t|}| j|gdS )a  Vertically flips the given paddle tensor.

    Args:
        img (paddle.Tensor): Image to be flipped.
        data_format (str, optional): Data format of img, should be 'HWC' or
            'CHW'. Default: 'CHW'.

    Returns:
        paddle.Tensor:  Vertically flipped image.

    r*   )r   r   flip)r   r   Zh_axisr   r   r   vflip0     
r   c                 C   r   )a$  Horizontally flips the given paddle.Tensor Image.

    Args:
        img (paddle.Tensor): Image to be flipped.
        data_format (str, optional): Data format of img, should be 'HWC' or
            'CHW'. Default: 'CHW'.

    Returns:
        paddle.Tensor:  Horizontall flipped image.

    r*   )r   r   r   )r   r   Zw_axisr   r   r   hflipC  r   r   c                 C   sV   t | | t|r| dd||| ||| f S | ||| ||| ddf S )a>  Crops the given paddle.Tensor Image.

    Args:
        img (paddle.Tensor): Image to be cropped. (0,0) denotes the top left
            corner of the image.
        top (int): Vertical component of the top left corner of the crop box.
        left (int): Horizontal component of the top left corner of the crop box.
        height (int): Height of the crop box.
        width (int): Width of the crop box.
        data_format (str, optional): Data format of img, should be 'HWC' or
            'CHW'. Default: 'CHW'.
    Returns:
        paddle.Tensor: Cropped image.

    N)r   r$   )r   topleftheightwidthr   r   r   r   cropV  s   
""r   c              	   C   sn   t | d |s|  } t r || d||| ||| f< | S tj| dt||| t||| f|} | S )aQ  Erase the pixels of selected area in input Tensor image with given value.

    Args:
         img (paddle.Tensor): input Tensor image.
         i (int): y coordinate of the top-left point of erased region.
         j (int): x coordinate of the top-left point of erased region.
         h (int): Height of the erased region.
         w (int): Width of the erased region.
         v (paddle.Tensor): value used to replace the pixels in erased region.
         inplace (bool, optional): Whether this transform is inplace. Default: False.

     Returns:
         paddle.Tensor: Erased image.

    r_   .)r   cloner   rt   rv   rw   slice)r   rS   jrD   r~   rQ   Zinplacer   r   r   erasen  s   
 r   c           	      C   sx   t | | t|tjrt|t|f}t| |\}}|\}}tt|| d }tt|| d }t| |||||dS )a  Crops the given paddle.Tensor Image and resize it to desired size.

    Args:
        img (paddle.Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
        output_size (sequence or int): (height, width) of the crop box. If int,
            it is used for both directions
        data_format (str, optional): Data format of img, should be 'HWC' or
            'CHW'. Default: 'CHW'.
    Returns:
        paddle.Tensor: Cropped image.

    r,   r   )r   r   numbersNumberr   r)   roundr   )	r   Zoutput_sizer   Zimage_widthZimage_heightZcrop_heightZ
crop_widthZcrop_topZ	crop_leftr   r   r   center_crop  s   
r   constantc           	      C   sN  t | | t|tjttfstdt|tjtttfs tdt|ts)tdt|ttfrAt|dvrAt	dt| d |dv sIJ dt|t
rW| } } }}n#t|d	krj|d
  }}|d  }}n|d
 }|d }|d	 }|d }||||g}|dkrd}n|dkrt	d| d
} tj| ||t|d| d} | d
S )a=  
    Pads the given paddle.Tensor on all sides with specified padding mode and fill value.

    Args:
        img (paddle.Tensor): Image to be padded.
        padding (int|list|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 (float, optional): Pixel fill value for constant fill. 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. Default: 0.
        padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default: '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:
        paddle.Tensor: Padded image.

    zGot inappropriate padding argzGot inappropriate fill argz"Got inappropriate padding_mode arg)rq   r   z9Padding must be an int or a 2, or 4 element tuple, not a z element tuple)r   edgeZreflect	symmetriczBPadding mode should be either constant, edge, reflect or symmetricrq   r   rJ   r   r   Z	replicater   zDo not support symmetric modeN)padr   valuer   )r   r   r   r   r   r   	TypeErrorstrr   rg   r   rO   r   r   r\   r   )	r   paddingr   r   r   pad_left	pad_rightpad_topZ
pad_bottomr   r   r   r     sN   
"




r   bilinearc                 C   s  t | | t|tst|ttfrt|dkstd| t|trht| |\}}|dks2|dkr<td| d| ||krD||ksL||krN||krN| S ||k r]|}t|| | }n|}t|| | }n|\}}| 	d} t
j| ||f| d|  d} | dS )aj  
    Resizes the image to given size

    Args:
        input (paddle.Tensor): Image to be resized.
        size (int|list|tuple): Target size of input data, with (height, width) shape.
        interpolation (int|str, optional): Interpolation method. when use paddle backend,
            support method are as following:
            - "nearest"
            - "bilinear"
            - "bicubic"
            - "trilinear"
            - "area"
            - "linear"
        data_format (str, optional): paddle.Tensor format
            - 'CHW'
            - 'HWC'
    Returns:
        paddle.Tensor: Resized image.

    rq   zGot inappropriate size arg: r   z/Not support while w<=0 or h<=0, but received w=z, h=r   )sizer   r   )r   r   r   r   r   r   r   r)   NotImplementedErrorrO   r   Zinterpolater
   upperr   )r   r   r   r   r~   rD   r   r   r   r   r   resize  s:   

 


r   c                 C   sJ   t | d |dksJ dt| ddv sJ dt| | j}t| ||S )a  Adjusts brightness of an Image.

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

    Returns:
        paddle.Tensor: Brightness adjusted image.

    r_   r   z)brightness_factor should be non-negative.re   *channels of input should be either 1 or 3.)r   r(   r   Z
zeros_liker6   r^   )r   Zbrightness_factorextreme_targetr   r   r   adjust_brightness>  s   
r   c                 C   s   t | d |dksJ dt| d}t| r| jntj}|dkr-tj| |ddd}n|d	kr?tjt| |ddd}nt	d
t
| ||S )a  Adjusts contrast of an image.

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

    Returns:
        paddle.Tensor: Contrast adjusted image.

    r   r   z'contrast_factor should be non-negative.r_   rJ   )r   r   r   Trf   r   r   )r   r(   r   r[   r6   ro   rc   r5   rk   rg   r^   )r   Zcontrast_factorchannelsr6   r   r   r   r   adjust_contrastV  s   

r   c                 C   sV   t | d |dksJ dt| d}|dkr| S |dkr!t| }ntdt| ||S )a  Adjusts color saturation of an image.

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

    Returns:
        paddle.Tensor: Saturation adjusted image.

    r_   r   z)saturation_factor should be non-negative.rJ   r   r   )r   r(   rk   rg   r^   )r   Zsaturation_factorr   r   r   r   r   adjust_saturationv  s   


r   c           	      C   s   t | d |dkr|dksJ dt| d}|dkr| S |dkra| j}|tjkr0| tjd } t| }|jdd	\}}}|| }||	  }t
tj|||gdd	}|tjkr_|d |}|S td
)a2  Adjusts 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]`.

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

    Returns:
        paddle.Tensor: Hue adjusted image.

    r_   r   rl   z)hue_factor should be in range [-0.5, 0.5]rJ   r   rZ   r   r*   r   )r   r(   r6   r   Zuint8r5   ro   rE   r4   rL   rY   r8   rg   )	r   Z
hue_factorr   r6   Zimg_hsvrD   r;   rQ   Zimg_adjustedr   r   r   
adjust_hue  s(   



r   )r_   )rJ   r_   )r   Nr_   )r   FNNr_   )F)r   r   r_   )r   r_   ),r   r   numpyry   r   Zpaddle.nn.functionalnnZ
functionalr   Zbase.frameworkr   __all__r   r   r   r   r   r"   r$   r'   r(   r)   rE   rY   r^   rd   rk   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s\   
	
#
-1
 

(




 
W< 