Ë
    T^(hh ã                   óF  — d Z ddlZddlm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mZmZmZ ddlmZmZmZmZ dd	lmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ dd
l%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,  e)«       rddl-Z-ddl.m/c m0Z1  e*«       rddl2m3Z3  e(«       rddl4Z5ddl6mZ7 ddl8m9Z9m:Z:  e+jv                  e<«      Z= G d„ de«      Z>ddde?de@fd„ZAddde?de@fd„ZBde@dej†                  fd„ZD	 d5de@dej†                  dee@e@f   dej†                  fd„ZE	 	 	 	 	 d6de@de@de?d e
e@   d!e
e	e@      d"e
eeFef      dee	e	e@      e	e@   f   fd#„ZGd$„ ZH	 d7d%„ZId&e	e@   d'e@d(e@fd)„ZJd&e	e@   d'e@d(e@fd*„ZKd8d+„ZLd8d,„ZMd9d-„ZNd:d.„ZOd;d/„ZPd<d0„ZQd1eeFef   dej†                  fd2„ZRd=d3„ZSd=d4„ZTdgZUy)>zImage processor class for SAM.é    N)Údeepcopy)Úproduct)ÚAnyÚDictÚListÚOptionalÚTupleÚUnioné   )ÚBaseImageProcessorÚBatchFeatureÚget_size_dict)Úconvert_to_rgbÚpadÚresizeÚto_channel_dimension_format)ÚIMAGENET_DEFAULT_MEANÚIMAGENET_DEFAULT_STDÚChannelDimensionÚ
ImageInputÚPILImageResamplingÚget_image_sizeÚinfer_channel_dimension_formatÚis_scaled_imageÚmake_list_of_imagesÚto_numpy_arrayÚvalid_imagesÚvalidate_preprocess_arguments)Ú
TensorTypeÚfilter_out_non_signature_kwargsÚis_tf_availableÚis_torch_availableÚis_torchvision_availableÚloggingÚrequires_backends)Úbatched_nms)Únumpy)ÚflattenÚ
shape_listc            )       ól  ‡ — e Zd ZdZdgZdddej                  dddddddddfdedee	e
f   dee	e
f   d	ed
edee
ef   dedeeeee   f      deeeee   f      dedee
   dee
   deddfˆ fd„Z	 	 d4dej"                  dee	e
f   deee	ef      deee	ef      dej"                  f
d„Zdee
e
f   de
fd„Zej,                  ddfdej"                  dee	e
f   d	edeee	ef      deee	ef      dej"                  fd„Z	 	 	 	 	 	 	 	 d5deded
ededeee	e
f      d	edee   deeeee   f      deeeee   f      dee   deee	e
f      deee	ef      fd„Z	 	 	 	 	 	 	 	 	 	 	 	 	 d6dedee   dee	e
f   d	ed
ee   dee   dee   deeeee   f      deeeee   f      dee   deee	e
f      dee   deee	ef      deee	ef      deej"                  ee
e
f   ee
e
f   f   fd„Z	 	 	 	 	 d7dedee   dee	e
f   dee   deee	e
f      deee	ef      dej"                  fd „Z e«       dddddddddddddddej:                  dfd!ed"ee   dee   deee	e
f      deee	e
f      d	ed#   d
ee   deee
ef      dee   deeeee   f      deeeee   f      dee   deee	e
f      deee	e
f      dee   d$eee	ef      dedeee	ef      f$d%„«       Z	 	 	 	 d8d&„Z 	 d9d'„Z!	 d9d(„Z"	 d:d)„Z#	 	 	 	 	 	 	 d;d*e
d+ed,ee
   d-eee
      d.ed/   deee	ef      d$e	fd0„Z$	 	 	 	 	 d<d1„Z%	 	 	 	 d=d2„Z&	 	 	 	 d=d3„Z'ˆ xZ(S )>ÚSamImageProcessora  
    Constructs a SAM image processor.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
            `do_resize` parameter in the `preprocess` method.
        size (`dict`, *optional*, defaults to `{"longest_edge": 1024}`):
            Size of the output image after resizing. Resizes the longest edge of the image to match
            `size["longest_edge"]` while maintaining the aspect ratio. Can be overridden by the `size` parameter in the
            `preprocess` method.
        mask_size (`dict`, *optional*, defaults to `{"longest_edge": 256}`):
            Size of the output segmentation map after resizing. Resizes the longest edge of the image to match
            `size["longest_edge"]` while maintaining the aspect ratio. Can be overridden by the `mask_size` parameter
            in the `preprocess` method.
        resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
            Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
            `preprocess` method.
        do_rescale (`bool`, *optional*, defaults to `True`):
            Wwhether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
            `do_rescale` parameter in the `preprocess` method.
        rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
            Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
            overridden by the `rescale_factor` parameter in the `preprocess` method.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
            method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
        image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
            Mean to use if normalizing the image. This is a float or list of floats the length of the number of
            channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
            overridden by the `image_mean` parameter in the `preprocess` method.
        image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
            Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
            number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
            Can be overridden by the `image_std` parameter in the `preprocess` method.
        do_pad (`bool`, *optional*, defaults to `True`):
            Whether to pad the image to the specified `pad_size`. Can be overridden by the `do_pad` parameter in the
            `preprocess` method.
        pad_size (`dict`, *optional*, defaults to `{"height": 1024, "width": 1024}`):
            Size of the output image after padding. Can be overridden by the `pad_size` parameter in the `preprocess`
            method.
        mask_pad_size (`dict`, *optional*, defaults to `{"height": 256, "width": 256}`):
            Size of the output segmentation map after padding. Can be overridden by the `mask_pad_size` parameter in
            the `preprocess` method.
        do_convert_rgb (`bool`, *optional*, defaults to `True`):
            Whether to convert the image to RGB.
    Úpixel_valuesTNgp?Ú	do_resizeÚsizeÚ	mask_sizeÚresampleÚ
do_rescaleÚrescale_factorÚdo_normalizeÚ
image_meanÚ	image_stdÚdo_padÚpad_sizeÚmask_pad_sizeÚdo_convert_rgbÚreturnc                 óî  •— t        ‰| �  d	i |¤Ž |�|nddi}t        |t        «      st	        |d¬«      n|}|�|ndddœ}t	        |d¬«      }|�|nddi}t        |t        «      st	        |d¬«      n|}|�|ndddœ}t	        |d¬«      }|| _        || _        || _        || _        || _	        || _
        || _        |�|nt        | _        |	�|	nt        | _        |
| _        || _        || _        || _        y )
NÚlongest_edgei   F©Úmax_sizeÚdefault_to_square)ÚheightÚwidthT©r?   é   © )ÚsuperÚ__init__Ú
isinstanceÚdictr   r-   r.   r/   r0   r1   r2   r3   r   r4   r   r5   r6   r7   r8   r9   )Úselfr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   ÚkwargsÚ	__class__s                  €új/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/sam/image_processing_sam.pyrF   zSamImageProcessor.__init__v   s  ø€ ô" 	‰ÑÑ"˜6Ò"ØÐ'‰t¨n¸dÐ-CˆÜLVÐW[Ô]aÔLbŒ} d¸eÕDÐhlˆà'Ð3‘8ÀDÐSWÑ9XˆÜ  ¸TÔBˆà!*Ð!6‘I¸^ÈSÐ<Qˆ	ô ˜i¬Ô.ô  9ÀÕFàð 	ð *7Ð)B™ÐSVÐadÑHeˆÜ% mÀtÔLˆà"ˆŒØˆŒ	Ø"ˆŒØ ˆŒØ$ˆŒØ,ˆÔØ(ˆÔØ(2Ð(>™*ÔDYˆŒØ&/Ð&;™ÔAUˆŒØˆŒØ ˆŒØ*ˆÔØ,ˆÕó    ÚimageÚdata_formatÚinput_data_formatc                 óz   — |d   |d   }}t        ||¬«      \  }}	||	z
  }
||z
  }t        |d|fd|
fff||dœ|¤Ž}|S )a½  
        Pad an image to `(pad_size["height"], pad_size["width"])` with zeros to the right and bottom.

        Args:
            image (`np.ndarray`):
                Image to pad.
            pad_size (`Dict[str, int]`):
                Size of the output image after padding.
            data_format (`str` or `ChannelDimension`, *optional*):
                The data format of the image. Can be either "channels_first" or "channels_last". If `None`, the
                `data_format` of the `image` will be used.
            input_data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
        r@   rA   ©Úchannel_dimr   )rO   rP   )r   r   )rI   rN   r7   rO   rP   rJ   Úoutput_heightÚoutput_widthÚinput_heightÚinput_widthÚ	pad_widthÚ
pad_heightÚpadded_images                rL   Ú	pad_imagezSamImageProcessor.pad_image¦   sy   € ð, '/¨xÑ&8¸(À7Ñ:K�|ˆÜ$2°5ÐFWÔ$XÑ!ˆ�kà  ;Ñ.ˆ	Ø" \Ñ1ˆ
äØØ�ˆ_˜q )˜nÐ-ð
ð $Ø/ñ	
ð
 ñ
ˆð ÐrM   Ú	old_shaper<   c                 ó„   — |\  }}|dz  t        ||«      z  }||z  ||z  }}t        |dz   «      }t        |dz   «      }||fS )zW
        Compute the output size given input size and target long side length.
        ç      ð?ç      à?)ÚmaxÚint)rI   r\   r<   ÚoldhÚoldwÚscaleÚnewhÚnewws           rL   Ú_get_preprocess_shapez'SamImageProcessor._get_preprocess_shapeË   sW   € ð ‰
