o
    پi#                     @   s   d Z 	 ddlm  mZ ddlZdZdZejj	  					dd	d
Z
dd Zdd Zdd Zdd ZedfddZedfddZddedfddZG dd dZdS )z Tensorflow Preprocessing Adapter

Allows use of Tensorflow preprocessing pipeline in PyTorch Transform

Copyright of original Tensorflow code below.

Hacked together by / Copyright 2020 Ross Wightman
    N       皙?      ?gHzG?g?      ?d   c              
   C   s   t |d| |gD t j| }t jj||||||dd}|\}	}
}t |	\}}}t |
\}}}t ||||g}t jj| |dd}|W  d   S 1 sPw   Y  dS )a  Generates cropped_image using one of the bboxes randomly distorted.

    See `tf.image.sample_distorted_bounding_box` for more documentation.

    Args:
      image_bytes: `Tensor` of binary image data.
      bbox: `Tensor` of bounding boxes arranged `[1, num_boxes, coords]`
          where each coordinate is [0, 1) and the coordinates are arranged
          as `[ymin, xmin, ymax, xmax]`. If num_boxes is 0 then use the whole
          image.
      min_object_covered: An optional `float`. Defaults to `0.1`. The cropped
          area of the image must contain at least this fraction of any bounding
          box supplied.
      aspect_ratio_range: An optional list of `float`s. The cropped area of the
          image must have an aspect ratio = width / height within this range.
      area_range: An optional list of `float`s. The cropped area of the image
          must contain a fraction of the supplied image within in this range.
      max_attempts: An optional `int`. Number of attempts at generating a cropped
          region of the image of the specified constraints. After `max_attempts`
          failures, return the entire image.
      scope: Optional `str` for name scope.
    Returns:
      cropped image `Tensor`
    distorted_bounding_box_cropT)bounding_boxesmin_object_coveredaspect_ratio_range
area_rangemax_attemptsuse_image_if_no_bounding_boxes   channelsN)tf
name_scopeimageextract_jpeg_shapesample_distorted_bounding_boxunstackstackdecode_and_crop_jpeg)image_bytesbboxr   r   r   r   scopeshaper   
bbox_begin	bbox_size_offset_yoffset_xtarget_heighttarget_widthcrop_windowr    r(   N/home/ubuntu/.local/lib/python3.10/site-packages/timm/data/tf_preprocessing.pyr
   !   s$   
$r
   c                 C   s,   t | |}t |t j}t t ||S )z0At least `x` of `a` and `b` `Tensors` are equal.)r   equalcastint32greater_equal
reduce_sum)abxmatchr(   r(   r)   _at_least_x_are_equalU   s   r3   c              	      sv   t jg dt jg dd}t|dddddd	 t j}t|t  d
}t |fdd fdd  S )z!Make a random crop of image_size.)        r4   r   r   )   r5      )dtyper   r   )r   gUUUUUU?)g{Gz?r   
   N)r   r   r   r   r   r   c                      s
   t  S )N)_decode_and_center_cropr(   )r   
image_sizer(   r)   <lambda>l   s   
 z)_decode_and_random_crop.<locals>.<lambda>c                      s   t j ggd S Nr   )r   r   resizer(   )r   r:   resize_methodr(   r)   r;   m   s    )	r   constantfloat32r
   r   r   r3   r   cond)r   r:   r>   r   original_shapebadr(   )r   r   r:   r>   r)   _decode_and_random_crop\   s$   rD   c              	   C   s   t j| }|d }|d }t ||t  t t ||t j t j}|| d d }|| d d }t ||||g}	t jj	| |	dd}
t j
|
g||g|d }
|
S )z=Crops to center of image with padding then scales image_size.r   r5      r   r   )r   r   r   r+   CROP_PADDINGminimumr@   r,   r   r   r=   )r   r:   r>   r   image_heightimage_widthpadded_center_crop_sizeoffset_heightoffset_widthr'   r   r(   r(   r)   r9   r   s"   
r9   c                 C   s   t j| } | S )zRandom horizontal image flip.)r   r   random_flip_left_right)r   r(   r(   r)   _flip   s   rN   bicubicc                 C   sb   |dkr	t jjjnt jjj}t| ||}t|}t |||dg}t jj||r*t j	nt j
d}|S aA  Preprocesses the given image for evaluation.

    Args:
      image_bytes: `Tensor` representing an image binary of arbitrary size.
      use_bfloat16: `bool` for whether to use bfloat16.
      image_size: image size.
      interpolation: image interpolation method

    Returns:
      A preprocessed image `Tensor`.
    rO   r   )r7   )r   r   ResizeMethodBICUBICBILINEARrD   rN   reshapeconvert_image_dtypebfloat16r@   r   use_bfloat16r:   interpolationr>   r   r(   r(   r)   preprocess_for_train   s   rZ   c                 C   sZ   |dkr	t jjjnt jjj}t| ||}t |||dg}t jj||r&t jnt j	d}|S rP   )
r   r   rQ   rR   rS   r9   rT   rU   rV   r@   rW   r(   r(   r)   preprocess_for_eval   s   r[   Fc                 C   s    |r	t | |||S t| |||S )a  Preprocesses the given image.

    Args:
      image_bytes: `Tensor` representing an image binary of arbitrary size.
      is_training: `bool` for whether the preprocessing is for training.
      use_bfloat16: `bool` for whether to use bfloat16.
      image_size: image size.
      interpolation: image interpolation method

    Returns:
      A preprocessed image `Tensor` with value range of [0, 255].
    )rZ   r[   )r   is_trainingrX   r:   rY   r(   r(   r)   preprocess_image   s   r]   c                   @   s&   e Zd ZdddZdd Zdd	 Zd
S )TfPreprocessTransformFr   rO   c                 C   s>   || _ t|tr|d n|| _|| _d | _|  | _d | _d S r<   )	r\   
isinstancetuplesizerY   _image_bytes_build_tf_graphprocess_imagesess)selfr\   ra   rY   r(   r(   r)   __init__   s   

zTfPreprocessTransform.__init__c                 C   sZ   t d t jg t jd| _t| j| jd| j| j}W d    |S 1 s&w   Y  |S )Nz/cpu:0)r   r7   F)	r   deviceplaceholderstringrb   r]   r\   ra   rY   )rf   imgr(   r(   r)   rc      s   
z%TfPreprocessTransform._build_tf_graphc                 C   sl   | j d u r
t | _ | j j| j| j|id}| ddt	j
}|jdk r.t	j|dd}t	|d}|S )N)	feed_dictr      r   )axisrE   )re   r   Sessionrunrd   rb   roundclipastypenpuint8ndimexpand_dimsrollaxis)rf   r   rk   r(   r(   r)   __call__   s   


zTfPreprocessTransform.__call__N)Fr   rO   )__name__
__module____qualname__rg   rc   rz   r(   r(   r(   r)   r^      s    

r^   )r   r   r   r	   N)__doc__tensorflow.compat.v1compatv1r   numpyru   
IMAGE_SIZErF   disable_eager_executionr
   r3   rD   r9   rN   rZ   r[   r]   r^   r(   r(   r(   r)   <module>   s2    
4
