a
    OSicV                     @   st  d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZ d dlZd dlZd dlmZmZmZmZ g dZe d+eejeej f eeee	e
eef  eeejd
ddZe d,eejeej f eeejef e	e ddddZe d-ejeje	ee  e	eeeee
eeef f  ee
eeef f  e	e ee	e e	e ejd	ddZe d.ejejee	eeeee
eeef f  ee
eeef f  ejdddZe d/ejeje	ee
eef   e	eee
eeef f  eeejdddZ e ejejdddZ!e ejejdd d!Z"ejd"d#d$Z#ed%d&d'Z$edd(d)d*Z%dS )0    N)FunctionType)AnyBinaryIOListOptionalTupleUnion)Image
ImageColor	ImageDraw	ImageFont)	make_grid
save_imagedraw_bounding_boxesdraw_segmentation_masksdraw_keypointsflow_to_image      F        )tensornrowpadding	normalizevalue_range
scale_each	pad_valuereturnc                    s  t j st j stt t | sjt| trX| D ] }t |s4t	dt
| q4nt	dt
|  d| v rtd |d }t| trt j| dd} |  dkr| d} |  dkr| dd	krt | | | fd} | d} |  d
kr| d	d	krt | | | fd	} |du r|  } |durLt|tsLt	ddd   fdd}	|du r| D ]}|	|| qnn
|	| | t| t jst	d| dd	kr| dS | d}
t||
}ttt|
| }t| d| t| d|  }}| d	}| ||| | || | f|}d}t|D ]h}t|D ]X}||
krd qD|d	|| | || d|| | || | |  |d	 }qPqD|S )a)  
    Make a grid of images.

    Args:
        tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
            or a list of images all of the same size.
        nrow (int, optional): Number of images displayed in each row of the grid.
            The final grid size is ``(B / nrow, nrow)``. Default: ``8``.
        padding (int, optional): amount of padding. Default: ``2``.
        normalize (bool, optional): If True, shift the image to the range (0, 1),
            by the min and max values specified by ``value_range``. Default: ``False``.
        value_range (tuple, optional): tuple (min, max) where min and max are numbers,
            then these numbers are used to normalize the image. By default, min and max
            are computed from the tensor.
        range (tuple. optional):
            .. warning::
                This parameter was deprecated in ``0.12`` and will be removed in ``0.14``. Please use ``value_range``
                instead.
        scale_each (bool, optional): If ``True``, scale each image in the batch of
            images separately rather than the (min, max) over all images. Default: ``False``.
        pad_value (float, optional): Value for the padded pixels. Default: ``0``.

    Returns:
        grid (Tensor): the tensor containing grid of images.
    z:tensor or list of tensors expected, got a list containing z(tensor or list of tensors expected, got rangezmThe parameter 'range' is deprecated since 0.12 and will be removed in 0.14. Please use 'value_range' instead.r   dimr            TNzNvalue_range has to be a tuple (min, max) if specified. min and max are numbersc                 S   s,   | j ||d | |t|| d d S )N)minmaxgh㈵>)clamp_sub_div_r%   )imglowhigh r,   M/var/www/html/django/DPS/env/lib/python3.9/site-packages/torchvision/utils.pynorm_ip]   s    zmake_grid.<locals>.norm_ipc                    s>   |d ur | |d |d  n | t |  t |   d S )Nr   r"   )floatr$   r%   )tr   r.   r,   r-   
norm_rangea   s    zmake_grid.<locals>.norm_rangez%tensor should be of type torch.Tensor) torchjitis_scripting
is_tracing_log_api_usage_oncer   	is_tensor
isinstancelist	TypeErrortypekeyswarningswarnstackr    	unsqueezesizecatclonetupleTensorsqueezer$   intmathceilr/   new_fullr   narrowcopy_)r   r   r   r   r   r   r   kwargsr0   r2   ZnmapsZxmapsZymapsheightwidthnum_channelsgridkyxr,   r1   r-   r      sn    $