ˆˆdØ˜sÑ"¤S¨¨t£_Ñ4ˆØ˜E‘\ 4¨%¡<ˆdˆÜ�4˜#‘:‹ˆÜ�4˜#‘:‹ˆØ�dˆ|ÐrM   c                 óÈ   — t        |«      }d|vrt        d|j                  «       › �«      ‚t        ||¬«      }| j	                  ||d   «      \  }}	t        |f||	f|||dœ|¤ŽS )a/  
        Resize an image to `(size["height"], size["width"])`.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Dictionary in the format `{"longest_edge": int}` specifying the size of the output image. The longest
                edge of the image will be resized to the specified size, while the other edge will be resized to
                maintain the aspect ratio.
            resample:
                `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
            data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the output image. If unset, the channel dimension format of the input
                image is used. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.

        Returns:
            `np.ndarray`: The resized image.
        r<   z?The `size` dictionary must contain the key `longest_edge`. Got rR   )r.   r0   rO   rP   )r   Ú
ValueErrorÚkeysr   rg   r   )
rI   rN   r.   r0   rO   rP   rJ   Ú
input_sizerT   rU   s
             rL   r   zSamImageProcessor.resizeÖ   s�   € ôF ˜TÓ"ˆØ Ñ%ÜÐ^Ð_c×_hÑ_hÓ_jÐ^kÐlÓmÐmÜ# EÐ7HÔIˆ
Ø&*×&@Ñ&@ÀÈTÐR`ÑMaÓ&bÑ#ˆ�|ÜØð
à Ð.ØØ#Ø/ñ
ð ñ
ð 	
rM   c                 óØ   — |r| j                  ||||¬«      }t        ||¬«      }|r| j                  |||¬«      }|r| j                  |||	|¬«      }|
r| j	                  |||¬«      }||fS )N)rN   r.   r0   rP   rR   )rN   rd   rP   )rN   ÚmeanÚstdrP   )rN   r7   rP   )r   r   ÚrescaleÚ	normalizer[   )rI   rN   r-   r1   r3   r.   r0   r2   r4   r5   r6   r7   rP   Úreshaped_input_sizes                 rL   Ú_preprocesszSamImageProcessor._preprocess  s‚   € ñ Ø—K‘K e°$ÀÐ]n�KÓoˆEÜ,¨UÐ@QÔRÐáØ—L‘L u°NÐVg�LÓhˆEáØ—N‘N¨°ZÀYÐbs�NÓtˆEáØ—N‘N¨¸ÐUf�NÓgˆEàÐ)Ð)Ð)rM   c                 ó  — |rt        |«      }t        |«      }|r t        |«      rt        j	                  d«       |€t        |«      }t        ||¬«      }| j                  |||||||||	|
||¬«      \  }}|�t        |||¬«      }|||fS )Nz­It looks like you are trying to rescale already rescaled images. If the input images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.rR   )rN   r-   r.   r0   r1   r2   r3   r4   r5   r6   r7   rP   )Úinput_channel_dim)	r   r   r   ÚloggerÚwarning_oncer   r   rr   r   )rI   rN   r-   r.   r0   r1   r2   r3   r4   r5   r6   r7   r9   rO   rP   Úoriginal_sizerq   s                    rL   Ú_preprocess_imagez#SamImageProcessor._preprocess_image%  s¿   € ñ$ Ü" 5Ó)ˆEô ˜uÓ%ˆáœ/¨%Ô0Ü×Ñðsôð
 Ð$Ü >¸uÓ EÐä& uÐ:KÔLˆà%)×%5Ñ%5ØØØØØ!Ø)Ø%Ø!ØØØØ/ð &6ó &
Ñ"ˆÐ"ð Ð"Ü/°°{ÐVgÔhˆEà�mÐ%8Ð8Ð8rM   Úsegmentation_mapc                 ód  — t        |«      }|j                  dk(  rd}|d   }t        j                  }nd}|€t	        |d¬«      }t        ||¬«      }| j                  |||t        j                  dd|||¬«	      \  }}	|r|j                  d	«      }|j                  t        j                  «      }||fS )
Né   T)N.Fé   )Únum_channelsrR   )	rN   r-   r.   r0   r1   r3   r6   r7   rP   r   )r   Úndimr   ÚFIRSTr   r   rr   r   ÚNEARESTÚsqueezeÚastypeÚnpÚint64)
rI   ry   r-   r/   r6   r8   rP   Úadded_channel_dimrw   Ú_s
             rL   Ú_preprocess_maskz"SamImageProcessor._preprocess_mask\  sØ   € ô *Ð*:Ó;Ðð × Ñ  AÒ%Ø $ÐØ/°	Ñ:ÐÜ 0× 6Ñ 6Ñà %ÐØ Ð(Ü$BÐCSÐbcÔ$dÐ!ä&Ð'7ÐEVÔWˆà"×.Ñ.Ø"ØØÜ'×/Ñ/ØØØØ"Ø/ð /ó 

ÑÐ˜!ñ Ø/×7Ñ7¸Ó:ÐØ+×2Ñ2´2·8±8Ó<Ðà Ð.Ð.rM   ÚimagesÚsegmentation_mapsr   Úreturn_tensorsc                 ó  ‡ ‡‡‡‡‡‡‡	‡
‡‡‡‡‡‡‡— ‰�‰n‰ j                   Š‰�‰n‰ j                  Št        ‰t        «      st	        ‰d¬«      n‰Š‰�‰n‰ j
                  Št        ‰t        «      st	        ‰d¬«      n‰Š‰�‰n‰ j                  Š‰�‰n‰ j                  Š‰�‰n‰ j                  Š‰	�‰	n‰ j                  Š	‰
�‰
n‰ j                  Š
‰�‰n‰ j                  Š‰�‰n‰ j                  Š‰�‰n‰ j                  Št	        ‰d¬«      Š‰�‰n‰ j                  Št	        ‰d¬«      Š‰�‰n‰ j                  Št!        |«      }t#        |«      st%        d«      ‚|�#t!        |d¬«      }t#        |«      st%        d«      ‚t'        ‰‰‰	‰
‰‰‰‰‰‰¬	«
       t)        ˆˆˆ	ˆˆˆˆ
ˆˆˆˆˆˆ ˆfd
„|D «       Ž \  }}}|||dœ}|�At)        ˆˆˆˆˆˆ fd„|D «       Ž \  }}t+        d„ t)        ||«      D «       «      sJ d«       ‚||d<   t-        ||¬«      S )aš  
        Preprocess an image or batch of images.

        Args:
            images (`ImageInput`):
                Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
                passing in images with pixel values between 0 and 1, set `do_rescale=False`.
            segmentation_maps (`ImageInput`, *optional*):
                Segmentation map to preprocess.
            do_resize (`bool`, *optional*, defaults to `self.do_resize`):
                Whether to resize the image.
            size (`Dict[str, int]`, *optional*, defaults to `self.size`):
                Controls the size of the image after `resize`. The longest edge of the image is resized to
                `size["longest_edge"]` whilst preserving the aspect ratio.
            mask_size (`Dict[str, int]`, *optional*, defaults to `self.mask_size`):
                Controls the size of the segmentation map after `resize`. The longest edge of the image is resized to
                `size["longest_edge"]` whilst preserving the aspect ratio.
            resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
                `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
            do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image pixel values by rescaling factor.
            rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`):
                Rescale factor to apply to the image pixel values.
            do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
                Whether to normalize the image.
            image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
                Image mean to normalize the image by if `do_normalize` is set to `True`.
            image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
                Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
            do_pad (`bool`, *optional*, defaults to `self.do_pad`):
                Whether to pad the image.
            pad_size (`Dict[str, int]`, *optional*, defaults to `self.pad_size`):
                Controls the size of the padding applied to the image. The image is padded to `pad_size["height"]` and
                `pad_size["width"]` if `do_pad` is set to `True`.
            mask_pad_size (`Dict[str, int]`, *optional*, defaults to `self.mask_pad_size`):
                Controls the size of the padding applied to the segmentation map. The image is padded to
                `mask_pad_size["height"]` and `mask_pad_size["width"]` if `do_pad` is set to `True`.
            do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
                Whether to convert the image to RGB.
            return_tensors (`str` or `TensorType`, *optional*):
                The type of tensors to return. Can be one of:
                    - Unset: Return a list of `np.ndarray`.
                    - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
                    - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
                    - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
                    - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
            data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
                The channel dimension format for the output image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - Unset: Use the channel dimension format of the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
        Fr=   TrB   zkInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.r{   )Úexpected_ndimszvInvalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.)
r1   r2   r3   r4   r5   r6   Úsize_divisibilityr-   r.   r0   c              3   ó\   •K  — | ]#  }‰j                  |‰‰‰‰‰‰‰‰	‰‰‰‰‰
¬ «      –— Œ% y­w))rN   r-   r.   r0   r1   r2   r3   r4   r5   r6   r7   r9   rO   rP   N)rx   )Ú.0ÚimgrO   r9   r3   r6   r1   r-   r4   r5   rP   r7   r0   r2   rI   r.   s     €€€€€€€€€€€€€€rL   ú	<genexpr>z/SamImageProcessor.preprocess.<locals>.<genexpr>
  sU   øè ø€ ò ð" ð! ×&Ñ&ØØ'ØØ%Ø)Ø#1Ø!-Ø)Ø'Ø!Ø%Ø#1Ø +Ø&7ð '÷ ñùs   ƒ),)r,   Úoriginal_sizesÚreshaped_input_sizesc           	   3   óL   •K  — | ]  }‰j                  |‰‰‰‰‰¬ «      –— Œ y­w))ry   r-   r/   r6   r8   rP   N)r‡   )r�   Úmaskr6   r-   rP   r8   r/   rI   s     €€€€€€rL   r‘   z/SamImageProcessor.preprocess.<locals>.<genexpr>'  s=   øè ø€ ò 
