Team Ai
Apppublic

David310/Detect_AI-generated_Image

sourceHugging Faceupdated 2y agoView on Hugging Face
4likes
vision_transformer_utils.cpython-38.pyc245 linesDownload Raw Back to __pycache__
1U

2��^f/T�@sxddlZddlZddlZddlmZddlmZmZmZm	Z	m3Z4mZddlZ
ddlZddlmZmZmZmZddddd	d5gZe��d+eejeejfeeee	e6eefeeejd�dd��Ze��d,eejeejfeeejefe	edd�dd��Ze��d-ejeje	eee	eeeee7eeeffee8eeeffe	eee	eeejd�	dd��Ze��d.ejejee	eeeee9eeeffee10eeeffejd�dd��Ze��d/ejeje	ee11eefe	eee12eeeffeeejd�dd	��Z e��ejejd�dd13��Z!e��ejejd�d d!��Z"ejd"�d#d$�Z#ed%�d&d'�Z$edd(�d)d*�Z%dS)0�N)�FunctionType)�Any�BinaryIO�List�Optional�Tuple�Union)�Image�14ImageColor�	ImageDraw�	ImageFont�	make_grid�15save_image�draw_bounding_boxes�draw_segmentation_masks�draw_keypoints�
flow_to_image��F�)�tensor�nrow�padding�	normalize�value_range�16scale_each�	pad_value�returncs�tj��stj��stt�t�|�sTt|t�rBt	dd�|D��sTt17dt|�����d|��krrt
�d�|d}t|t�r�tj|dd�}|��dkr�|�d�}|��d	kr�|�d�d18kr�t�|||fd�}|�d�}|��dk�r|�d19�d20k�rt�|||fd21�}|dk�rv|��}|d
k	�r6t|t��s6td��dd���fdd�}|dk�rl|D]}	||	|��qXn22|||�t|tj��s�t�|�d�d23k�r�|�d�S|�d�}24t||25�}tt�t|26�|��}t|�d�|�t|�d	�|�}
}|�d27�}|�||
|||||f|�}d}t|�D]h}t|�D]X}||28k�rJ�q*|� d29||
||
|�� d|||||��!||�|d30}�q6�q*|S)a)31    Make a grid of images.32 33    Args:34        tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)35            or a list of images all of the same size.36        nrow (int, optional): Number of images displayed in each row of the grid.37            The final grid size is ``(B / nrow, nrow)``. Default: ``8``.38        padding (int, optional): amount of padding. Default: ``2``.39        normalize (bool, optional): If True, shift the image to the range (0, 1),40            by the min and max values specified by ``value_range``. Default: ``False``.41        value_range (tuple, optional): tuple (min, max) where min and max are numbers,42            then these numbers are used to normalize the image. By default, min and max43            are computed from the tensor.44        range (tuple. optional):45            .. warning::46                This parameter was deprecated in ``0.12`` and will be removed in ``0.14``. Please use ``value_range``47                instead.48        scale_each (bool, optional): If ``True``, scale each image in the batch of49            images separately rather than the (min, max) over all images. Default: ``False``.50        pad_value (float, optional): Value for the padded pixels. Default: ``0``.51 52    Returns:53        grid (Tensor): the tensor containing grid of images.54    css|]}t�|�VqdS)N)�torch�	is_tensor)�.0�t�r"�G/root/autodl-tmp/UniversalFakeDetect/models/vision_transformer_utils.py�	<genexpr>;szmake_grid.<locals>.<genexpr>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 numberscSs,|j||d�|�|��t||d��dS)N)�min�maxg�h㈵��>)�clamp_�sub_�div_r,)�img�low�highr"r"r#�norm_ipZszmake_grid.<locals>.norm_ipcs>|dk	r�||d|d�n�|t|���t|����dS)Nrr))�floatr+r,)r!r�r3r"r#�55norm_range^szmake_grid.<locals>.norm_range)"r�jit�is_scripting�56is_tracing�_log_api_usage_oncer
r�57isinstance�list�all�	TypeError�type�keys�warnings�warn�stackr'�	unsqueeze�size�cat�clone�tuple�AssertionError�Tensor�squeezer+�int�math�ceilr4�new_fullr%�narrow�copy_)rrrrrrr�kwargsr6r!�nmaps�xmaps�ymaps�height�width�num_channels�grid�k�y�xr"r5r#r
sr$&�5859606162��6364656667&68"6970��)r�fp�formatrcKsttj��stj��stt�t|f|�}|�d��d��	dd��71ddd��dtj��
�}t�|�}|j||d�dS)	a#72    Save a given Tensor into an image file.73 74    Args:75        tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,76            saves the tensor as a grid of images by calling ``make_grid``.77        fp (string or file object): A filename or a file object78        format(Optional):  If omitted, the format to use is determined from the filename extension.79            If a file object was used instead of a filename, this parameter should always be used.80        **kwargs: Other arguments are documented in ``make_grid``.81    ��g�?rr)r�cpu)r^N)rr7r8r9r:rr
�mul�add_r-�permute�to�uint8�numpyr	�	fromarray�save)rr]r^rRrY�ndarr�imr"r"r#r�s082r)�83)	�image�boxes�labels�colors�fillrW�font�	font_sizercCs\tj��stj��stt�t|tj�s<tdt	|�����nJ|j84tjkrZtd|j85����n,|�
�dkrptd��n|�d�dkr�td��|jd}|dkr�dg|}n&t|�|kr�td	|�d86t|��d���|dkr�t|�}n@t|t��rt|�|k�rtdt|��d
|�d���n87|g|}dd�|D�}|�d�dk�rFt�|d�}|�ddd�����}	t�|	�}88|�tj���}|�r�t�|89d�}n90t�|91�}|dk�r�t��ntj ||d�}
t!|||�D]v\}}}|�r�|d}|j"||||d�n|j"|||d�|dk	�r�|d}|j#|d||d|f|||
d��q�t�$t%�&|92���ddd�jtjd�S)a�93    Draws bounding boxes on given image.94    The values of the input image should be uint8 between 0 and 255.95    If fill is True, Resulting Tensor should be saved as PNG image.96 97    Args:98        image (Tensor): Tensor of shape (C x H x W) and dtype uint8.99        boxes (Tensor): Tensor of size (N, 4) containing bounding boxes in (xmin, ymin, xmax, ymax) format. Note that100            the boxes are absolute coordinates with respect to the image. In other words: `0 <= xmin < xmax < W` and101            `0 <= ymin < ymax < H`.102        labels (List[str]): List containing the labels of bounding boxes.103        colors (color or list of colors, optional): List containing the colors104            of the boxes or single color for all boxes. The color can be represented as105            PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.106            By default, random colors are generated for boxes.107        fill (bool): If `True` fills the bounding box with specified color.108        width (int): Width of bounding box.109        font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may110            also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,111            `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.112        font_size (int): The requested font size in points.113 114    Returns:115        img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted.116    zTensor expected, got zTensor uint8 expected, got r(�#Pass individual images, not batchesr>r)r(z+Only grayscale and RGB images are supportedNzNumber of boxes (z) and labels (z/) mismatch. Please specify labels for each box.zNumber of colors (z ) is less than number of boxes (z). cSs$g|]}t|t�rt�|�n|�qSr")r;�strr117�getrgb)r �colorr"r"r#�118<listcomp>�sz'draw_bounding_boxes.<locals>.<listcomp>r))r(r)r)r�RGBA)rqrE)�d)rW�outlinerp)rWrz)rprq��dtype)'rr7r8r9r:rr;rJr>r?r|re�119ValueErrorr'rE�shape�len�_generate_color_paletter<�tilercr`rfr	rgrd�int64�tolistr�Drawr�load_default�truetype�zip�	rectangle�text�120from_numpy�np�array)rlrmrnrorprWrqrr�	num_boxesri�img_to_draw�	img_boxes�draw�txt_font�bboxrv�label�121fill_color�marginr"r"r#r�sT&122123�124125126127 128*皙�����?)rl�masks�alpharorcCs>tj��stj��stt�t|tj�s<tdt	|�����nL|j129tjkrZtd|j130����n.|�
�dkrptd��n|��ddkr�td��|jdkr�|ddd�dd�f}|jdkr�td	��|j131tjkr�td132|j133����|jdd�|jdd�kr�td��|��d}|dk	�r8|t|�k�r8td
|�dt|��d���|dk�rJt|�}t|t��s\|g}t|dttf��sxtd��t|dt��r�t|d�dk�r�td��tj}g}|D]0}t|t��r�t�|�}|�tj||d���q�|����}t||�D]&\}	}|dd�df|dd�|	f<�q�|d|||}134|135�|�S)a_136    Draws segmentation masks on given RGB image.137    The values of the input image should be uint8 between 0 and 255.138 139    Args:140        image (Tensor): Tensor of shape (3, H, W) and dtype uint8.141        masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool.142        alpha (float): Float number between 0 and 1 denoting the transparency of the masks.143            0 means full transparency, 1 means no transparency.144        colors (color or list of colors, optional): List containing the colors145            of the masks or single color for all masks. The color can be represented as146            PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.147            By default, random colors are generated for each mask.148 149    Returns:150        img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top.151    � The image must be a tensor, got �#The image dtype must be uint8, got r(rsr�8Pass an RGB image. Other Image formats are not supportedrNz3masks 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 widthzThere are more masks (z) than colors (�)z5colors must be a tuple or a string, or a list thereofzFIt seems that you passed a tuple of colors instead of a list of colorsr{r))rr7r8r9r:rr;rJr>r?r|rer}r'rE�ndim�boolr~rr�r<rHrtr152ru�appendr�detachrGr�rd)rlr�r�ro�	num_masks�	out_dtype�colors_rvr��mask�outr"r"r#rsP153154155156"157 r()rl�	keypoints�connectivityro�radiusrWrcCs�tj��stj��stt�t|tj�s<tdt	|�����nL|j158tjkrZtd|j159����n.|�
�dkrptd��n|��ddkr�td��|jdkr�td��|�dd	d�����}t�|�}t�|�}|�tj���}	t|	�D]�\}160}t|�D]R\}}
|
d|}|
d|}|
d|}|
d|}|j||||g|d161dd�q�|r�|D]`}||dd}||dd}||dd}||dd}|j||f||ff|d��qHq�t�t�|���d	dd�jtjd
�S)a_162    Draws Keypoints on given RGB image.163    The values of the input image should be uint8 between 0 and 255.164 165    Args:166        image (Tensor): Tensor of shape (3, H, W) and dtype uint8.167        keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoints location for each of the N instances,168            in the format [x, y].169        connectivity (List[Tuple[int, int]]]): A List of tuple where,170            each tuple contains pair of keypoints to be connected.171        colors (str, Tuple): The color can be represented as172            PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.173        radius (int): Integer denoting radius of keypoint.174        width (int): Integer denoting width of line connecting keypoints.175 176    Returns:177        img (Tensor[C, H, W]): Image Tensor of dtype uint8 with keypoints drawn.178    r�r�r(rsrr�z0keypoints must be of shape (num_instances, K, 2)r)rN)rprzrW)rWr{) rr7r8r9r:rr;rJr>r?r|rer}r'rEr�rcr`rfr	rgrr�rdr�r��	enumerate�ellipse�liner�r�r�)rlr�r�ror�rWrir�r��img_kpts�kpt_id�kpt_inst�inst_id�kpt�x1�x2�y1�y2�179connection�180start_pt_x�181start_pt_y�end_pt_x�end_pt_yr"r"r#rLsD182183184185�)�flowrcCs�|jtjkrtd|j�d���|j}|jdkr6|d}|jdksN|jddkr^td|�d���tj|ddd	�����}t�	|j�j186}|||}t|�}t|�dkr�|d187}|S)aJ188    Converts a flow to an RGB image.189 190    Args:191        flow (Tensor): Flow of shape (N, 2, H, W) or (2, H, W) and dtype torch.float.192 193    Returns:194        img (Tensor): Image Tensor of dtype uint8 where each color corresponds195            to a given flow direction. Shape is (N, 3, H, W) or (3, H, W) depending on the input.196    z)Flow should be of dtype torch.float, got �.r(Nr*r)rz<Input flow should have shape (2, H, W) or (N, 2, H, W), got r&r)
r|rr4r}r~r��sum�sqrtr,�finfo�eps�_normalized_flow_to_imager)r��197orig_shape�max_norm�epsilon�normalized_flowr0r"r"r#r�s198)r�rc	Csl|j\}}}}|j}tj|d||ftj|d�}t��|�}|jd}tj|ddd���}	t�	|dd�ddd�dd�f|dd�ddd�dd�f�tj199}200|201dd|d}t�|��tj�}|d}
d|
|
|k<||}t
|jd�D]v}|dd�|f}||d}||
d}d||||}d|	d|}t�d	|�|dd�|dd�dd�f<q�|S)202z�203    Converts a batch of normalized flow to an RGB image.204 205    Args:206        normalized_flow (torch.Tensor): Normalized flow tensor of shape (N, 2, H, W)207    Returns:208       img (Tensor(N, 3, H, W)): Flow visualization image of dtype uint8.209    r()r|�devicerrr)r&Ng�o@r_)r~r�r�zerosre�_make_colorwheelrdr�r��atan2�pi�floor�longr%)r��N�_�H�Wr��210flow_image�211colorwheel�num_cols�norm�a�fk�k0�k1�f�c�tmp�col0�col1�colr"r"r#r��s(212F(r�)rc	Cs�d}d}d}d}d}d}||||||}t�|df�}d}d|d|�df<t�dt�d|�|�|d|�d	f<||}dt�dt�d|�|�||||�df<d||||�d	f<||}d||||�d	f<t�dt�d|�|�||||�d213f<||}dt�dt�|�|�||||�d	f<d||||�d214f<||}d||||�d215f<t�dt�d|�|�||||�df<||}dt�dt�|�|�||||�d216f<d||||�df<|S)a-217    Generates a color wheel for optical flow visualization as presented in:218    Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007)219    URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf.220 221    Returns:222        colorwheel (Tensor[55, 3]): Colorwheel Tensor.223    ��r*��
r(rr_r)r)rr�r��arange)	�RY�YG�GC�CB�BM�MR�ncolsr�r�r"r"r#r��s6224&.*,*,r���num_objectscs&t�dddg���fdd�t|�D�S)Ni���i�i��csg|]}t|�d��qS)r_)rH)r �i��paletter"r#rwsz+_generate_color_palette.<locals>.<listcomp>)rrr%r�r"r�r#r�	sr�)�objrcCsD|j�d�sdS|jj}t|t�r(|j}tj�|j�d|���dS)a�225    Logs API usage(module and name) within an organization.226    In a large ecosystem, it's often useful to track the PyTorch and227    TorchVision APIs usage. This API provides the similar functionality to the228    logging module in the Python stdlib. It can be used for debugging purpose229    to log which methods are used and by default it is inactive, unless the user230    manually subscribes a logger via the `SetAPIUsageLogger method <https://github.com/pytorch/pytorch/blob/eb3b9fe719b21fae13c7a7cf3253f970290a573e/c10/util/Logging.cpp#L114>`_.231    Please note it is triggered only once for the same API call within a process.232    It does not collect any data from open-source users since it is no-op by default.233    For more information, please refer to234    * PyTorch note: https://pytorch.org/docs/stable/notes/large_scale_deployments.html#api-usage-logging;235    * Logging policy: https://github.com/pytorch/vision/issues/5052;236 237    Args:238        obj (class instance or method): an object to extract info from.239    �torchvisionNr�)	�240__module__�241startswith�	__class__�__name__r;rr�_Cr:)r��namer"r"r#r:s242r:)rrFNFr)N)NNFr)Nrk)r�N)NNrr()&rM�pathlibrA�typesr�typingrrrrrrrfr�r�PILr	r243rr�__all__�no_gradrJrLr�r4r
rt�Pathrrrrrr�r�r�r:r"r"r"r#�<module>s� �244��m���2450�`�0�K��H!"/