&
"
r   )r   fpformatr   c                 K   sx   t j st j stt t| fi |}|dd	dd
ddddt j }t|}|j||d dS )	a#  
    Save a given Tensor into an image file.

    Args:
        tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,
            saves the tensor as a grid of images by calling ``make_grid``.
        fp (string or file object): A filename or a file object
        format(Optional):  If omitted, the format to use is determined from the filename extension.
            If a file object was used instead of a filename, this parameter should always be used.
        **kwargs: Other arguments are documented in ``make_grid``.
       g      ?r   r"   r   cpu)rW   N)r3   r4   r5   r6   r7   r   r   muladd_r&   permutetouint8numpyr	   	fromarraysave)r   rV   rW   rN   rR   ndarrimr,   r,   r-   r      s    0
r   r"   )	imageboxeslabelscolorsfillrP   font	font_sizer   c                 C   s  t j st j stt t| t js<tdt	|  nJ| j
t jkrZtd| j
 n,|  dkrptdn| ddvrtd|jd }|dkrtd | S |d	u rd	g| }n&t||krtd
| dt| d|d	u rt|}n@t|tr(t||k r2tdt| d| dn
|g| }dd |D }|d	u rh|d	ur^td t }	ntj||pvdd}	| ddkrt | d} | ddd  }
t|
}|t j  }|rt!"|d}n
t!"|}t#|||D ]v\}}}|r|d }|j$||||d n|j$|||d |d	ur|d }|j%|d | |d | f|||	d qt &t'(|dddjt jdS )a  
    Draws bounding boxes on given image.
    The values of the input image should be uint8 between 0 and 255.
    If fill is True, Resulting Tensor should be saved as PNG image.

    Args:
        image (Tensor): Tensor of shape (C x H x W) and dtype uint8.
        boxes (Tensor): Tensor of size (N, 4) containing bounding boxes in (xmin, ymin, xmax, ymax) format. Note that
            the boxes are absolute coordinates with respect to the image. In other words: `0 <= xmin < xmax < W` and
            `0 <= ymin < ymax < H`.
        labels (List[str]): List containing the labels of bounding boxes.
        colors (color or list of colors, optional): List containing the colors
            of the boxes or single color for all boxes. The color can be represented as
            PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
            By default, random colors are generated for boxes.
        fill (bool): If `True` fills the bounding box with specified color.
        width (int): Width of bounding box.
        font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may
            also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,
            `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.
        font_size (int): The requested font size in points.

    Returns:
        img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted.
    zTensor expected, got zTensor uint8 expected, got r!   #Pass individual images, not batchesr   >   r"   r!   z+Only grayscale and RGB images are supportedz/boxes doesn't contain any box. No box was drawnNzNumber of boxes (z) and labels (z/) mismatch. Please specify labels for each box.zNumber of colors (z ) is less than number of boxes (z). c                 S   s$   g | ]}t |trt|n|qS r,   )r9   strr
   getrgb).0colorr,   r,   r-   
<listcomp>       z'draw_bounding_boxes.<locals>.<listcomp>z=Argument 'font_size' will be ignored since 'font' is not set.
   )ri   rB   r"   )r!   r"   r"   r   RGBA)d   )rP   outlinerh   )rP   ru   )rh   ri   dtype))r3   r4   r5   r6   r7   r   r9   rF   r;   r<   rw   r^   
ValueErrorr    rB   shaper>   r?   len_generate_color_paletter:   r   Zload_defaulttruetypetiler\   rY   r_   r	   r`   r]   int64tolistr   Drawzip	rectangletext
from_numpynparray)rd   re   rf   rg   rh   rP   ri   rj   	num_boxesZtxt_fontrb   img_to_drawZ	img_boxesdrawbboxro   labelZ
fill_colormarginr,   r,   r-   r      sb    &











*r   皙?)rd   masksalpharg   r   c                 C   sV  t j st j stt t| t js<tdt	|  nL| j
t jkrZtd| j
 n.|  dkrptdn|  d dkrtd|jdkr|dddddf }|jdkrtd	|j