ð ð ×)Ñ)Ø)-Ø"+Ø"+Ø%Ø&3Ø*;ð *÷ ñ
ùs   ƒ!$c              3   ó,   K  — | ]  \  }}||k(  –— Œ y ­w©NrD   )r�   Úoriginal_im_sizeÚoriginal_mask_sizes      rL   r‘   z/SamImageProcessor.preprocess.<locals>.<genexpr>5  s$   è ø€ ò á8Ð$Ð&8ð !Ð$6Õ6ñùs   ‚z:Segmentation maps should be the same size as input images.Úlabels)ÚdataÚtensor_type)r-   r.   rG   rH   r   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r   r   ri   r   ÚzipÚallr   )rI   rˆ   r‰   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   rŠ   rO   rP   r’   r“   r›   Úoriginal_mask_sizess   `  ````````````` ``    rL   Ú
preprocesszSamImageProcessor.preprocess†  sk  ÿÿ€ ð` "+Ð!6‘I¸D¿N¹Nˆ	ØÐ'‰t¨T¯Y©YˆÜLVÐW[Ô]aÔLbŒ} d¸eÕDÐhlˆØ!*Ð!6‘I¸D¿N¹Nˆ	ô ˜i¬Ô.ô  9ÀÕFàð 	ð
  (Ð3‘8¸¿¹ˆØ#-Ð#9‘Z¸t¿¹ˆ
Ø+9Ð+E™È4×K^ÑK^ˆØ'3Ð'?‘|ÀT×EVÑEVˆØ#-Ð#9‘Z¸t¿¹ˆ
Ø!*Ð!6‘I¸D¿N¹Nˆ	Ø!Ð-‘°4·;±;ˆØ'Ð3‘8¸¿¹ˆÜ  ¸TÔBˆØ)6Ð)B™È×HZÑHZˆÜ% mÀtÔLˆØ+9Ð+E™È4×K^ÑK^ˆä$ VÓ,ˆä˜FÔ#Üð:óð ð
 Ð(Ü 3Ð4EÐVWÔ XÐäÐ 1Ô2Ü ð>óð ô 	&Ø!Ø)Ø%Ø!ØØØ&ØØØõ	
ô 8;÷÷ ð ð" "ô#ð8
Ñ4ˆ�Ð 4ð. #Ø,Ø$8ñ
ˆð Ð(Ü58÷
ð 
ð !2ô
ð6Ñ2ÐÐ2ô ñ ä<?ÀÐPcÓ<dôô ð Lð LóLð ð
 /ˆD�‰Nä °>ÔBÐBrM   c                 óˆ   — |dk(  r| j                  ||||||¬«      S |dk(  r| j                  ||||||¬«      S t        d«      ‚)a  
        Remove padding and upscale masks to the original image size.

        Args:
            masks (`Union[List[torch.Tensor], List[np.ndarray], List[tf.Tensor]]`):
                Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
            original_sizes (`Union[torch.Tensor, tf.Tensor, List[Tuple[int,int]]]`):
                The original sizes of each image before it was resized to the model's expected input shape, in (height,
                width) format.
            reshaped_input_sizes (`Union[torch.Tensor, tf.Tensor, List[Tuple[int,int]]]`):
                The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
            mask_threshold (`float`, *optional*, defaults to 0.0):
                The threshold to use for binarizing the masks.
            binarize (`bool`, *optional*, defaults to `True`):
                Whether to binarize the masks.
            pad_size (`int`, *optional*, defaults to `self.pad_size`):
                The target size the images were padded to before being passed to the model. If None, the target size is
                assumed to be the processor's `pad_size`.
            return_tensors (`str`, *optional*, defaults to `"pt"`):
                If `"pt"`, return PyTorch tensors. If `"tf"`, return TensorFlow tensors.
        Returns:
            (`Union[torch.Tensor, tf.Tensor]`): Batched masks in batch_size, num_channels, height, width) format, where
            (height, width) is given by original_size.
        Úpt)Úmasksr’   r“   Úmask_thresholdÚbinarizer7   Útfz*return_tensors must be either 'pt' or 'tf')Ú_post_process_masks_ptÚ_post_process_masks_tfri   )rI   r£   r’   r“   r¤   r¥   r7   rŠ   s           rL   Úpost_process_masksz$SamImageProcessor.post_process_masks>  sy   € ðD ˜TÒ!Ø×.Ñ.ØØ-Ø%9Ø-Ø!Ø!ð /ó ð ð ˜tÒ#Ø×.Ñ.ØØ-Ø%9Ø-Ø!Ø!ð /ó ð ô ÐIÓJÐJrM   c                 óò  — t        | dg«       |€| j                  n|}|d   |d   f}t        |t        j                  t
        j                  f«      r|j                  «       }t        |t        j                  t
        j                  f«      r|j                  «       }g }t        |«      D ]Ë  \  }	}
t        ||	   t
        j                  «      rt        j                  ||	   «      ||	<   n(t        ||	   t        j                  «      st        d«      ‚t        j                  ||	   |dd¬«      }|d	d||	   d
   …d||	   d   …f   }t        j                  ||
dd¬«      }|r||kD  }|j                  |«       ŒÍ |S )aF  
        Remove padding and upscale masks to the original image size.

        Args:
            masks (`Union[List[torch.Tensor], List[np.ndarray]]`):
                Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
            original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
                The original sizes of each image before it was resized to the model's expected input shape, in (height,
                width) format.
            reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
                The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
            mask_threshold (`float`, *optional*, defaults to 0.0):
                The threshold to use for binarizing the masks.
            binarize (`bool`, *optional*, defaults to `True`):
                Whether to binarize the masks.
            pad_size (`int`, *optional*, defaults to `self.pad_size`):
                The target size the images were padded to before being passed to the model. If None, the target size is
                assumed to be the processor's `pad_size`.
        Returns:
            (`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
            is given by original_size.
        ÚtorchNr@   rA   zIInput masks should be a list of `torch.tensors` or a list of `np.ndarray`ÚbilinearF)ÚmodeÚalign_corners.r   r|   )r%   r7   rG   r«   ÚTensorrƒ   ÚndarrayÚtolistÚ	enumerateÚ
from_numpyri   ÚFÚinterpolateÚappend)rI   r£   r’   r“   r¤   r¥   r7   Útarget_image_sizeÚoutput_masksÚirw   Úinterpolated_masks               rL   r§   z(SamImageProcessor._post_process_masks_ptu  sw  € ô2 	˜$  	Ô*Ø$,Ð$4�4—=’=¸(ˆØ% hÑ/°¸'Ñ1BÐCÐÜ�n¤u§|¡|´R·Z±ZÐ&@ÔAØ+×2Ñ2Ó4ˆNÜÐ*¬U¯\©\¼2¿:¹:Ð,FÔGØ#7×#>Ñ#>Ó#@Ð ØˆÜ )¨.Ó 9ò 
	3ÑˆAˆ}Ü˜% ™(¤B§J¡JÔ/Ü ×+Ñ+¨E°!©HÓ5��a’Ü  a¡¬%¯,©,Ô7Ü Ð!lÓmÐmÜ !§¡¨e°A©hÐ8IÐPZÐjoÔ pÐØ 1°#Ð7SÐ9MÈaÑ9PÐQRÑ9SÐ7SÐUqÐWkÐlmÑWnÐopÑWqÐUqÐ2qÑ rÐÜ !§¡Ð.?ÀÐU_ÐotÔ uÐÙØ$5¸Ñ$FÐ!Ø×ÑÐ 1Õ2ð
	3ð ÐrM   c                 óÖ  — t        | dg«       |€| j                  n|}|d   |d   f}g }t        |«      D ]±  \  }	}
t        j                  ||	   g d¢¬«      }t        j
                  j                  ||d¬«      }|dd…d||	   d	   …d||	   d
   …dd…f   }t        j
                  j                  ||
