CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
image_utils.cpython-310.pyc392 linesDownload Raw Back to __pycache__
1o

2.�Yi���@s>ddlZddlZddlmZddlmZddlmZddlm	Z	m3Z4ddlZddl
Z
ddlmZmZmZmZmZmZmZmZmZmZmZddlmZmZmZmZmZm Z e�r�ddl!Z"ddl#Z"e"j$j%Z&e�r�dd	l'm(Z(e&j)e(j*e&j+e(j+e&j,e(j,e&j-e(j-e&j.e(j.e&j/e(j/iZ0niZ0e�r�ddl1Z1e�2e3�Z4e5d6ej5de6d7e6ej5e6dfZ7Gdd
�d
e�Z8Gdd�de�Z9Gdd�de�Z:e;e<e8e=e<e6e;ffZ>dd�Z?Gdd�de�Z@dd�ZAdd�ZBde6fdd�ZCdd�ZDdd �ZEd!d"�ZFd#ej5d$eGfd%d&�ZHdnd(e=d$e6e7fd)d*�ZI	'dnde9e6e7e7fd(e=d$e7fd+d,�ZJ	'dnde10e6e7e7fd(e=d$e6e7fd-d.�ZKd$ej5fd/d0�ZL	dod#ej5d1e	e11e=eMe=d2ffd$e8fd3d4�ZN	dod#ej5d5e	e12e8e<fd$e=fd6d7�ZOdod#ej5d8e	e8d$eMe=e=ffd9d:�ZPd;eMe=e=fd<e=d=e=d$eMe=e=ffd>d?�ZQd@e;e<e13e6eMffd$eGfdAdB�ZRd@e;e<e14e6eMffd$eGfdCdD�ZSdEee;e<e15e6eMffd$eGfdFdG�ZTdEee;e<e16e6eMffd$eGfdHdI�ZUdod#e17e<d18fdJe	eVd$d19fdKdL�ZW	dode20e6eMe<d21fdJe	eVd$e22d23e6d24e6e6d25ffdMdN�ZX													dpdOe	eGdPe	eVdQe	eGdRe	e26eVe6eVfdSe	e27eVe6eVfdTe	eGdUe	e28e;e<e=fe=fdVe	eGdWe	e;e<e=fdXe	eGdYe	e;e<e=fdZe	d[d\e	d]fd^d_�ZYGd`da�da�ZZdbe9dceMe9d2fdEe6e;d$dfddde�Z[dfe6e<dge6e<fdhdi�Z\edjdk�Gdldm�dm��Z]dS)q�N)�Iterable)�	dataclass)�BytesIO)�Optional�Union�)�ExplicitEnum�
is_jax_tensor�is_numpy_array�is_tf_tensor�is_torch_available�is_torch_tensor�is_torchvision_available�is_vision_available�logging�requires_backends�to_numpy)�IMAGENET_DEFAULT_MEAN�IMAGENET_DEFAULT_STD�IMAGENET_STANDARD_MEAN�IMAGENET_STANDARD_STD�OPENAI_CLIP_MEAN�OPENAI_CLIP_STD)�InterpolationModezPIL.Image.Imageztorch.Tensorc@�eZdZdZdZdS)�ChannelDimensionZchannels_firstZ
channels_lastN)�__name__�29__module__�__qualname__�FIRST�LAST�r!r!��E:\DocsHouse\542 percep lab latest\PerceptionLab\PerceptionLab_Portable\python_embed\Lib\site-packages\transformers/image_utils.pyrQ�rc@r)�AnnotationFormatZcoco_detectionZ
coco_panopticN)rrr�COCO_DETECTION�
COCO_PANOPTICr!r!r!r"r$Vr#r$c@seZdZejjZejjZdS)�AnnotionFormatN)rrrr$r%�valuer&r!r!r!r"r'[sr'cCst�o	t|tjj�S�N)r�30isinstance�PIL�Image��imgr!r!r"�is_pil_imagecsr/c@s eZdZdZdZdZdZdZdS)�	ImageTypeZpillow�torch�numpyZ31tensorflowZjaxN)rrrr+�TORCH�NUMPY�32TENSORFLOW�JAXr!r!r!r"r0gsr0cCsXt|�rtjSt|�rtjSt|�rtjSt|�rtjSt	|�r#tj33Stdt|�����)NzUnrecognized image type )
r/r0r+r
r3r34r4rr5r	r6�35ValueError�type��imager!r!r"�get_image_typeosr;cCs(t|�pt|�pt|�pt|�pt|�Sr))r/r36r
rr	r-r!r!r"�is_valid_image}s(r<�imagescCs|o37tdd�|D��S)Ncs��|]}t|�VqdSr))r<��.0r:r!r!r"�	<genexpr>���z*is_valid_list_of_images.<locals>.<genexpr>��all)r=r!r!r"�is_valid_list_of_images�srEcCs\t|dt�rdd�|D�St|dtj�rtj|dd�St|dtj�r,tj|dd�SdS)NrcS�g|]	}|D]}|�qqSr!r!)r@Zsublist�itemr!r!r"�38<listcomp>��z$concatenate_list.<locals>.<listcomp>�Zaxis)�dim)r*�list�np�ndarrayZconcatenater1�Tensor�cat)Z39input_listr!r!r"�concatenate_list�s�rQcCs:t|ttf�r|D]	}t|�sdSq	dSt|�sdSdS)NFT)r*rL�tuple�valid_imagesr<)Zimgsr.r!r!r"rS�s��rScCst|ttf�r
t|d�SdS)NrF)r*rLrRr<r-r!r!r"�40is_batched�srTr:�returncCs,|jtjkrdSt�|�dkot�|�dkS)zV41    Checks to see whether the pixel values have already been rescaled to [0, 1].42    Frr)�dtyperM�uint8�min�maxr9r!r!r"�is_scaled_image�srZ��expected_ndimscCs�t|�r|St|�r
|gSt|�r9|j|dkrt|�}|S|j|kr(|g}|Std|d�d|�d|j�d���tdt|��d���)a43    Ensure that the output is a list of images. If the input is a single image, it is converted to a list of length 1.44    If the input is a batch of images, it is converted to a list of images.45 46    Args:47        images (`ImageInput`):48            Image of images to turn into a list of images.49        expected_ndims (`int`, *optional*, defaults to 3):50            Expected number of dimensions for a single input image. If the input image has a different number of51            dimensions, an error is raised.52    rz%Invalid image shape. Expected either z or z dimensions, but got z dimensions.ztInvalid image type. Expected either PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray, but got �.)rTr/r<�ndimrLr7r8�r=r\r!r!r"�make_list_of_images�s*	53������r`cCs�t|ttf�r tdd�|D��r tdd�|D��r dd�|D�St|ttf�rJt|�rJt|d�s8|dj|kr:|S|dj|dkrJdd�|D�St|�ret|�sW|j|krZ|gS|j|dkret|�Std	|����)54a�55    Ensure that the output is a flat list of images. If the input is a single image, it is converted to a list of length 1.56    If the input is a nested list of images, it is converted to a flat list of images.57    Args:58        images (`Union[list[ImageInput], ImageInput]`):59            The input image.60        expected_ndims (`int`, *optional*, defaults to 3):61            The expected number of dimensions for a single input image.62    Returns:63        list: A list of images or a 4d array of images.64    cs��|]65}t|ttf�VqdSr)�r*rLrR�r@Zimages_ir!r!r"rA���z+make_flat_list_of_images.<locals>.<genexpr>cs��|]66}t|�p67|VqdSr)�rErcr!r!r"rA�rdcSrFr!r!�r@Zimg_listr.r!r!r"rH�rIz,make_flat_list_of_images.<locals>.<listcomp>rrcSrFr!r!rgr!r!r"rH�rIz*Could not make a flat list of images from �	r*rLrRrDrEr/r^r<r7r_r!r!r"�make_flat_list_of_images�s$���ricCs�t|ttf�rtdd�|D��rtdd�|D��r|St|ttf�rFt|�rFt|d�s3|dj|kr6|gS|dj|dkrFdd�|D�St|�rct|�sS|j|krW|ggS|j|dkrct|�gStd��)	as68    Ensure that the output is a nested list of images.69    Args:70        images (`Union[list[ImageInput], ImageInput]`):71            The input image.72        expected_ndims (`int`, *optional*, defaults to 3):73            The expected number of dimensions for a single input image.74    Returns:75        list: A list of list of images or a list of 4d array of images.76    csrar)rbrcr!r!r"rA	rdz-make_nested_list_of_images.<locals>.<genexpr>csrer)rfrcr!r!r"rA77rdrrcSsg|]}t|��qSr!)rLr?r!r!r"rHsz.make_nested_list_of_images.<locals>.<listcomp>z]Invalid input type. Must be a single image, a list of images, or a list of batches of images.rhr_r!r!r"�make_nested_list_of_images�s$���78rjcCs@t|�s
tdt|�����t�rt|tjj�rt�|�St	|�S)NzInvalid image type: )79r<r7r8rr*r+r,rM�arrayrr-r!r!r"�to_numpy_arrays8081rl�num_channels.cCs�|dur|nd}t|t�r|fn|}|jdkrd\}}n|jdkr&d\}}n|jdkr0d\}}ntd|j����|j||vrS|j||vrSt�d	|j�d82��tjS|j||vr]tjS|j||vrgtj	Std��)a[83    Infers the channel dimension format of `image`.84 85    Args:86        image (`np.ndarray`):87            The image to infer the channel dimension of.88        num_channels (`int` or `tuple[int, ...]`, *optional*, defaults to `(1, 3)`):89            The number of channels of the image.90 91    Returns:92        The channel dimension of the image.93    N�rr[r[)r���)rorpz(Unsupported number of image dimensions: z4The channel dimension is ambiguous. Got image shape z�. Assuming channels are the first dimension. Use the [input_data_format](https://huggingface.co/docs/transformers/main/internal/image_processing_utils#transformers.image_transforms.rescale.input_data_format) parameter to assign the channel dimension.z(Unable to infer channel dimension format)94r*�intr^r7�shape�logger�warningrrr )r:rmZ	first_dimZlast_dimr!r!r"�infer_channel_dimension_format(s&9596979899100�rv�input_data_formatcCsF|durt|�}|tjkr|jdS|tjkr|jdStd|����)a�101    Returns the channel dimension axis of the image.102 103    Args:104        image (`np.ndarray`):105            The image to get the channel dimension axis of.106        input_data_format (`ChannelDimension` or `str`, *optional*):107            The channel dimension format of the image. If `None`, will infer the channel dimension from the image.108 109    Returns:110        The channel dimension axis of the image.111    Nr[r�Unsupported data format: )rvrrr^r r7)r:rwr!r!r"�get_channel_dimension_axisOs112113114115ry�channel_dimcCsZ|durt|�}|tjkr|jd|jdfS|tjkr&|jd|jdfStd|����)a�116    Returns the (height, width) dimensions of the image.117 118    Args:119        image (`np.ndarray`):120            The image to get the dimensions of.121        channel_dim (`ChannelDimension`, *optional*):122            Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.123 124    Returns:125        A tuple of the image's height and width.126    N���������������rx)rvrrrsr r7)r:rzr!r!r"�get_image_sizegs
127128r~�129image_size�130max_height�	max_widthc131CsB|\}}||}||}t||�}t||�}t||�}	||	fS)a�132    Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio.133    Important, even if image_height < max_height and image_width < max_width, the image will be resized134    to at least one of the edges be equal to max_height or max_width.135 136    For example:137        - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50)138        - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400)139 140    Args:141        image_size (`tuple[int, int]`):142            The image to resize.143        max_height (`int`):144            The maximum allowed height.145        max_width (`int`):146            The maximum allowed width.147    )rXrr)148rr�r��height�widthZheight_scaleZwidth_scaleZ	min_scaleZ149new_heightZ	new_widthr!r!r"�#get_image_size_for_max_height_widths150r��151annotationcCsVt|t�r)d|vr)d|vr)t|dttf�r)t|d�dks't|ddt�r)dSdS)N�image_id�annotationsrTF�r*�dictrLrR�len�r�r!r!r"�"is_valid_annotation_coco_detection�s��"r�cCs^t|t�r-d|vr-d|vr-d|vr-t|dttf�r-t|d�dks+t|ddt�r-dSdS)Nr�Z
segments_info�	file_namerTFr�r�r!r!r"�!is_valid_annotation_coco_panoptic�s��"r�r�cC�tdd�|D��S)Ncsr>r))r��r@�annr!r!r"rA�rBz3valid_coco_detection_annotations.<locals>.<genexpr>rC�r�r!r!r"� valid_coco_detection_annotations��r�cCr�)Ncsr>r))r�r�r!r!r"rA�rBz2valid_coco_panoptic_annotations.<locals>.<genexpr>rCr�r!r!r"�valid_coco_panoptic_annotations�r�r��timeoutc152Cs�ttdg�t|t�re|�d�s|�d�r$tj�tt	j153||d�j��}nLtj
�|�r1tj�|�}n?|�d�r=|�d�d}zt�|���}tj�t|��}Wn!tyd}z154td|�d	|����d155}~wwt|tjj�sptd��tj�|�}|�d�}|S)
a3156    Loads `image` to a PIL Image.157 158    Args:159        image (`str` or `PIL.Image.Image`):160            The image to convert to the PIL Image format.161        timeout (`float`, *optional*):162            The timeout value in seconds for the URL request.163 164    Returns:165        `PIL.Image.Image`: A PIL Image.166    Zvisionzhttp://zhttps://�r�zdata:image/�,rz�Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got z. Failed with NzuIncorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image.�RGB)r�167load_imager*�str�168startswithr+r,�openr�requests�get�content�os�path�isfile�split�base64�decodebytes�encode�	Exceptionr7�	TypeErrorZImageOpsZexif_transpose�convert)r:r�Zb64�er!r!r"r��s0
169170����171r�csXt|ttf�r&t|�rt|dttf�r�fdd�|D�S�fdd�|D�St|�d�S)aLoads images, handling different levels of nesting.172 173    Args:174      images: A single image, a list of images, or a list of lists of images to load.175      timeout: Timeout for loading images.176 177    Returns:178      A single image, a list of images, a list of lists of images.179    rcsg|]}�fdd�|D��qS)c�g|]}t|�d��qS�r��r�r?r�r!r"rH��z*load_images.<locals>.<listcomp>.<listcomp>r!)r@Zimage_groupr�r!r"rH�szload_images.<locals>.<listcomp>cr�r�r�r?r�r!r"rH�r�r�)r*rLrRr�r�)r=r�r!r�r"�load_images�s180r��181do_rescale�rescale_factor�do_normalize�182image_mean�	image_std�do_pad�pad_size�do_center_crop�	crop_size�	do_resize�size�resample�PILImageResampling�
interpolationrc