t jkrtd
|j
 |jdd | jdd krtd| d }|dur8|t|kr8td| dt| d|dkrPtd | S |du rbt|}t|tst|g}t|d ttfstdt|d trt|d dkrtdt j}g }|D ]0}t|trt|}|t j||d q|   }t||D ]&\}	}|dddf |dd|	f< q| d|  ||  }
|
 |S )a_  
    Draws segmentation masks on given RGB image.
    The values of the input image should be uint8 between 0 and 255.

    Args:
        image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
        masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool.
        alpha (float): Float number between 0 and 1 denoting the transparency of the masks.
            0 means full transparency, 1 means no transparency.
        colors (color or list of colors, optional): List containing the colors
            of the masks or single color for all masks. The color can be represented as
            PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
            By default, random colors are generated for each mask.

    Returns:
        img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top.
     The image must be a tensor, got #The image dtype must be uint8, got r!   rk   r   8Pass an RGB image. Other Image formats are not supportedr   Nz3masks must be of shape (H, W) or (batch_size, H, W)z%The masks must be of dtype bool. Got z;The image and the masks must have the same height and widthzThere are more masks (z) than colors ()z1masks doesn't contain any mask. No mask was drawnz5colors must be a tuple or a string, or a list thereofzFIt seems that you passed a tuple of colors instead of a list of colorsrv   r"   )!r3   r4   r5   r6   r7   r   r9   rF   r;   r<   rw   r^   rx   r    rB   ndimboolry   rz   r>   r?   r{   r:   rE   rl   r
   rm   appendr   detachrD   r   r]   )rd   r   r   rg   Z	num_masks	out_dtypeZcolors_ro   r   maskoutr,   r,   r-   r     sV    





"
 r   r!   )rd   	keypointsconnectivityrg   radiusrP   r   c                 C   s  t j st j stt t| t js<tdt	|  nL| j
t jkrZtd| j
 n.|  dkrptdn|  d dkrtd|jdkrtd| dd	d  }t|}t|}|t j }	t|	D ]\}
}t|D ]R\}}|d | }|d | }|d | }|d | }|j||||g|d
dd q|r|D ]`}||d  d }||d  d }||d  d }||d  d }|j||f||ff|d qHqt t|d	ddjt jdS )a_  
    Draws Keypoints on given RGB image.
    The values of the input image should be uint8 between 0 and 255.

    Args:
        image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
        keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoints location for each of the N instances,
            in the format [x, y].
        connectivity (List[Tuple[int, int]]]): A List of tuple where,
            each tuple contains pair of keypoints to be connected.
        colors (str, Tuple): The color can be represented as
            PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
        radius (int): Integer denoting radius of keypoint.
        width (int): Integer denoting width of line connecting keypoints.

    Returns:
        img (Tensor[C, H, W]): Image Tensor of dtype uint8 with keypoints drawn.
    r   r   r!   rk   r   r   z0keypoints must be of shape (num_instances, K, 2)r"   r   N)rh   ru   rP   )rP   rv   ) r3   r4   r5   r6   r7   r   r9   rF   r;   r<   rw   r^   rx   r    rB   r   r\   rY   r_   r	   r`   r   r   r]   r~   r   	enumerateellipseliner   r   r   )rd   r   r   rg   r   rP   rb   r   r   Zimg_kptsZkpt_idZkpt_instZinst_idZkptx1x2y1y2
connectionZ
start_pt_xZ
start_pt_yZend_pt_xZend_pt_yr,   r,   r-   r   ]  sD    



r   )flowr   c                 C   s   | j tjkrtd| j  d| j}| jdkr6| d } | jdksN| jd dkr^td| dtj| d dd	  }t	| j j
}| ||  }t|}t|dkr|d
 }|S )aJ  
    Converts a flow to an RGB image.

    Args:
        flow (Tensor): Flow of shape (N, 2, H, W) or (2, H, W) and dtype torch.float.

    Returns:
        img (Tensor): Image Tensor of dtype uint8 where each color corresponds
            to a given flow direction. Shape is (N, 3, H, W) or (3, H, W) depending on the input.
    z)Flow should be of dtype torch.float, got .r!   Nr#   r"   r   z<Input flow should have shape (2, H, W) or (N, 2, H, W), got r   r   )rw   r3   r/   rx   ry   r   sumsqrtr%   finfoeps_normalized_flow_to_imagerz   )r   