d¬«      }|r||kD  }|j                  t        j                  |g d¢¬«      «       Œ³ |S )aµ  
        Remove padding and upscale masks to the original image size.

        Args:
            masks (`tf.Tensor`):
                Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
            original_sizes (`tf.Tensor`):
                The original size of the images before resizing for input to the model, in (height, width) format.
            reshaped_input_sizes (`tf.Tensor`):
                The size of the image input to the model, in (height, width) format. Used to remove padding.
            mask_threshold (`float`, *optional*, defaults to 0.0):
                The threshold to use for binarizing the masks.
            binarize (`bool`, *optional*, defaults to `True`):
                Whether to binarize the masks.
            pad_size (`int`, *optional*, defaults to `self.pad_size`):
                The target size the images were padded to before being passed to the model. If None, the target size is
                assumed to be the processor's `pad_size`.
        Returns:
            (`tf.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width) is
            given by original_size.
        r¦   Nr@   rA   )r   r{   r   r|   ©Úpermr¬   )Úmethodr   r|   )r   r   r|   r{   )r%   r7   r²   r¦   Ú	transposerN   r   r¶   )rI   r£   r’   r“   r¤   r¥   r7   r·   r¸   r¹   rw   r•   rº   s                rL   r¨   z(SamImageProcessor._post_process_masks_tf¤  s  € ô0 	˜$  Ô'Ø$,Ð$4�4—=’=¸(ˆØ% hÑ/°¸'Ñ1BÐCÐàˆÜ )¨.Ó 9ò 		TÑˆAˆ}ä—<‘<  a¡ª|Ô<ˆDÜ "§¡§¡°Ð6GÐPZ Ó [ÐØ 1²!Ð5QÐ7KÈAÑ7NÈqÑ7QÐ5QÐSoÐUiÐjkÑUlÐmnÑUoÐSoÒqrÐ2rÑ sÐÜ "§¡§¡Ð0AÀ=ÐYc Ó dÐÙØ$5¸Ñ$FÐ!à×Ñ¤§¡Ð->Â\Ô RÕSð		Tð ÐrM   c                 óP   — |dk(  rt        ||||«      S |dk(  rt        ||||«      S y)a  
        Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.

        Args:
            all_masks (`Union[List[torch.Tensor], List[tf.Tensor]]`):
                List of all predicted segmentation masks
            all_scores (`Union[List[torch.Tensor], List[tf.Tensor]]`):
                List of all predicted iou scores
            all_boxes (`Union[List[torch.Tensor], List[tf.Tensor]]`):
                List of all bounding boxes of the predicted masks
            crops_nms_thresh (`float`):
                Threshold for NMS (Non Maximum Suppression) algorithm.
            return_tensors (`str`, *optional*, defaults to `pt`):
                If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.
        r¢   r¦   N)Ú_postprocess_for_mgÚ_postprocess_for_mg_tf)rI   Ú	all_masksÚ
all_scoresÚ	all_boxesÚcrops_nms_threshrŠ   s         rL   Ú post_process_for_mask_generationz2SamImageProcessor.post_process_for_mask_generationÎ  s=   € ð$ ˜TÒ!Ü& y°*¸iÐIYÓZÐZØ˜tÒ#Ü)¨)°ZÀÐL\Ó]Ð]ð $rM   Úcrop_n_layersÚoverlap_ratioÚpoints_per_cropÚcrop_n_points_downscale_factorÚdeviceztorch.devicec
           	      ó¸  — t        |||||||«      \  }
}}}|	dk(  r]|€t        j                  d«      }t        j                  |
|¬«      }
t        j                  ||¬«      }t        j                  ||¬«      }n]|	dk(  rM|�t	        d«      ‚t        j                  |
«      }
t        j                  |«      }t        j                  |«      }nt	        d«      ‚|
|||fS )aC  
        Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

        Args:
            image (`np.array`):
                Input original image
            target_size (`int`):
                Target size of the resized image
            crop_n_layers (`int`, *optional*, defaults to 0):
                If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where
                each layer has 2**i_layer number of image crops.
            overlap_ratio (`float`, *optional*, defaults to 512/1500):
                Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
                the image length. Later layers with more crops scale down this overlap.
            points_per_crop (`int`, *optional*, defaults to 32):
                Number of points to sample from each crop.
            crop_n_points_downscale_factor (`List[int]`, *optional*, defaults to 1):
                The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
            device (`torch.device`, *optional*, defaults to None):
                Device to use for the computation. If None, cpu will be used.
            input_data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
            return_tensors (`str`, *optional*, defaults to `pt`):
                If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.
        r¢   Úcpu©rÌ   r¦   z=device is not a supported argument when return_tensors is tf!z+return_tensors must be either 'pt' or 'tf'.)Ú_generate_crop_boxesr«   rÌ   Útensorri   r¦   Úconvert_to_tensor)rI   rN   Útarget_sizerÈ   rÉ   rÊ   rË   rÌ   rP   rŠ   Ú
crop_boxesÚcropped_imagesÚinput_labelss                rL   Úgenerate_crop_boxesz%SamImageProcessor.generate_crop_boxeså  sâ   € ôJ EYØØØØØØ*ØóE
ÑAˆ
�O ^°\ð ˜TÒ!Øˆ~ÜŸ™ eÓ,�ÜŸ™ j¸Ô@ˆJÜ#Ÿl™l¨?À6ÔJˆOä Ÿ<™<¨¸VÔD‰Là˜tÒ#ØÐ!Ü Ð!`ÓaÐaÜ×-Ñ-¨jÓ9ˆJÜ ×2Ñ2°?ÓCˆOä×/Ñ/°Ó=‰LäÐJÓKÐKØ˜?¨N¸LÐHÐHrM   c
           
      ó|   — |	dk(  r| j                  ||||||||¬«      S |	dk(  r| j                  ||||||||¬«      S y)a»  
        Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
        that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
        score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
        bounding boxes and pad the predicted masks if necessary.

        Args:
            masks (`Union[torch.Tensor, tf.Tensor]`):
                Input masks.
            iou_scores (`Union[torch.Tensor, tf.Tensor]`):
                List of IoU scores.
            original_size (`Tuple[int,int]`):
                Size of the orginal image.
            cropped_box_image (`np.array`):
                The cropped image.
            pred_iou_thresh (`float`, *optional*, defaults to 0.88):
                The threshold for the iou scores.
            stability_score_thresh (`float`, *optional*, defaults to 0.95):
                The threshold for the stability score.
            mask_threshold (`float`, *optional*, defaults to 0):
                The threshold for the predicted masks.
            stability_score_offset (`float`, *optional*, defaults to 1):
                The offset for the stability score used in the `_compute_stability_score` method.
            return_tensors (`str`, *optional*, defaults to `pt`):
                If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.
        r¢   )r£   Ú
iou_scoresrw   Úcropped_box_imageÚpred_iou_threshÚstability_score_threshr¤   Ústability_score_offsetr¦   N)Ú_filter_masks_ptÚ_filter_masks_tf)
rI   r£   rÙ   rw   rÚ   rÛ   rÜ   r¤   rÝ   rŠ   s
             rL   Úfilter_maskszSamImageProcessor.filter_masks&  s|   € ðL ˜TÒ!Ø×(Ñ(ØØ%Ø+Ø"3Ø /Ø'=Ø-Ø'=ð )ó 	ð 	ð ˜tÒ#Ø×(Ñ(ØØ%Ø+Ø"3Ø /Ø'=Ø-Ø'=ð )ó 	ð 	ð $rM   c	                 ó¨  — t        | dg«       |\  }	}
|j                  dd«      }|j                  dd«      }|j                  d   |j                  d   k7  rt        d«      ‚|j                  |j                  k7  r|j                  |j                  «      }|j                  d   }t        j                  |t        j                  |j                  ¬«      }|dkD  r|||kD  z  }|dkD  rt        |||«      }|||kD  z  }||   }||   }||kD  }t        |«      }t        ||dd|
|	g«       }||   }||   }||   }t        |||	|
«      }t        |«      }|||fS )a  
        Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
        that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
        score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
        bounding boxes and pad the predicted masks if necessary.

        Args:
            masks (`torch.Tensor`):
                Input masks.
            iou_scores (`torch.Tensor`):
                List of IoU scores.
            original_size (`Tuple[int,int]`):
                Size of the orginal image.
            cropped_box_image (`np.array`):
                The cropped image.
            pred_iou_thresh (`float`, *optional*, defaults to 0.88):
                The threshold for the iou scores.
            stability_score_thresh (`float`, *optional*, defaults to 0.95):
                The threshold for the stability score.
            mask_threshold (`float`, *optional*, defaults to 0):
                The threshold for the predicted masks.
            stability_score_offset (`float`, *optional*, defaults to 1):
                The offset for the stability score used in the `_compute_stability_score` method.

        r«   r   r|   ú3masks and iou_scores must have the same batch size.©ÚdtyperÌ   ç        )r%   r(   Úshaperi   rÌ   Útor«   ÚonesÚboolÚ_compute_stability_score_ptÚ_batched_mask_to_boxÚ_is_box_near_crop_edgeÚ
_pad_masksÚ_mask_to_rle_pytorch©rI   r£   rÙ   rw   rÚ   rÛ   rÜ   r¤   rÝ   Úoriginal_heightÚoriginal_widthÚ
batch_sizeÚ	keep_maskÚstability_scoresÚscoresÚconverted_boxess                   rL   rÞ   z"SamImageProcessor._filter_masks_ptc  sƒ  € ôH 	˜$  	Ô*Ø*7Ñ'ˆ˜Ø×'Ñ'¨¨1Ó-ˆ
Ø—‘˜a Ó#ˆà�;‰;�q‰>˜Z×-Ñ-¨aÑ0Ò0ÜÐRÓSÐSà�<‰<˜:×,Ñ,Ò,Ø#Ÿ™ u§|¡|Ó4ˆJà—[‘[ ‘^ˆ
ä—J‘J˜z´·±ÀEÇLÁLÔQˆ	à˜SÒ Ø! Z°/Ñ%AÑBˆIð " CÒ'Ü:¸5À.ÐRhÓiÐØ!Ð%5Ð8NÑ%NÑOˆIà˜IÑ&ˆØ�iÑ ˆð ˜Ñ&ˆÜ.¨uÓ5ˆä+ØÐ.°°A°~ÀÐ0Wó
ð 
ˆ	ð ˜	Ñ"ˆØ�iÑ ˆØ)¨)Ñ4ˆä˜5Ð"3°_ÀnÓUˆä$ UÓ+ˆà�f˜oÐ-Ð-rM   c	                 óê  — t        | dg«       |\  }	}
t        j                  ||j                  d   |j                  d   z  |j                  dd g«      }t        j                  ||j                  d   |j                  d   z  |j                  dd g«      }|j                  d   |j                  d   k7  rt	        d«      ‚|j                  d   }t        j
                  |t        j                  ¬«      }|dkD  r|||kD  z  }|dkD  rt        |||«      }|||kD  z  }||   }||   }||kD  }t        |«      }t        ||dd|