Cs�|r183|dur184td��|r|durtd��|r"|dus|dur"td��|r,|dur,td��|dur8|dur8td��|	rJ|185durF|dusL|dusNtd��dSdSdS)a�186    Checks validity of typically used arguments in an `ImageProcessor` `preprocess` method.187    Raises `ValueError` if arguments incompatibility is caught.188    Many incompatibilities are model-specific. `do_pad` sometimes needs `size_divisor`,189    sometimes `size_divisibility`, and sometimes `size`. New models and processors added should follow190    existing arguments when possible.191 192    Nz=`rescale_factor` must be specified if `do_rescale` is `True`.zgDepending on the model, `size_divisor` or `pad_size` or `size` must be specified if `do_pad` is `True`.zP`image_mean` and `image_std` must both be specified if `do_normalize` is `True`.z<`crop_size` must be specified if `do_center_crop` is `True`.zbOnly one of `interpolation` and `resample` should be specified, depending on image processor type.zO`size` and `resample/interpolation` must be specified if `do_resize` is `True`.)r7)
r�r�r�r�r�r�r�r�r�r�r�r�r�r!r!r"�validate_preprocess_argumentss"���r�c@s�eZdZdZdd�Zddd�Zdd�Zd	ejd193e	e194efdejfdd
�Zd dd�Z
dd�Zd!dd�Zd"dd�Zdd�Zdd�Zd#dd�ZdS)$�ImageFeatureExtractionMixinzD195    Mixin that contain utilities for preparing image features.196    cCs8t|tjjtjf�st|�stdt|��d���dSdS)Nz	Got type zU which is not supported, only `PIL.Image.Image`, `np.ndarray` and `torch.Tensor` are.)r*r+r,rMrNr
r7r8��selfr:r!r!r"�_ensure_format_supported>s197��z4ImageFeatureExtractionMixin._ensure_format_supportedNcCs�|�|�t|�r
|��}t|tj�rE|dur t|jdtj�}|jdkr3|j	ddvr3|�198ddd�}|r9|d}|�tj�}t
j�|�S|S)a"199        Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if200        needed.201 202        Args:203            image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):204                The image to convert to the PIL Image format.205            rescale (`bool`, *optional*):206                Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will207                default to `True` if the image type is a floating type, `False` otherwise.208        Nrr[rnrro��)r�r
r2r*rMrN�flatZfloatingr^rs�	transpose�astyperWr+r,Z	fromarray)r�r:�rescaler!r!r"�to_pil_imageEs209z(ImageFeatureExtractionMixin.to_pil_imagecCs&|�|�t|tjj�s|S|�d�S)z�210        Converts `PIL.Image.Image` to RGB format.211 212        Args:213            image (`PIL.Image.Image`):214                The image to convert.215        r�)r�r*r+r,r�r�r!r!r"�convert_rgbcs216217z'ImageFeatureExtractionMixin.convert_rgbr:�scalerUcCs|�|�||S)z7218        Rescale a numpy image by scale amount219        )r�)r�r:r�r!r!r"r�qs220z#ImageFeatureExtractionMixin.rescaleTcCs�|�|�t|tjj�rt�|�}t|�r|��}|dur&t|jdtj	�n|}|r4|�221|�tj�d�}|rB|j
dkrB|�ddd�}|S)a�222        Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first223        dimension.224 225        Args:226            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):227                The image to convert to a NumPy array.228            rescale (`bool`, *optional*):229                Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will230                default to `True` if the image is a PIL Image or an array/tensor of integers, `False` otherwise.231            channel_first (`bool`, *optional*, defaults to `True`):232                Whether or not to permute the dimensions of the image to put the channel dimension first.233        Nr�p?r[ror)r�r*r+r,rMrkr
r2r��integerr�r��float32r^r�)r�r:r��
channel_firstr!r!r"rlxs234235z*ImageFeatureExtractionMixin.to_numpy_arraycCsD|�|�t|tjj�r|St|�r|�d�}|Stj|dd�}|S)z�236        Expands 2-dimensional `image` to 3 dimensions.237 238        Args:239            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):240                The image to expand.241        rrJ)r�r*r+r,r
Z	unsqueezerM�expand_dimsr�r!r!r"r��s242243�z'ImageFeatureExtractionMixin.expand_dimsFcCsh|�|�t|tjj�r|j|dd�}n|r3t|tj�r'|�|�tj	�d�}nt244|�r3|�|��d�}t|tj�rXt|tj�sHt�|��|j
�}t|tj�sWt�|��|j
�}n6t245|�r�ddl}t||j�swt|tj�rr|�|�}n|�|�}t||j�s�t|tj�r�|�|�}n|�|�}|jdkr�|jddvr�||dd�ddf|dd�ddfS|||S)a
246        Normalizes `image` with `mean` and `std`. Note that this will trigger a conversion of `image` to a NumPy array247        if it's a PIL Image.248 249        Args:250            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):251                The image to normalize.252            mean (`list[float]` or `np.ndarray` or `torch.Tensor`):253                The mean (per channel) to use for normalization.254            std (`list[float]` or `np.ndarray` or `torch.Tensor`):255                The standard deviation (per channel) to use for normalization.256            rescale (`bool`, *optional*, defaults to `False`):257                Whether or not to rescale the image to be between 0 and 1. If a PIL image is provided, scaling will258                happen automatically.259        T)r�r�rNr[rn)r�r*r+r,rlrMrNr�r�r�r
�floatrkrVr1rOZ260from_numpyZtensorr^rs)r�r:�meanZstdr�r1r!r!r"�	normalize�s6261�262263(z%ImageFeatureExtractionMixin.normalizec
CsJ|dur|ntj}|�|�t|tjj�s|�|�}t|t�r#t|�}t|t	�s.t264|�dkr�|rBt|t	�r9||fn|d|df}n\|j\}}||krO||fn||f\}}	t|t	�r\|n|d}265||266krf|S|267t	|268|	|�}}|dur�||269kr�td|�d|����||kr�t	|||�|}}||kr�||fn||f}|j
||d�S)a�270        Resizes `image`. Enforces conversion of input to PIL.Image.271 272        Args:273            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):274                The image to resize.275            size (`int` or `tuple[int, int]`):276                The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be277                matched to this.278 279                If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If280                `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to281                this number. i.e, if height > width, then image will be rescaled to (size * height / width, size).282            resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):283                The filter to user for resampling.284            default_to_square (`bool`, *optional*, defaults to `True`):285                How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a286                square (`size`,`size`). If set to `False`, will replicate287                [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)288                with support for resizing only the smallest edge and providing an optional `max_size`.289            max_size (`int`, *optional*, defaults to `None`):290                The maximum allowed for the longer edge of the resized image: if the longer edge of the image is291                greater than `max_size` after being resized according to `size`, then the image is resized again so292                that the longer edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller293                edge may be shorter than `size`. Only used if `default_to_square` is `False`.294 295        Returns:296            image: A resized `PIL.Image.Image`.297        Nrrzmax_size = zN must be strictly greater than the requested size for the smaller edge size = )r�)r��BILINEARr�r*r+r,r�rLrRrrr�r�r7�resize)
r�r:r�r�Zdefault_to_square�max_sizer�r�Zshort�longZrequested_new_shortZ	new_shortZnew_longr!r!r"r��s4298299300$301��z"ImageFeatureExtractionMixin.resizecCsx|�|�t|t�s||f}t|�st|tj�r8|jdkr"|�|�}|jddvr0|jdd�n|jdd�}n302|j	d|j	df}|d|dd}||d}|d|dd}||d}t|t303jj�rr|�||||f�S|jddv}|s�t|tj�r�|�
ddd�}t|�r�|�ddd�}|dkr�||dkr�|dkr�||dkr�|d||�||�fS|jdd�t|d|d�t|d|d�f}	t|tj�r�tj||	d�}304n	t|�r�|�|	�}305|	d|dd}||d}|	d	|dd}
|
|d}||306d||�|
|�f<||7}||7}||
7}||
7}|307dtd|�t|308jd|��td|�t|309jd	|��f}310|311S)312a�313        Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to the314        size given, it will be padded (so the returned result has the size asked).315 316        Args:317            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape (n_channels, height, width) or (height, width, n_channels)):318                The image to resize.319            size (`int` or `tuple[int, int]`):320                The size to which crop the image.321 322        Returns:323            new_image: A center cropped `PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape: (n_channels,324            height, width).325        rorrnrN.r{)rsr|)r�r*rRr
rMrNr^r�rsr�r+r,�cropr�ZpermuterYZ326zeros_likeZ	new_zerosrX)r�r:r�Zimage_shape�top�bottom�left�rightr�Z	new_shapeZ	new_imageZtop_padZ327bottom_padZleft_padZ	right_padr!r!r"�center_crop#sP328329330331,(23324�z'ImageFeatureExtractionMixin.center_cropcCs>|�|�t|tjj�r|�|�}|ddd�dd�dd�fS)a�333        Flips the channel order of `image` from RGB to BGR, or vice versa. Note that this will trigger a conversion of334        `image` to a NumPy array if it's a PIL Image.335 336        Args:337            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):338                The image whose color channels to flip. If `np.ndarray` or `torch.Tensor`, the channel dimension should339                be first.340        Nr|)r�r*r+r,rlr�r!r!r"�flip_channel_orderns341 342343z.ImageFeatureExtractionMixin.flip_channel_orderrcCsL|dur|ntjj}|�|�t|tjj�s|�|�}|j||||||d�S)a�344        Returns a rotated copy of `image`. This method returns a copy of `image`, rotated the given number of degrees345        counter clockwise around its centre.346 347        Args:348            image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):349                The image to rotate. If `np.ndarray` or `torch.Tensor`, will be converted to `PIL.Image.Image` before350                rotating.351 352        Returns:353            image: A rotated `PIL.Image.Image`.354        N)r��expand�center�	translate�	fillcolor)r+r,�NEARESTr�r*r��rotate)r�r:Zangler�r�r�r�r�r!r!r"r�s
355356�z"ImageFeatureExtractionMixin.rotater))NT)F)NTN)NrNNN)rrr�__doc__r�r�r�rMrNrr�rrr�rlr�r�r�r�r�r�r!r!r!r"r�9s357"358 3593604CKr��annotation_format�supported_annotation_formatscCsX||vrtdt�d|����|tjurt|�std��|tjur(t|�s*td��dSdS)NzUnsupported annotation format: z must be one of z�Invalid COCO detection annotations. Annotations must a dict (single image) or list of dicts (batch of images) with the following keys: `image_id` and `annotations`, with the latter being a list of annotations in the COCO format.z�Invalid COCO panoptic annotations. Annotations must a dict (single image) or list of dicts (batch of images) with the following keys: `image_id`, `file_name` and `segments_info`, with the latter being a list of annotations in the COCO format.)r7�formatr$r%r�r&r�)r�r�r�r!r!r"�validate_annotations�s361�362��r��valid_processor_keys�captured_kwargscCs:t|��t|��}|rd�|�}t�d|�d��dSdS)Nz, zUnused or unrecognized kwargs: r])�set�363difference�joinrtru)r�r�Zunused_keysZunused_key_strr!r!r"�validate_kwargs�s364365�r�T)�frozenc@szeZdZUdZdZeeed<dZeeed<dZ	eeed<dZ366eeed<dZeeed<dZeeed<d	d367�Z
dS)�SizeDictz>368    Hashable dictionary to store image size information.369    Nr�r��longest_edge�
shortest_edger�r�cCs$t||�r370t||�Std|�d���)NzKey z not found in SizeDict.)�hasattr�getattr�KeyError)r��keyr!r!r"�__getitem__�s371372zSizeDict.__getitem__)rrrr�r�rrr�__annotations__r�r�r�r�r�r�r!r!r!r"r��s373r�)r[r))
NNNNNNNNNNNNN)^r�r��collections.abcr�dataclassesr�ior�typingrrr2rMr��utilsrr	r374rrr
rrrrrZutils.constantsrrrrrrZ	PIL.Imager+ZPIL.ImageOpsr,Z375Resamplingr�Ztorchvision.transformsrr�Z
NEAREST_EXACTZBOXr�ZHAMMINGZBICUBICZLANCZOSZpil_torch_interpolation_mappingr1Z376get_loggerrrtrNrLZ377ImageInputrr$r'r�r�rrZAnnotationTyper/r0r;r<rErQrSrT�boolrZr`rirjrlrRrvryr~r�r�r�r�r�r�r�r�r�r�r�r�r�r!r!r!r"�<module>s64 
378�	379�	)���380�(���381�'382���383�(���384�&385���386387�""&&$+���388����������	�389���
390�5a�391��392�
Aluode/PerceptionLabPortable · CoolFace