orig_shapemax_normepsilonnormalized_flowr)   r,   r,   r-   r     s    
r   )r   r   c              	   C   sl  | j \}}}}| j}tj|d||ftj|d}t |}|j d }tj| d dd }	t	| dddddddf  | dddddddf  tj
 }
|
d d |d  }t|tj}|d }d|||k< || }t|j d D ]v}|dd|f }|| d }|| d }d| | ||  }d|	d|   }td	| |dd|ddddf< q|S )
z
    Converts a batch of normalized flow to an RGB image.

    Args:
        normalized_flow (torch.Tensor): Normalized flow tensor of shape (N, 2, H, W)
    Returns:
       img (Tensor(N, 3, H, W)): Flow visualization image of dtype uint8.
    r!   )rw   devicer   r   r"   r   Ng     o@rX   )ry   r   r3   zerosr^   _make_colorwheelr]   r   r   atan2pifloorlongr   )r   N_HWr   Z
flow_image
colorwheelnum_colsnormafkZk0k1fctmpcol0col1colr,   r,   r-   r     s(    
F(r   )r   c            	      C   s  d} d}d}d}d}d}| | | | | | }t |df}d}d|d| df< t dt d|  |  |d| d	f< ||  }dt dt d| |  |||| df< d|||| d	f< || }d|||| d	f< t dt d| | |||| d
f< || }dt dt | |  |||| d	f< d|||| d
f< || }d|||| d
f< t dt d| | |||| df< || }dt dt | |  |||| d
f< d|||| df< |S )a-  
    Generates a color wheel for optical flow visualization as presented in:
    Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007)
    URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf.

    Returns:
        colorwheel (Tensor[55, 3]): Colorwheel Tensor.
          r#         r!   r   rX   r"   r   )r3   r   r   arange)	ZRYZYGZGCZCBBMZMRncolsr   r   r,   r,   r-   r     s6    
&.*,*,r   num_objectsc                    s$   t g d  fddt| D S )N)ii  i c                    s   g | ]}t |  d  qS )rX   )rE   )rn   ipaletter,   r-   rp     rq   z+_generate_color_palette.<locals>.<listcomp>)r3   r   r   r   r,   r   r-   r{     s    r{   )objr   c                 C   sD   | j dsdS | jj}t| tr(| j}tj| j  d|  dS )a  
    Logs API usage(module and name) within an organization.
    In a large ecosystem, it's often useful to track the PyTorch and
    TorchVision APIs usage. This API provides the similar functionality to the
    logging module in the Python stdlib. It can be used for debugging purpose
    to log which methods are used and by default it is inactive, unless the user
    manually subscribes a logger via the `SetAPIUsageLogger method <https://github.com/pytorch/pytorch/blob/eb3b9fe719b21fae13c7a7cf3253f970290a573e/c10/util/Logging.cpp#L114>`_.
    Please note it is triggered only once for the same API call within a process.
    It does not collect any data from open-source users since it is no-op by default.
    For more information, please refer to
    * PyTorch note: https://pytorch.org/docs/stable/notes/large_scale_deployments.html#api-usage-logging;
    * Logging policy: https://github.com/pytorch/vision/issues/5052;

    Args:
        obj (class instance or method): an object to extract info from.
    torchvisionNr   )	
__module__
startswith	__class____name__r9   r   r3   _Cr7   )r   namer,   r,   r-   r7     s    
r7   )r   r   FNFr   )N)NNFr"   NN)r   N)NNr   r!   )&rI   pathlibr>   typesr   typingr   r   r   r   r   r   r_   r   r3   PILr	   r
   r   r   __all__no_gradrF   rH   r   r/   r   rl   Pathr   r   r   r   r   r   r   r{   r7   r,   r,   r,   r-   <module>   s    
      q       
0i  0O    H!"/