|	g«       }||   }||   }||   }t        |||	|
«      }t        |«      }|||fS )	a  
        Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
        that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
        score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
        bounding boxes and pad the predicted masks if necessary.

        Args:
            masks (`tf.Tensor`):
                Input masks.
            iou_scores (`tf.Tensor`):
                List of IoU scores.
            original_size (`Tuple[int,int]`):
                Size of the orginal image.
            cropped_box_image (`np.array`):
                The cropped image.
            pred_iou_thresh (`float`, *optional*, defaults to 0.88):
                The threshold for the iou scores.
            stability_score_thresh (`float`, *optional*, defaults to 0.95):
                The threshold for the stability score.
            mask_threshold (`float`, *optional*, defaults to 0):
                The threshold for the predicted masks.
            stability_score_offset (`float`, *optional*, defaults to 1):
                The offset for the stability score used in the `_compute_stability_score` method.

        r¦   r   r|   r{   Nrâ   ©rä   rå   )r%   r¦   Úreshaperæ   ri   rè   ré   Ú_compute_stability_score_tfÚ_batched_mask_to_box_tfÚ_is_box_near_crop_edge_tfÚ_pad_masks_tfÚ_mask_to_rle_tfrï   s                   rL   rß   z"SamImageProcessor._filter_masks_tf³  s®  € ôH 	˜$  Ô'Ø*7Ñ'ˆ˜Ü—Z‘Z 
¨Z×-=Ñ-=¸aÑ-@À:×CSÑCSÐTUÑCVÑ-VÐXb×XhÑXhÐijÐikÐXlÐ,mÓnˆ
Ü—
‘
˜5 5§;¡;¨q¡>°E·K±KÀ±NÑ#BÀEÇKÁKÐPQÐPRÀOÐ"TÓUˆà�;‰;�q‰>˜Z×-Ñ-¨aÑ0Ò0ÜÐRÓSÐSà—[‘[ ‘^ˆ
ä—G‘G˜J¬b¯g©gÔ6ˆ	à˜SÒ Ø! Z°/Ñ%AÑBˆIð " CÒ'Ü:¸5À.ÐRhÓiÐØ!Ð%5Ð8NÑ%NÑOˆIà˜IÑ&ˆØ�iÑ ˆð ˜Ñ&ˆÜ1°%Ó8ˆä.ØÐ.°°A°~ÀÐ0Wó
ð 
ˆ	ð ˜	Ñ"ˆØ�iÑ ˆØ)¨)Ñ4ˆä˜eÐ%6¸ÈÓXˆä Ó&ˆà�f˜oÐ-Ð-rM   )NN)NNNNNNNN)NNNNNNNNNNNNN)NNNNN)rå   TNr¢   )rå   TN)r¢   )r   ç¥âìÃgØÕ?é    r|   NNr¢   )ç)\�Âõ(ì?çffffffî?r   r|   r¢   )r  r  r   r|   ))Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úmodel_input_namesr   ÚBILINEARré   r   Ústrra   r
   Úfloatr   r   rF   rƒ   r°   r   r[   r	   rg   ÚBICUBICr   r   rr   rx   r‡   r    r   r   r    r©   r§   r¨   rÇ   r×   rà   rÞ   rß   Ú__classcell__)rK   s   @rL   r+   r+   C   sÐ  ø„ ñ.ð` (Ð(Ðð Ø#Ø$(Ø'9×'BÑ'BØØ,3Ø!Ø:>Ø9=ØØ"&Ø'+Ø#ñ.-àð.-ð �3˜�8‰nð.-ð ˜˜S˜‘>ð	.-ð
 %ð.-ð ð.-ð ˜c 5˜jÑ)ð.-ð ð.-ð ˜U 5¨$¨u©+Ð#5Ñ6Ñ7ð.-ð ˜E %¨¨e©Ð"4Ñ5Ñ6ð.-ð ð.-ð ˜3‘-ð.-ð   ‘}ð.-ð ð.-ð  
õ!.-ðh ?CØDHñ#à�z‰zð#ð �s˜C�x‘.ð#ð ˜e CÐ)9Ð$9Ñ:Ñ;ð	#ð
 $ E¨#Ð/?Ð*?Ñ$@ÑAð#ð 
�‰ó#ðJ	¨u°S¸#°X©ð 	Ècó 	ð (:×'AÑ'AØ>BØDHñ/
à�z‰zð/
ð �3˜�8‰nð/
ð %ð	/
ð
 ˜e CÐ)9Ð$9Ñ:Ñ;ð/
ð $ E¨#Ð/?Ð*?Ñ$@ÑAð/
ð 
�‰ó/
ðn *.Ø'+Ø*.Ø:>Ø9=Ø!%Ø-1ØDHñ*àð*ð ð*ð ð	*ð
 ð*ð �t˜C ˜H‘~Ñ&ð*ð %ð*ð ! ™ð*ð ˜U 5¨$¨u©+Ð#5Ñ6Ñ7ð*ð ˜E %¨¨e©Ð"4Ñ5Ñ6ð*ð ˜‘ð*ð ˜4  S ™>Ñ*ð*ð $ E¨#Ð/?Ð*?Ñ$@ÑAó*ðB %)Ø#Ø'+Ø%)Ø*.Ø'+Ø:>Ø9=Ø!%Ø-1Ø)-Ø>BØDHñ59àð59ð ˜D‘>ð59ð �3˜�8‰nð	59ð
 %ð59ð ˜T‘Nð59ð ! ™ð59ð ˜t‘nð59ð ˜U 5¨$¨u©+Ð#5Ñ6Ñ7ð59ð ˜E %¨¨e©Ð"4Ñ5Ñ6ð59ð ˜‘ð59ð ˜4  S ™>Ñ*ð59ð ! ™ð59ð ˜e CÐ)9Ð$9Ñ:Ñ;ð59ð $ E¨#Ð/?Ð*?Ñ$@ÑAð59ð  
ˆr�z‰z˜5  c ™?¨E°#°s°(©OÐ;Ñ	<ó!59ðt %)Ø$(Ø!%Ø26ØDHñ(/à$ð(/ð ˜D‘>ð(/ð ˜˜S˜‘>ð	(/ð
 ˜‘ð(/ð    S¨# X¡Ñ/ð(/ð $ E¨#Ð/?Ð*?Ñ$@ÑAð(/ð 
�‰ó(/ñT %Ó&ð 37Ø$(Ø)-Ø.2Ø37Ø%)Ø6:Ø'+Ø:>Ø9=Ø!%Ø-1Ø26Ø)-Ø;?Ø(8×(>Ñ(>ØDHñ'uCàðuCð $ JÑ/ðuCð ˜D‘>ð	uCð
 �t˜C ˜H‘~Ñ&ðuCð ˜D  c ™NÑ+ðuCð Ð/Ñ0ðuCð ˜T‘NðuCð !  s¨E zÑ!2Ñ3ðuCð ˜t‘nðuCð ˜U 5¨$¨u©+Ð#5Ñ6Ñ7ðuCð ˜E %¨¨e©Ð"4Ñ5Ñ6ðuCð ˜‘ðuCð ˜4  S ™>Ñ*ðuCð    S¨# X¡Ñ/ðuCð  ! ™ð!uCð" !  s¨J Ñ!7Ñ8ð#uCð$ &ð%uCð& $ E¨#Ð/?Ð*?Ñ$@ÑAò'uCó 'ðuCðx ØØØó5Kðp hló-ð` hló(ðV RVó^ð6 Ø)Ø)+Ø>?Ø+/ØDHØ"ñ?Ið ð	?Ið
 ð?Ið " #™ð?Ið )1°°c±Ñ(;ð?Ið ˜Ñ(ð?Ið $ E¨#Ð/?Ð*?Ñ$@ÑAð?Ið ó?IðN Ø#ØØ Øó;ðF Ø#ØØ óN.ðl Ø#ØØ ÷K.rM   r+   r£   útorch.Tensorr¤   rÝ   c                 ó(  — | ||z   kD  j                  dt        j                  ¬«      j                  dt        j                  ¬«      }| ||z
  kD  j                  dt        j                  ¬«      j                  dt        j                  ¬«      }||z  }|S )Néÿÿÿÿrø   )Úsumr«   Úint16Úint32©r£   r¤   rÝ   ÚintersectionsÚunionsrô   s         rL   rê   rê     s’   € ð 
�.Ð#9Ñ9Ñ	:×?Ñ?ÀÌ%Ï+É+Ð?ÓV×ZÑZÐ[]Ôej×epÑepÐZÓqð ð �~Ð(>Ñ>Ñ?×DÑDÀRÌuÏ{É{ÐDÓ[×_Ñ_Ð`bÔjo×juÑjuÐ_Óv€FØ$ vÑ-ÐØÐrM   ú	tf.Tensorc                 óÈ   — t        j                  | ||z   kD  ddgt         j                  ¬«      }t        j                  | ||z
  kD  ddgt         j                  ¬«      }||z  }|S )Nr  éþÿÿÿ)Úaxisrä   )r¦   Úcount_nonzeroÚfloat32r  s         rL   rú   rú     sq   € ô ×$Ñ$Ø�Ð"8Ñ8Ñ9ÀÀRÀÔPR×PZÑPZô€Mô ×Ñ˜e ~Ð8NÑ'NÑOÐWYÐ[]ÐV^Ôfh×fpÑfpÔq€FØ$ vÑ-ÐØÐrM   Ú
n_per_sider:   c                 ó  — dd| z  z  }t        j                  |d|z
  | «      }t        j                  |ddd…f   | df«      }t        j                  |dd…df   d| f«      }t        j                  ||gd¬«      j	                  dd«      }|S )z;Generates a 2D grid of points evenly spaced in [0,1]x[0,1].r|   r{   Nr  ©r  )rƒ   ÚlinspaceÚtileÚstackrù   )r  ÚoffsetÚpoints_one_sideÚpoints_xÚpoints_yÚpointss         rL   Ú_build_point_gridr'    s‡   € à�!�j‘.Ñ!€FÜ—k‘k &¨!¨f©*°jÓA€OÜ�w‰w� tªQ wÑ/°*¸a°ÓA€HÜ�w‰w�¢q¨$ wÑ/°!°Z°ÓA€HÜ�X‰X�x Ð*°Ô4×<Ñ<¸RÀÓC€FØ€MrM   rÓ   Úcoordsrw   c                 óF  — |\  }}| dz  t        ||«      z  }||z  ||z  }}t        |dz   «      }t        |dz   «      }t        |«      j                  t        «      }|r|j                  ddd«      }|d   ||z  z  |d<   |d   ||z  z  |d<   |r|j                  dd«      }|S )zƒ
    Expects a numpy array of length 2 in the final dimension. Requires the original image size in (height, width)
    format.
    r^   r_   r  r{   ).r   ).r|   é   )r`   ra   r   r‚   r
  rù   )	rÓ   r(  rw   Úis_bounding_boxÚ
old_heightÚ	old_widthrd   Ú
new_heightÚ	new_widths	            rL   Ú_normalize_coordinatesr0  !  sÄ   € ð *Ñ€J�	à˜#Ñ¤ J°	Ó :Ñ:€EØ&¨Ñ.°	¸EÑ0A�	€JÜ�I ‘OÓ$€IÜ�Z #Ñ%Ó&€Jä�fÓ×$Ñ$¤UÓ+€FáØ—‘  A qÓ)ˆà˜F‘^ y°9Ñ'<Ñ=€Fˆ6�NØ˜F‘^ z°JÑ'>Ñ?€Fˆ6�NáØ—‘  AÓ&ˆà€MrM   rÈ   rÉ   rÊ   rË   rP   c           	      ó`  — t        | t        «      rt        d«      ‚t        | «      } t	        | |«      }g }t        |dz   «      D ]-  }	t        |||	z  z  «      }
|j                  t        |
«      «       Œ/ t        |||«      \  }}t        || |||||«      \  }}t        j                  |«      }|j                  t        j                  «      }t        j                  |g«      }t        j                  |d¬«      }t        j                   |dd…dd…dd…df   t        j"                  ¬«      }||||fS )a¾  
    Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

    Args:
        image (Union[`numpy.ndarray`, `PIL.Image`, `torch.Tensor`]):
            Image to generate crops for.
        target_size (`int`):
            Size of the smallest crop.
        crop_n_layers (`int`, *optional*):
            If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of layers
            to run, where each layer has 2**i_layer number of image crops.
        overlap_ratio (`int`, *optional*):
            Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the
            image length. Later layers with more crops scale down this overlap.
        points_per_crop (`int`, *optional*):
            Number of points to sample per crop.
        crop_n_points_downscale_factor (`int`, *optional*):
            The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
        input_data_format (`str` or `ChannelDimension`, *optional*):
            The channel dimension format of the input image. If not provided, it will be inferred.
    z.Only one image is allowed for crop generation.r|   )r   r{   r|   r   )ÚaxesNr   rø   )rG   Úlistri   r   r   Úrangera   r¶   r'  Ú_generate_per_layer_cropsÚ_generate_crop_imagesrƒ   Úarrayr‚   r  r¿   Ú	ones_liker„   )rN   rÓ   rÈ   rÉ   rÊ   rË   rP   rw   Úpoints_gridr¹   Ún_pointsrÔ   Ú
layer_idxsrÕ   Úpoint_grid_per_croprÖ   s                   rL   rÐ   rÐ   =  s$  € ô> �%œÔÜÐIÓJÐJÜ˜5Ó!€EÜ" 5Ð*;Ó<€Mà€KÜ�= 1Ñ$Ó%ò 8ˆÜ�Ð*HÈ!Ñ*KÑLÓMˆØ×ÑÔ,¨XÓ6Õ7ð8ô 7°}ÀmÐUbÓcÑ€J�
ä*?Ø�E˜;¨
°KÀÐPaó+Ñ'€NÐ'ô —‘˜*Ó%€JØ×"Ñ"¤2§:¡:Ó.€JÜ—h‘hÐ 3Ð4Ó5€OÜ—l‘l ?¸ÔF€Oä—<‘< ²²1²a¸°
Ñ ;Ä2Ç8Á8ÔL€Là�¨¸ÐDÐDrM   c           	      óæ  — g g }}|\  }}t        ||«      }|j                  dd||g«       |j                  d«       t        | «      D �]  }d|dz   z  }	t        ||z  d|	z  z  «      }
t        t	        j
                  |
|	dz
  z  |z   |	z  «      «      }t        t	        j
                  |
|	dz
  z  |z   |	z  «      «      }t        |	«      D �cg c]  }t        ||
z
  |z  «      ‘Œ }}t        |	«      D �cg c]  }t        ||
z
  |z  «      ‘Œ }}t        ||«      D ]J  \  }}||t        ||z   |«      t        ||z   |«      g}|j                  |«       |j                  |dz   «       ŒL �Œ ||fS c c}w c c}w )aq  
    Generates 2 ** (layers idx + 1) crops for each crop_n_layers. Crops are in the XYWH format : The XYWH format
    consists of the following required indices:
        - X: X coordinate of the top left of the bounding box
        - Y: Y coordinate of the top left of the bounding box
        - W: width of the bounding box
        - H: height of the bounding box
    r   r{   r|   )Úminr¶   r4  ra   ÚmathÚceilr   )rÈ   rÉ   rw   rÔ   r;  Ú	im_heightÚim_widthÚ
short_sideÚi_layerÚn_crops_per_sideÚoverlapÚ
crop_widthÚcrop_heightr¹   Úcrop_box_x0Úcrop_box_y0ÚleftÚtopÚboxs                      rL   r5  r5  u  s   € ð   �
€JØ'Ñ€IˆxÜ�Y Ó)€Jð ×Ñ�q˜!˜X yÐ1Ô2Ø×Ñ�aÔÜ˜Ó'ó +ˆØ ¨1¡Ñ-ÐÜ�m jÑ0°AÐ8HÑ4HÑIÓJˆäœŸ™ GÐ/?À!Ñ/CÑ$DÀxÑ$OÐScÑ#cÓdÓeˆ
Üœ$Ÿ)™) WÐ0@À1Ñ0DÑ%EÈ	Ñ%QÐUeÑ$eÓfÓgˆä@EÐFVÓ@WÖX¸1”s˜J¨Ñ0°AÑ5Õ6ÐXˆÐXÜAFÐGWÓAXÖY¸A”s˜K¨'Ñ1°QÑ6Õ7ÐYˆÐYä  ¨kÓ:ò 	+‰IˆD�#Ø˜œc $¨Ñ"3°XÓ>ÄÀCÈ+ÑDUÐW`Ó@aÐbˆCØ×Ñ˜cÔ"Ø×Ñ˜g¨™kÕ*ò	+ð+ð �zÐ!Ð!ùò YùÚYs   ÃE)Ã/E.c                 ó„  — g }g }t        | «      D ]«  \  }	}
|
\  }}}}t        ||«      }|t        j                  k(  r|||…||…dd…f   }n|dd…||…||…f   }|j	                  |«       t        ||«      }t        j                  |«      dddd…f   }|||	      |z  }t        |||«      }|j	                  |«       Œ­ ||fS )z�
    Takes as an input bounding boxes that are used to crop the image. Based in the crops, the corresponding points are
    also passed.
    Nr  )	r²   r   r   ÚLASTr¶   r   rƒ   r7  r0  )rÔ   rN   r9  r;  rÓ   rw   rP   rÕ   Útotal_points_per_cropr¹   Úcrop_boxrK  rL  ÚrightÚbottomrS   Ú
cropped_imÚcropped_im_sizeÚpoints_scaler&  Únormalized_pointss                        rL   r6  r6  —  s÷   € ð €NØÐÜ  Ó,ò 8‰ˆˆ8Ø#+Ñ ˆˆc�5˜&ä4°UÐ<MÓNˆØÔ*×/Ñ/Ò/Ø˜s 6˜z¨4°¨:²qÐ8Ñ9‰Jàšq # f *¨d°5¨jÐ8Ñ9ˆJà×Ñ˜jÔ)ä(¨°[ÓAˆÜ—x‘x Ó0°±t¸°t°Ñ<ˆà˜Z¨™]Ñ+¨lÑ:ˆÜ2°;ÀÈÓVÐØ×$Ñ$Ð%6Õ7ð!8ð$ Ð0Ð0Ð0rM   rQ  Úorig_heightÚ
orig_widthc                 óÌ   — |\  }}}}|dk(  r|dk(  r||k(  r||k(  r| S |||z
  z
  |||z
  z
  }	}|||z
  ||	|z
  f}
t         j                  j                  j                  | |
d¬«      S )Nr   )Úvalue)r«   ÚnnÚ
functionalr   ©r£   rQ  rX  rY  rK  rL  rR  rS  Úpad_xÚpad_yr   s              rL   rí   rí   µ  sƒ   € Ø'Ñ€Dˆ#ˆu�fØˆq‚y�S˜A’X %¨:Ò"5¸&ÀKÒ:OØˆà ¨¡Ñ.°¸vÈ¹|Ñ0Lˆ5€EØ�˜‘˜s E¨C¡KÐ
0€CÜ�8‰8×Ñ×"Ñ" 5¨#°QÐ"Ó7Ð7rM   c                 ó¤   — |\  }}}}|dk(  r|dk(  r||k(  r||k(  r| S |||z
  z
  |||z
  z
  }	}|||z
  ||	|z
  f}
t        j                  | |
d¬«      S )Nr   )Úconstant_values)r¦   r   r^  s              rL   rý   rý   ¿  st   € Ø'Ñ€Dˆ#ˆu�fØˆq‚y�S˜A’X %¨:Ò"5¸&ÀKÒ:OØˆà ¨¡Ñ.°¸vÈ¹|Ñ0Lˆ5€EØ�˜‘˜s E¨C¡KÐ
0€CÜ�6‰6�%˜¨aÔ0Ð0rM   c                 óp  — t        j                  |t         j                  | j                  ¬«      }t        j                  |t         j                  | j                  ¬«      }|\  }}}}t        j                  ||||gg| j                  ¬«      }	t        | j                  «      dk(  r|	j                  d«      }	| |	z   j                  «       } t        j                  | |ddd…f   |d¬«      }
t        j                  | |ddd…f   |d¬«      }t        j                  |
| «      }
t        j                  |
d¬«      S )	úNFilter masks at the edge of a crop, but not at the edge of the original image.rã   rÏ   r   r|   Nr   ©ÚatolÚrtol©Údim)r«   Ú	as_tensorr
  rÌ   rÑ   Úlenræ   Ú	unsqueezeÚiscloseÚlogical_andÚany)ÚboxesrQ  Úorig_boxrf  Úcrop_box_torchÚorig_box_torchrK  rL  r†   r"  Únear_crop_edgeÚnear_image_edges               rL   rì   rì   É  sø   € ä—_‘_ X´U·[±[ÈÏÉÔV€NÜ—_‘_ X´U·[±[ÈÏÉÔV€Nà�O€Dˆ#ˆq�!Ü�\‰\˜D # t¨SÐ1Ð2¸5¿<¹<ÔH€Fä
ˆ5�;‰;Ó˜1ÒØ×!Ñ! !Ó$ˆØ�V‰^×"Ñ"Ó$€Eä—]‘] 5¨.¸ºq¸Ñ*AÈÐSTÔU€NÜ—m‘m E¨>¸$Â¸'Ñ+BÈÐTUÔV€OÜ×&Ñ& ~¸Ð7GÓH€NÜ�9‰9�^¨Ô+Ð+rM   c                 ór  — t        j                  |t         j                  ¬«      }t        j                  |t         j                  ¬«      }|\  }}}}t        j                  ||||gg«      }	t        | j                  «      dk(  rt        j
                  |	d«      }	t        j                  | |	z   t         j                  «      } t        j                  | |ddd…f   |d¬«      }
t        j                  | |ddd…f   |d¬«      }t         j                  j                  |
| «      }
t        j                  |
d¬«      S )rd  rø   r   r|   Nr   re  r  )r¦   rÒ   r  rk  ræ   Úexpand_dimsÚcastÚtnprm  r?  rn  Ú
reduce_any)rp  rQ  rq  rf  Úcrop_box_tfÚorig_box_tfrK  rL  r†   r"  rt  ru  s               rL   rü   rü   Û  sô   € ä×&Ñ& x´r·z±zÔB€KÜ×&Ñ& x´r·z±zÔB€Kà�O€Dˆ#ˆq�!Ü×!Ñ! D¨#¨t°SÐ#9Ð":Ó;€Fä
ˆ5�;‰;Ó˜1ÒÜ—‘ ¨Ó*ˆÜ�G‰G�E˜F‘N¤B§J¡JÓ/€Eä—[‘[ ¨°Dº!°GÑ(<À4ÈaÔP€NÜ—k‘k %¨°Tº1°WÑ)=ÀDÈqÔQ€OÜ—W‘W×(Ñ(¨¸/Ð9IÓJ€NÜ�=‰=˜¨aÔ0Ð0rM   c                 ól  — t        j                  | «      dk(  r1t        j                  g | j                  dd ¢d‘­d| j                  iŽS | j                  }|dd \  }}t        j
                  | d¬«      \  }}|t        j                  ||j                  ¬«      ddd…f   z  }t        j
                  |d¬«      \  }}||| z  z   }t        j                  |d¬«      \  }}t        j
                  | d¬«      \  }	}|	t        j                  ||	j                  ¬«      ddd…f   z  }
t        j
                  |
d¬«      \  }}|
||	 z  z   }
t        j                  |
d¬«      \  }}||k  ||k  z  }t        j                  ||||gd¬«      }|| j                  d«      z  } |j                  g |dd ¢d‘­Ž }|S )	aL  
    Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which
    corresponds the following required indices:
        - LEFT: left hand side of the bounding box
        - TOP: top of the bounding box
        - RIGHT: right of the bounding box
        - BOTTOM: bottom of the bounding box

    Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape
    is channel_1 x channel_2 x ... x 4.

    Args:
        - masks (`torch.Tensor` of shape `(batch, nb_mask, height, width)`)
    r   Nr  r*  rÌ   r  rh  rÏ   )r«   ÚnumelÚzerosræ   rÌ   r`   Úaranger>  r!  rl  rù   )r£   ræ   r@   rA   Ú	in_heightr†   Úin_height_coordsÚbottom_edgesÚ	top_edgesÚin_widthÚin_width_coordsÚright_edgesÚ
left_edgesÚempty_filterÚouts                  rL   rë   rë   í  s±  € ô" ‡{�{�5Ó˜QÒÜ�{‰{ÐE˜EŸK™K¨¨Ð,ÐE¨aÒE¸¿¹ÑEÐEð �K‰K€EØ˜"˜#�J�M€FˆEô —9‘9˜U¨Ô+�L€IˆqØ ¤5§<¡<°¸y×?OÑ?OÔ#PÐQUÒWXÐQXÑ#YÑYÐÜ—i‘iÐ 0°bÔ9�O€L�!Ø'¨&°Y°JÑ*?Ñ?ÐÜ—9‘9Ð-°2Ô6�L€Iˆqô —)‘)˜E rÔ*�K€HˆaØ¤§¡¨e¸H¿O¹OÔ!LÈTÒSTÈWÑ!UÑU€OÜ—Y‘Y˜°BÔ7�N€K�Ø%¨°(°Ñ(;Ñ;€OÜ—I‘I˜o°2Ô6�M€J�ð   *Ñ,°À	Ñ1IÑJ€LÜ
�+‰+�z 9¨k¸<ÐHÈbÔ
Q€CØ
�,�×)Ñ)¨"Ó-Ñ
-€Cð ˆ#�+‰+Ð
%�u˜S˜b�zÐ
% 1Ò
%€CØ€JrM   c                 ó$  — t        j                  | «      dk(  r&t        j                  g | j                  dd ¢d‘«      S t	        | «      }|dd \  }}t        j
                  | d¬«      }|t        j                  |«      ddd…f   z  }t        j
                  |d¬«      }||| z  z   }t        j                  |d¬«      }t        j
                  | d¬«      \  }}	|t        j                  |«      ddd…f   z  }
t        j
                  |
d¬«      \  }}	|
|| z  z   }
t        j                  |
d¬«      \  }}	||k  ||k  z  }t        j                  ||||gd¬«      }|t        j                  | d«      z  }t        j                  |g|dd ¢d‘­Ž }|S )aI  
    Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which
    corresponds the following required indices:
        - LEFT: left hand side of the bounding box
        - TOP: top of the bounding box
        - RIGHT: right of the bounding box
        - BOTTOM: bottom of the bounding box

    Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape
    is channel_1 x channel_2 x ... x 4.

    Args:
        - masks (`tf.Tensor` of shape `(batch, nb_mask, height, width)`)
    r   Nr  r*  r  r  )r¦   r.   r  ræ   r)   Ú
reduce_maxr4  Ú
reduce_minr!  rw  rù   )r£   ræ   r@   rA   r�  r‚  rƒ  r„  r…  r†   r†  r‡  rˆ  r‰  rŠ  s                  rL   rû   rû     sŒ  € ô  
‡w�wˆuƒ~˜ÒÜ�x‰xÐ.˜%Ÿ+™+ c rÐ*Ð.¨AÐ.Ó/Ð/ô �uÓ€EØ˜"˜#�J�M€FˆEô —‘˜e¨"Ô-€IØ ¤2§8¡8¨FÓ#3°Dº!°GÑ#<Ñ<ÐÜ—=‘=Ð!1¸Ô;€LØ'¨&°Y°JÑ*?Ñ?ÐÜ—‘Ð.°RÔ8€Iô —-‘- ¨BÔ/�K€HˆaØ¤§¡¨%£°²q°Ñ!9Ñ9€OÜ—]‘] ?¸Ô<�N€K�Ø%¨°(°Ñ(;Ñ;€OÜ—M‘M /¸Ô;�M€J�ð   *Ñ,°À	Ñ1IÑJ€LÜ
�(‰(�J 	¨;¸ÐEÈBÔ
O€CØ
”—‘ ˜}¨bÓ1Ñ
1€Cô �*‰*�SÐ
)˜5  "˜:Ð
) qÒ
)€CØ€JrM   c                 óˆ  — | j                   \  }}}| j                  ddd«      j                  d«      } | dd…dd…f   | dd…dd…f   z  }|j                  «       }g }t	        |«      D ]Ø  }||dd…df   |k(  df   dz   }t        |«      dk(  rA| |df   dk(  r|j                  ||g||z  gdœ«       n|j                  ||gd||z  gdœ«       Œf|dd |dd z
  }	| |df   dk(  rg ndg}
|
|d   j                  «       g|	j                  «       z   ||z  |d   j                  «       z
  gz   z  }
|j                  ||g|
dœ«       ŒÚ |S )ú^
    Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools.
    r   r{   r|   Nr  ©r.   Úcounts)	ræ   Úpermuter(   Únonzeror4  rk  r¶   Úitemr±   ©Ú
input_maskrò   r@   rA   ÚdiffÚchange_indicesrŠ  r¹   Úcur_idxsÚbtw_idxsr‘  s              rL   rî   rî   N  s�  € ð
 !+× 0Ñ 0Ñ€J�˜Ø×#Ñ# A q¨!Ó,×4Ñ4°QÓ7€Jð ’a˜™�eÑ˜zª!¨S¨b¨S¨&Ñ1Ñ1€DØ—\‘\“^€Nð €CÜ�:Óò @ˆØ! .²°A°Ñ"6¸!Ñ";¸QÐ">Ñ?À!ÑCˆÜˆx‹=˜AÒð ˜!˜Q˜$Ñ 1Ò$Ø—
‘
 V¨U OÀÈÁÐ?OÑPÕQà—
‘
 V¨U OÀÀ6ÈEÁ>Ð?RÑSÔTØØ˜A˜B�< (¨3¨B -Ñ/ˆØ! ! Q $Ñ'¨1Ò,‘°1°#ˆØ�8˜A‘;×#Ñ#Ó%Ð&¨¯©Ó):Ñ:¸fÀu¹nÈxÐXZÉ|×O`ÑO`ÓObÑ>bÐ=cÑcÑcˆØ�
‰
˜V U˜O°vÑ>Õ?ð@ð €JrM   c                 óò  — | j                   \  }}}t        t        j                  | d¬«      d«      } | dd…dd…f   | dd…dd…f   z  }t        j                  |«      }g }t        |«      D �]  }||dd…df   |k(     dd…df   dz   }t        |«      dk(  rA| |df   dk(  r|j                  ||g||z  gdœ«       n|j                  ||gd||z  gdœ«       Œl|dd |dd z
  }	| |df   dk(  rg ndg}
|
|d   j                  «       j                  «       g|	j                  «       j                  «       z   ||z  |d   j                  «       j                  «       z
  gz   z  }
|j                  ||g|
dœ«       �Œ |S )r�  )r   r{   r|   r¼   r|   Nr  r   r�  )ræ   r(   r¦   r¿   Úwherer4  rk  r¶   r'   r”  r±   r•  s              rL   rþ   rþ   m  s°  € ð
 !+× 0Ñ 0Ñ€J�˜ÜœŸ™ j°yÔAÀ1ÓE€Jð ’a˜™�eÑ˜zª!¨S¨b¨S¨&Ñ1Ñ1€DÜ—X‘X˜d“^€Nð €CÜ�:Óó @ˆØ! .²°A°Ñ"6¸!Ñ";Ñ<ºQÀ¸TÑBÀQÑFˆÜˆx‹=˜AÒð ˜!˜Q˜$Ñ 1Ò$Ø—
‘
 V¨U OÀÈÁÐ?OÑPÕQà—
‘
 V¨U OÀÀ6ÈEÁ>Ð?RÑSÔTØØ˜A˜B�< (¨3¨B -Ñ/ˆØ! ! Q $Ñ'¨1Ò,‘°1°#ˆØØ�a‰[×ÑÓ ×%Ñ%Ó'Ð(¨8¯>©>Ó+;×+BÑ+BÓ+DÑDÈÐQVÉÐYaÐbdÑYe×YkÑYkÓYm×YrÑYrÓYtÑHtÐGuÑuñ	
ˆð 	�
‰
˜V U˜O°vÑ>Ö?ð@ð  €JrM   Úrlec                 óÎ   — | d   \  }}t        j                  ||z  t        ¬«      }d}d}| d   D ]  }|||||z    ||z  }| }Œ |j                  ||«      }|j	                  «       S )z/Compute a binary mask from an uncompressed RLE.r.   rø   r   Fr‘  )rƒ   Úemptyré   rù   r¿   )r�  r@   rA   r•   ÚidxÚparityÚcounts          rL   Ú_rle_to_maskr£  Ž  s   € à˜‘K�M€FˆEÜ�8‰8�F˜U‘N¬$Ô/€DØ
€CØ€FØ�X‘ò ˆØ"(ˆˆS�3˜‘;ÐØˆu‰ˆØ�‰ðð �<‰<˜˜vÓ&€DØ�>‰>ÓÐrM   c                 ó  — t        |j                  «       |t        j                  |j                  d   «      |¬«      }||   }|D �cg c]  }| |   ‘Œ	 } }||   }| D �cg c]  }t        |«      ‘Œ }}||| |fS c c}w c c}w )aë  
    Perform NMS (Non Maximum Suppression) on the outputs.

    Args:
            rle_masks (`torch.Tensor`):
                binary masks in the RLE format
            iou_scores (`torch.Tensor` of shape (nb_masks, 1)):
                iou_scores predicted by the model
            mask_boxes (`torch.Tensor`):
                The bounding boxes corresponding to segmentation masks
            amg_crops_nms_thresh (`float`, *optional*, defaults to 0.7):
                NMS threshold.
    r   ©rp  rõ   ÚidxsÚiou_threshold)r&   r
  r«   r  ræ   r£  ©Ú	rle_masksrÙ   Ú
mask_boxesÚamg_crops_nms_threshÚkeep_by_nmsr¹   r�  r£   s           rL   rÁ   rÁ   œ  s“   € ô Ø×ÑÓ ØÜ�[‰[˜×)Ñ)¨!Ñ,Ó-Ø*ô	€Kð ˜KÑ(€JØ'2Ö3 !�˜1“Ð3€IÐ3Ø˜KÑ(€JØ*3Ö4 3Œ\˜#ÕÐ4€EÐ4à�*˜i¨Ð3Ð3ùò	 4ùâ4s   ÁA8ÁA=c                 ó,  — t         j                  j                  |j                  «       |t	        j
                  |j                  d   «      |¬«      }||   }|D �cg c]  }| |   ‘Œ	 } }||   }| D �cg c]  }t        |«      ‘Œ }}||| |fS c c}w c c}w )aâ  
    Perform NMS (Non Maximum Suppression) on the outputs.

    Args:
            rle_masks (`tf.Tensor`):
                binary masks in the RLE format
            iou_scores (`tf.Tensor` of shape (nb_masks, 1)):
                iou_scores predicted by the model
            mask_boxes (`tf.Tensor`):
                The bounding boxes corresponding to segmentation masks
            amg_crops_nms_thresh (`float`, *optional*, defaults to 0.7):
                NMS threshold.
    r   r¥  )r¦   rN   Úcombined_non_max_suppressionr
  r«   r  ræ   r£  r¨  s           rL   rÂ   rÂ   ¹  s¢   € ô —(‘(×7Ñ7Ø×ÑÓ ØÜ�[‰[˜×)Ñ)¨!Ñ,Ó-Ø*ð	 8ó €Kð ˜KÑ(€JØ'2Ö3 !�˜1“Ð3€IÐ3Ø˜KÑ(€JØ*3Ö4 3Œ\˜#ÕÐ4€EÐ4à�*˜i¨Ð3Ð3ùò	 4ùâ4s   ÁBÁ2B)F)r   rÿ   r   r|   Nr—   )g      4@)r£   r  )r£   r  )r–  r  )r–  r  )gffffffæ?)Vr  r?  Úcopyr   Ú	itertoolsr   Útypingr   r   r   r   r	   r
   r'   rƒ   Úimage_processing_utilsr   r   r   Úimage_transformsr   r   r   r   Úimage_utilsr   r   r   r   r   r   r   r   r   r   r   r   Úutilsr   r    r!   r"   r#   r$   r%   r«   Útorch.nn.functionalr\  r]  r´   Útorchvision.ops.boxesr&   Ú
tensorflowr¦   Útensorflow.experimentalry  Útf_utilsr(   r)   Ú
get_loggerr  ru   r+   r
  ra   rê   rú   r°   r'  r0  r	  rÐ   r5  r6  rí   rý   rì   rü   rë   rû   rî   rþ   r£  rÁ   rÂ   Ú__all__rD   rM   rL   ú<module>r½     sW  ðñ %ã Ý Ý ß :× :ã ç UÑ Uß XÓ X÷÷ ÷ ó ÷÷ ñ ñ ÔÛß#Ð#áÔÝ1áÔÛÝ4ç/à	ˆ×	Ñ	˜HÓ	%€ô{.Ð*ô {.ð| ~ð Àuð Ðfió ð {ð ÀEð Ðcfó ð #ð ¨"¯*©*ó ð [`ñØðØ Ÿj™jðØ9>¸sÀC¸x¹ðà‡Z�Zóð> Ø%Ø%'Ø:;Ø@Dñ5Eàð5Eð ð5Eð ð	5Eð
 ˜c‘]ð5Eð %-¨T°#©YÑ$7ð5Eð    cÐ+;Ð&;Ñ <Ñ=ð5Eð ˆ4��S‘	‰?˜D ™IÐ%Ñ&ó5Eòp"ðF _có1ð<8  S¡	ð 8¸ð 8Èó 8ð1 4¨¡9ð 1¸3ð 1ÈCó 1ó,ó$1ó$.ób-ó`ó>ðB�d˜3 ˜8‘nð ¨¯©ó ó4ó:4ð: Ð
�rM   