ó
    qyüiLo  ã                   ó�  • S SK r S SKJr  S SKJr  S SKJrJrJr  S SK	r
S SKrS SKJs  Jr  S SKJr  SSKJr  SSKJrJr  SS	KJrJrJrJrJrJr  SS
KJrJ r   SSK!J"r"J#r#J$r$  \$" 5       (       a  S SK%r% " S S\SS9r&SSS\'S\(4S jr)S/S jr*S0S jr+S\,\(   S\(S\(4S jr-    S1S\(S\(S\'S\(S-  S\,\(   S-  S \.\,\,\(      \,\(   4   4S! jjr/S" r0S#\(S \Rb                  4S$ jr2 S2S% jr3 S3S\(S&\Rb                  S'\.\(\(4   S \Rb                  4S( jjr4S)\5\6\4   S \Rb                  4S* jr7S4S+ jr8S5S, jr9\# " S- S.\5      5       r:S./r;g)6é    N)Údeepcopy)Úproduct)ÚAnyÚOptionalÚUnion)Úbatched_nmsé   )ÚTorchvisionBackend)ÚBatchFeatureÚget_size_dict)ÚIMAGENET_DEFAULT_MEANÚIMAGENET_DEFAULT_STDÚChannelDimensionÚ
ImageInputÚPILImageResamplingÚSizeDict)ÚImagesKwargsÚUnpack)Ú
TensorTypeÚauto_docstringÚis_vision_availablec                   ó.   • \ rS rSr% Sr\\\4   \S'   Sr	g)ÚSam2ImageProcessorKwargsé0   z|
mask_size (`dict[str, int]`, *optional*):
    The size `{"height": int, "width": int}` to resize the segmentation maps to.
Ú	mask_size© N)
Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__ÚdictÚstrÚintÚ__annotations__Ú__static_attributes__r   ó    Úk/home/mande/repo/quber/.venv/lib/python3.13/site-packages/transformers/models/sam2/image_processing_sam2.pyr   r   0   s   ‡ ñð
 �C˜�H‰~Ör'   r   F)ÚtotalÚmasksútorch.TensorÚmask_thresholdÚstability_score_offsetc                 ó
  • XU-   :„  R                  S[        R                  S9R                  S[        R                  S9nXU-
  :„  R                  S[        R                  S9R                  S[        R                  S9nX4-  nU$ )Néÿÿÿÿ©Údtype)ÚsumÚtorchÚint16Úint32)r*   r,   r-   ÚintersectionsÚunionsÚstability_scoress         r(   Ú_compute_stability_scorer9   9   sŒ   € ð 
Ð#9Ñ9Ñ	:×?Ñ?ÀÌ%Ï+É+Ð?ÐV×ZÑZÐ[]Ôej×epÑepÐZÐqð ð Ð(>Ñ>Ñ?×DÑDÀRÌuÏ{É{ÐDÐ[×_Ñ_Ð`bÔjo×juÑjuÐ_Ðv€FØ$Ñ-ÐØÐr'   c                 ó.  • [         R                  " U 5      S:X  a2  [         R                  " / U R                  SS QSP7SU R                  06$ U R                  nUSS u  p#[         R
                  " U SS9u  pEU[         R                  " X$R                  S9SSS24   -  n[         R
                  " USS9u  puXbU) -  -   n[         R                  " USS9u  p…[         R
                  " U SS9u  p•U	[         R                  " X9R                  S9SSS24   -  n
[         R
                  " U
SS9u  pµX£U	) -  -   n
[         R                  " U
SS9u  pÅX¼:  Xx:  -  n[         R                  " XÈX·/SS9nXí) R                  S5      -  nUR                  " / USS QSP76 nU$ )	a   
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   Néþÿÿÿé   Údevicer/   ©Údim©r=   )r3   ÚnumelÚzerosÚshaper=   ÚmaxÚarangeÚminÚstackÚ	unsqueezeÚreshape)r*   rC   ÚheightÚwidthÚ	in_heightÚ_Úin_height_coordsÚbottom_edgesÚ	top_edgesÚin_widthÚin_width_coordsÚright_edgesÚ
left_edgesÚempty_filterÚouts                  r(   Ú_batched_mask_to_boxrW   D   s�  € ô" ‡{‚{�5Ó˜QÓÜ�{Š{ÐE˜EŸK™K¨¨Ð,ÐE¨aÒE¸¿¹ÑEÐEð �K‰K€EØ˜"˜#�J�M€Fô —9’9˜U¨Ñ+�L€IØ ¤5§<¢<°×?OÑ?OÑ#PÐQUÒWXÐQXÑ#YÑYÐÜ—i’iÐ 0°bÑ9�O€LØ'°Y°JÑ*?Ñ?ÐÜ—9’9Ð-°2Ñ6�L€Iô —)’)˜E rÑ*�K€HØ¤§¢¨e¿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¨kÐHÈbÑ
Q€CØ
�×)Ñ)¨"Ó-Ñ
-€Cð �+Š+Ð
%�u˜S˜b�zÐ
% 1Ò
%€CØ€Jr'   c                 óN  • [         R                  " U[         R                  U R                  S9n[         R                  " U[         R                  U R                  S9nUu  pg  n[         R                  " XgXg//U R                  S9n	[        U R                  5      S:X  a  U	R                  S5      n	X	-   R                  5       n [         R                  " XSSS24   USS9n
[         R                  " XSSS24   USS9n[         R                  " X«) 5      n
[         R                  " U
SS9$ )	zNFilter masks at the edge of a crop, but not at the edge of the original image.©r1   r=   r@   r	   é   Nr   )ÚatolÚrtolr>   )r3   Ú	as_tensorÚfloatr=   ÚtensorÚlenrC   rH   ÚiscloseÚlogical_andÚany)ÚboxesÚcrop_boxÚorig_boxr[   Úcrop_box_torchÚorig_box_torchÚleftÚtoprM   ÚoffsetÚnear_crop_edgeÚnear_image_edges               r(   Ú_is_box_near_crop_edgern   u   sê   € ä—_’_ X´U·[±[ÈÏÉÑV€NÜ—_’_ X´U·[±[ÈÏÉÑV€Nà�O€Dˆq�!Ü�\Š\˜D tÐ1Ð2¸5¿<¹<ÑH€Fä
ˆ5�;‰;Ó˜1ÓØ×!Ñ! !Ó$ˆØ‰^×"Ñ"Ó$€Eä—]’] 5¸ºq¸Ñ*AÈÐSTÑU€NÜ—m’m E¸$Â¸'Ñ+BÈÐTUÑV€OÜ×&Ò& ~Ð7GÓH€NÜ�9Š9�^¨Ñ+Ð+r'   re   Úorig_heightÚ
orig_widthc                 óº   • Uu  pEpgUS:X  a  US:X  a  Xc:X  a  Xr:X  a  U $ X6U-
  -
  X'U-
  -
  p˜XHU-
  XYU-
  4n
[         R                  R                  R                  X
SS9$ )Nr   )Úvalue)r3   ÚnnÚ
functionalÚpad)r*   re   ro   rp   ri   rj   ÚrightÚbottomÚpad_xÚpad_yru   s              r(   Ú
_pad_masksrz   ‡   so   € Ø'Ñ€DˆuØˆqƒy�S˜A“X %Ó"5¸&Ó:OØˆà¨¡Ñ.°È¹|Ñ0Lˆ5Ø˜‘˜s¨C¡KÐ
0€CÜ�8‰8×Ñ×"Ñ" 5°QÐ"Ð7Ð7r'   Útarget_sizeÚcrop_n_layersÚoverlap_ratioÚpoints_per_cropÚcrop_n_points_downscale_factorÚreturnc                 ón  • [        U [        5      (       a  [        S5      eU R                  SS n/ n[	        US-   5       H-  n[        XEU-  -  5      n	UR                  [        U	5      5        M/     [        X#U5      u  p«[        X X{X5      u  pÍ[        R                  " U
5      n
U
R                  5       n
[        R                  " U5      nUR                  S5      R                  SSSS5      n[        R                  " U5      n[        R                   " USS2SS2SS2S4   [        R"                  S9nX¤XÎ4$ )	a¯  
Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

Args:
    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 sam2ple per crop.
    crop_n_points_downscale_factor (`int`, *optional*):
        The number of points-per-side sam2pled in layer n is scaled down by crop_n_points_downscale_factor**n.
z.Only one image is allowed for crop generation.r;   NrZ   r   é   r	   r0   )Ú
isinstanceÚlistÚ
ValueErrorrC   Úranger$   ÚappendÚ_build_point_gridÚ_generate_per_layer_cropsÚ_generate_crop_imagesr3   r_   r^   rG   rH   ÚpermuteÚ	ones_likeÚint64)Úimager{   r|   r}   r~   r   Úoriginal_sizeÚpoints_gridÚiÚn_pointsÚ
crop_boxesÚ
layer_idxsÚcropped_imagesÚpoint_grid_per_cropÚinput_labelss                  r(   Ú_generate_crop_boxesr˜   ‘   s  € ô8 �%œ×ÑÜÐIÓJÐJØ—K‘K  Ð$€Mà€KÜ�= 1Ñ$Ö%ˆÜ�È!Ñ*KÑLÓMˆØ×ÑÔ,¨XÓ6Ö7ñ &ô 7°}ÐUbÓcÑ€Jä*?Ø˜;°Kó+Ñ'€Nô —’˜jÓ)€JØ×!Ñ!Ó#€JÜ—k’kÐ"5Ó6€OØ%×/Ñ/°Ó2×:Ñ:¸1¸aÀÀAÓF€OÜ—[’[ Ó0€Nä—?’? ?²1²aº¸A°:Ñ#>ÄeÇkÁkÑR€Là¨ÐDÐDr'   c           	      óè  • / / pCUu  pV[        XV5      nUR                  SSXe/5        UR                  S5        [        U 5       GH  nSUS-   -  n	[        X-  SU	-  -  5      n
[        [        R
                  " X©S-
  -  U-   U	-  5      5      n[        [        R
                  " X©S-
  -  U-   U	-  5      5      n[        U	5       Vs/ s H  n[        Xº-
  U-  5      PM     nn[        U	5       Vs/ s H  n[        XÊ-
  U-  5      PM     nn[        Xï5       HK  u  nnUU[        UU-   U5      [        UU-   U5      /nUR                  U5        UR                  US-   5        MM     GM"     X44$ s  snf s  snf )aU  
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‚   rZ   )rF   r‡   r†   r$   ÚmathÚceilr   )r|   r}   r�   r“   r”   Ú	im_heightÚim_widthÚ
short_sideÚi_layerÚn_crops_per_sideÚoverlapÚ
crop_widthÚcrop_heightr‘   Úcrop_box_x0Úcrop_box_y0ri   rj   Úboxs                      r(   r‰   r‰   Æ   s„  € ð   �
Ø'Ñ€IÜ�YÓ)€Jð ×Ñ�q˜!˜XÐ1Ô2Ø×Ñ�aÔÜ˜×'ˆØ ¨1¡Ñ-ÐÜ�mÑ0°AÐ8HÑ4HÑIÓJˆäœŸš GÀ!Ñ/CÑ$DÀxÑ$OÐScÑ#cÓdÓeˆ
Üœ$Ÿ)š) WÀ1Ñ0DÑ%EÈ	Ñ%QÐUeÑ$eÓfÓgˆä@EÐFVÔ@WÓXÒ@W¸1”s˜JÑ0°AÑ5Ö6Ñ@WˆÐXÜAFÐGWÔAXÓYÒAX¸A”s˜KÑ1°QÑ6Ö7ÑAXˆÐYä  Ö:‰IˆD�#Ø˜œc $¨Ñ"3°XÓ>ÄÀCÈ+ÑDUÐW`Ó@aÐbˆCØ×Ñ˜cÔ"Ø×Ñ˜g¨™kÖ*ô ;ñ (ð Ð!Ð!ùò YùÚYs   ÃE*Ã,E/Ú
n_per_sidec                 ó  • SSU -  -  n[         R                  " USU-
  U 5      n[         R                  " USSS24   U S45      n[         R                  " USS2S4   SU 45      n[         R                  " X4/SS9R	                  SS5      nU$ )z;Generates a 2D grid of points evenly spaced in [0,1]x[0,1].rZ   r‚   Nr/   r>   )r3   ÚlinspaceÚtilerG   rI   )r§   rk   Úpoints_one_sideÚpoints_xÚpoints_yÚpointss         r(   rˆ   rˆ   è   s…   € à�!�j‘.Ñ!€FÜ—n’n V¨Q°©Z¸ÓD€OÜ�zŠz˜/¨$²¨'Ñ2°ZÀ°OÓD€HÜ�zŠz˜/ª!¨T¨'Ñ2°Q¸
°OÓD€HÜ�[Š[˜(Ð-°2Ñ6×>Ñ>¸rÀ1ÓE€FØ€Mr'   c                 óN  • / n/ n[        U 5       H�  u  pšU
u  p¼pÞUSS2XÎ2X½24   nUR                  U5        UR                  SS n[        R                  " U5      R                  SS9R                  S5      nX#U	      U-  n[        UUU5      nUR                  U5        M’     Xx4$ )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   )Údimsr   )Ú	enumerater‡   rC   r3   r_   ÚfliprH   Ú_normalize_coordinates)r“   rŽ   r�   r”   r{   r�   Úinput_data_formatr•   Útotal_points_per_cropr‘   re   ri   rj   rv   rw   Ú
cropped_imÚcropped_im_sizeÚpoints_scaler®   Únormalized_pointss                       r(   rŠ   rŠ   ò   sÀ   € ð €NØÐÜ  Ö,‰ˆØ#+Ñ ˆ�5Øš1˜c˜j¨$¨*Ð4Ñ5ˆ
à×Ñ˜jÔ)à$×*Ñ*¨2¨3Ð/ˆÜ—|’| OÓ4×9Ñ9¸tÐ9ÐD×NÑNÈqÓQˆà¨™]Ñ+¨lÑ:ˆÜ2°;ÀÈÓVÐØ×$Ñ$Ð%6Ö7ñ -ð Ð0Ð0r'   Úcoordsr�   c                 óB  • Uu  pEU S-  [        XE5      -  nXF-  XV-  p‡[        US-   5      n[        US-   5      n[        U5      R                  5       nU(       a  UR	                  SSS5      nUS   X…-  -  US'   US   Xt-  -  US'   U(       a  UR	                  SS5      nU$ )zw
Expects a numpy array of length 2 in the final dimension. Requires the original image size in (height, width)
format.
g      ð?g      à?r/   r‚   ).r   ).rZ   r<   )rD   r$   r   r^   rI   )	r{   rº   r�   Úis_bounding_boxÚ
old_heightÚ	old_widthÚscaleÚ
new_heightÚ	new_widths	            r(   r³   r³     s´   € ð *Ñ€Jà˜#Ñ¤ JÓ :Ñ:€EØ&Ñ.°	Ñ0A�	Ü�I ‘OÓ$€IÜ�Z #Ñ%Ó&€Jä�fÓ×#Ñ#Ó%€FæØ—‘  A qÓ)ˆà˜F‘^ yÑ'<Ñ=€Fˆ6�NØ˜F‘^ zÑ'>Ñ?€Fˆ6�NæØ—‘  AÓ&ˆà€Mr'   Úrlec                 óÎ   • U S   u  p[         R                  " X-  [        S9nSnSnU S    H  nXSXDU-   & XF-  nU(       + nM     UR                  X!5      nUR	                  SS5      $ )z/Compute a binary mask from an uncompressed RLE.Úsizer0   r   FÚcountsrZ   )r3   ÚemptyÚboolrI   Ú	transpose)rÂ   rJ   rK   ÚmaskÚidxÚparityÚcounts          r(   Ú_rle_to_maskrÍ   '  sr   € à˜‘K�M€FÜ�;Š;�v‘~¬TÑ2€DØ
€CØ€FØ�X”ˆØ"(ˆS˜‘;ÐØ‰ˆØ”Šñ ð �<‰<˜Ó&€DØ�>‰>˜!˜QÓÐr'   c                 ó  • [        UR                  5       U[        R                  " UR                  S   5      US9nX   nU Vs/ s H  oPU   PM	     n nX$   nU  Vs/ s H  n[        U5      PM     nnXqX4$ s  snf s  snf )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   )rd   ÚscoresÚidxsÚiou_threshold)r   r^   r3   rB   rC   rÍ   )Ú	rle_masksÚ
iou_scoresÚ
mask_boxesÚamg_crops_nms_threshÚkeep_by_nmsr‘   rÂ   r*   s           r(   Ú!_post_process_for_mask_generationr×   5  s‹   € ô Ø×ÑÓ ØÜ�[Š[˜×)Ñ)¨!Ñ,Ó-Ø*ñ	€Kð Ñ(€JÙ'2Ó3¢{ !˜1”¡{€IÐ3ØÑ(€JÙ*3Ó4ª) 3Œ\˜#Ö©)€EÐ4à˜iÐ3Ð3ùò	 4ùâ4s   ÁA7ÁA<c                 ó~  • U R                   u  pnU R                  SSS5      R                  S5      n U SS2SS24   U SS2SS24   -  nUR                  5       n/ n[	        U5       HÓ  nXUSS2S4   U:H  S4   S-   n[        U5      S:X  a>  XS4   S:X  a  UR                  X#/X#-  /S.5        OUR                  X#/SX#-  /S.5        Mc  USS USS -
  n	XS4   S:X  a  / OS/n
X¨S   R                  5       /U	R                  5       -   X#-  US   R                  5       -
  /-   -  n
UR                  X#/U
S.5        MÕ     U$ )zV
Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools.
r   r‚   rZ   Nr/   )rÄ   rÅ   )	rC   r‹   ÚflattenÚnonzeror†   r`   r‡   ÚitemÚtolist)Ú
input_maskÚ
batch_sizerJ   rK   ÚdiffÚchange_indicesrV   r‘   Úcur_idxsÚbtw_idxsrÅ   s              r(   Ú_mask_to_rlerã   R  sr  € ð
 !+× 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 OÀÁÐ?OÑPÕQà—
‘
 V OÀÀ6Á>Ð?RÑSÔTÙØ˜A˜B�< (¨3¨B -Ñ/ˆØ! Q $Ñ'¨1Ó,‘°1°#ˆØ˜A‘;×#Ñ#Ó%Ð&¨¯©Ó):Ñ:¸f¹nÈxÐXZÉ|×O`ÑO`ÓObÑ>bÐ=cÑcÑcˆØ�
‰
˜V˜O°vÑ>Ö?ñ ð €Jr'   c                   ó  ^ • \ rS rSr\r\R                  r\	r
\rSSS.rSSS.rSrSrSrSrSrSrSrS\\   4U 4S jjr\ S$S	\S
\S-  S\\   S\4U 4S jjj5       r S$S\S-  S\4U 4S jjjr S$S	\S
\S-  S\S\ S\!\"S4   S-  S\\   S\4S jjr#S	\$S   S\"\%-  S-  SS4U 4S jjr&     S%SSS\'S\(S\'S-  S\$\'   S-  S\)S   4S jjr*    S&S jr+     S'S jr,S  r-S!\.R^                  S\.R^                  4S" jr0S#r1U =r2$ )(ÚSam2ImageProcessoriq  i   )rJ   rK   é   TNÚkwargsc                 ó&   >• [         TU ]  " S0 UD6  g )Nr   )ÚsuperÚ__init__)Úselfrç   Ú	__class__s     €r(   rê   ÚSam2ImageProcessor.__init__ƒ  s   ø€ Ü‰ÒÑ"˜6Ó"r'   ÚimagesÚsegmentation_mapsr€   c                 ó&   >• [         TU ]  " X40 UD6$ )zX
segmentation_maps (`ImageInput`, *optional*):
    The segmentation maps to preprocess.
)ré   Ú
preprocess)rë   rî   rï   rç   rì   s       €r(   rñ   ÚSam2ImageProcessor.preprocess†  s   ø€ ô ‰wÒ! &ÑF¸vÑFÐFr'   r   c           	      ó‚   >• Ub(  [        U[        5      (       d  [        S0 [        USS9D6nXS'   [        TU ]  " S0 UD6$ )zD
Update kwargs that need further processing before being validated.
r   )Ú
param_namer   )rƒ   r   r   ré   Ú_standardize_kwargs)rë   r   rç   rì   s      €r(   rõ   Ú&Sam2ImageProcessor._standardize_kwargs“  sF   ø€ ð Ñ ¬°I¼x×)HÑ)HÜ ÑT¤=°À{Ñ#SÑTˆIØ'ˆ{ÑÜ‰wÒ*Ñ4¨VÑ4Ð4r'   Údo_convert_rgbr´   r=   ztorch.devicec                 ó&  • U R                  XXES9nU Vs/ s H  owR                  SS PM     nnUR                  5       n	U R                  " U40 U	D6n
U
US.nUb¨  U R                  USS[        R
                  S9nUR                  5       nUR                  SS[        R                  UR                  S5      S	.5        U R                  " SS
U0UD6nUR                  S5      R                  [        R                  5      US'   [        X¶S   S9$ s  snf )z
Preprocess image-like inputs.
)rî   r÷   r´   r=   r;   N)Úpixel_valuesÚoriginal_sizesr‚   F)rî   Úexpected_ndimsr÷   r´   r   )Údo_normalizeÚ
do_rescaleÚresamplerÄ   rî   rZ   ÚlabelsÚreturn_tensors)ÚdataÚtensor_typer   )Ú_prepare_image_like_inputsrC   ÚcopyÚ_preprocessr   ÚFIRSTÚupdater   ÚNEARESTÚpopÚsqueezeÚtor3   r�   r   )rë   rî   rï   r÷   r´   r=   rç   rŽ   rú   Úimages_kwargsrù   r  Úprocessed_segmentation_mapsÚsegmentation_maps_kwargss                 r(   Ú_preprocess_image_like_inputsÚ0Sam2ImageProcessor._preprocess_image_like_inputs   s9  € ð ×0Ñ0ØÐL]ð 1ð 
ˆñ 9?Ó?º¨uŸ+™+ b cÓ*¹ˆÐ?ØŸ™›ˆØ×'Ò'¨Ñ@°-Ñ@ˆà(Ø,ñ
ˆð
 Ñ(Ø*.×*IÑ*IØ(Ø Ø$Ü"2×"8Ñ"8ð	 +Jð +Ð'ð (.§{¡{£}Ð$Ø$×+Ñ+à$)Ø"'Ü 2× :Ñ :Ø4×8Ñ8¸ÓEñ	ôð +/×*:Ò*:ñ +Ø2ð+Ø6Nñ+Ð'ð 9×@Ñ@ÀÓC×FÑFÄuÇ{Á{ÓSˆD�‰Nä Ð:JÑ3KÑLÐLùò= @s   •Dr+   r   c                 ó>   >• [         TU ]  " U4SU0UD6R                  $ )Nr   )ré   r  rù   )rë   rî   r   rç   rì   s       €r(   r  ÚSam2ImageProcessor._preprocessÏ  s%   ø€ ô ‰wÒ" 6ÑS¸.ÐSÈFÑS×`Ñ`Ð`r'   rŽ   z+np.ndarray | PIL.Image.Image | torch.Tensorr|   r}   r~   r   c                 óê   • U R                  U5      n[        UUUUUU5      u  p…pšUc  [        R                  " S5      nUR	                  U5      nUR	                  U5      nU
R	                  U5      n
X…Xš4$ )ap  
Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

Args:
    image (`torch.Tensor`):
        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 sam2ple from each crop.
    crop_n_points_downscale_factor (`list[int]`, *optional*, defaults to 1):
        The number of points-per-side sam2pled 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.
Úcpu)Úprocess_imager˜   r3   r=   r  )rë   rŽ   r{   r|   r}   r~   r   r=   r“   r•   r—   s              r(   Úgenerate_crop_boxesÚ&Sam2ImageProcessor.generate_crop_boxes×  s‚   € ð> ×"Ñ" 5Ó)ˆÜDXØØØØØØ*óE
ÑAˆ
 ^ð ‰>Ü—\’\ %Ó(ˆFØ—]‘] 6Ó*ˆ
Ø)×,Ñ,¨VÓ4ˆà#—‘ vÓ.ˆà¨NÐHÐHr'   c	                 ót  • Uu  pšUR                  SS5      nUR                  SS5      nUR                  S   UR                  S   :w  a  [        S5      eUR                  UR                  :w  a  UR	                  UR                  5      nUR                  S   n[
        R                  " U[
        R                  UR                  S9nUS:”  a  XÂU:„  -  nUS:”  a  [        XU5      nXÍU:„  -  nX,   nX   nX:„  n[        U5      n[        XôSSX©/5      ) nXì   nX   nXü   n[        XXš5      n[        U5      nXU4$ )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 original image.
    cropped_box_image (`torch.Tensor`):
        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   rZ   z4masks and iou_scores must have the sam2e batch size.rY   ç        )rÙ   rC   r…   r=   r  r3   ÚonesrÇ   r9   rW   rn   rz   rã   )rë   r*   rÓ   r�   Úcropped_box_imageÚpred_iou_threshÚstability_score_threshr,   r-   Úoriginal_heightÚoriginal_widthrÞ   Ú	keep_maskr8   rÏ   Úconverted_boxess                   r(   Úfilter_masksÚSam2ImageProcessor.filter_masks  sV  € ðF +8Ñ'ˆØ×'Ñ'¨¨1Ó-ˆ
Ø—‘˜a Ó#ˆà�;‰;�q‰>˜Z×-Ñ-¨aÑ0Ó0ÜÐSÓTÐTà�<‰<˜:×,Ñ,Ó,Ø#Ÿ™ u§|¡|Ó4ˆJà—[‘[ ‘^ˆ
ä—J’J˜z´·±ÀEÇLÁLÑQˆ	à˜SÓ Ø!°/Ñ%AÑBˆIð " CÓ'Ü7¸ÐOeÓfÐØ!Ð8NÑ%NÑOˆIàÑ&ˆØÑ ˆð Ñ&ˆÜ.¨uÓ5ˆä+Ø°°A°~Ð0Wó
ð 
ˆ	ð Ñ"ˆØÑ ˆØ)Ñ4ˆä˜5°_ÓUˆä˜UÓ#ˆà˜oÐ-Ð-r'   c                 ó  • [        U[        R                  [        R                  45      (       a  UR                  5       n/ n	[        U5       Hº  u  p«[        X   [        R                  5      (       a  [        R                  " X   5      X'   O,[        X   [        R                  5      (       d  [        S5      e[        R                  " X   USSS9nU(       a  U R                  U5      nU(       a  XÃ:„  nU	R                  U5        M¼     U	$ )aŸ  
Remove padding and upscale masks to the original image size.

Args:
    masks (`Union[torch.Tensor, List[torch.Tensor], np.ndarray, 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.
    mask_threshold (`float`, *optional*, defaults to 0.0):
        Threshold for binarization and post-processing operations.
    binarize (`bool`, *optional*, defaults to `True`):
        Whether to binarize the masks.
    max_hole_area (`float`, *optional*, defaults to 0.0):
        The maximum area of a hole to fill.
    max_sprinkle_area (`float`, *optional*, defaults to 0.0):
        The maximum area of a sprinkle to fill.
    apply_non_overlapping_constraints (`bool`, *optional*, defaults to `False`):
        Whether to apply non-overlapping constraints to the masks.

Returns:
    (`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
    is given by original_size.
zIInput masks should be a list of `torch.tensors` or a list of `np.ndarray`ÚbilinearF)ÚmodeÚalign_corners)rƒ   r3   ÚTensorÚnpÚndarrayrÜ   r±   Ú
from_numpyÚ	TypeErrorÚFÚinterpolateÚ"_apply_non_overlapping_constraintsr‡   )rë   r*   rú   r,   ÚbinarizeÚmax_hole_areaÚmax_sprinkle_areaÚ!apply_non_overlapping_constraintsrç   Úoutput_masksr‘   r�   Úinterpolated_masks                r(   Úpost_process_masksÚ%Sam2ImageProcessor.post_process_masksV  sÚ   € ôF �n¤u§|¡|´R·Z±ZÐ&@×AÑAØ+×2Ñ2Ó4ˆNàˆÜ )¨.Ö 9ÑˆAÜ˜%™(¤B§J¡J×/Ñ/Ü ×+Ò+¨E©HÓ5�’Ü ¡¬%¯,©,×7Ñ7ÜÐ kÓlÐlÜ !§¢¨e©h¸ÈJÐfkÑ lÐÞ0Ø$(×$KÑ$KÐL]Ó$^Ð!ÞØ$5Ñ$FÐ!Ø×ÑÐ 1Ö2ñ !:ð Ðr'   c                 ó   • [        XX45      $ )aÌ  
Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.

Args:
    all_masks (`torch.Tensor`):
        List of all predicted segmentation masks
    all_scores (`torch.Tensor`):
        List of all predicted iou scores
    all_boxes (`torch.Tensor`):
        List of all bounding boxes of the predicted masks
    crops_nms_thresh (`float`):
        Threshold for NMS (Non Maximum Suppression) algorithm.
)r×   )rë   Ú	all_masksÚ
all_scoresÚ	all_boxesÚcrops_nms_threshs        r(   Ú post_process_for_mask_generationÚ3Sam2ImageProcessor.post_process_for_mask_generation‹  s   € ô 1°È	ÓdÐdr'   Ú
pred_masksc           	      ó  • UR                  S5      nUS:X  a  U$ UR                  n[        R                  " USSS9n[        R                  " X#S9SS2SSS4   nXE:H  n[        R
                  " Xa[        R                  " USS95      nU$ )	zœ
Apply non-overlapping constraints to the object scores in pred_masks. Here we
keep only the highest scoring object at each spatial location in pred_masks.
r   rZ   T)r?   Úkeepdimr@   Ng      $À)rD   )rÄ   r=   r3   ÚargmaxrE   ÚwhereÚclamp)rë   r?  rÞ   r=   Úmax_obj_indsÚbatch_obj_indsÚkeeps          r(   r/  Ú5Sam2ImageProcessor._apply_non_overlapping_constraints›  s„   € ð
  —_‘_ QÓ'ˆ
Ø˜‹?ØÐà×"Ñ"ˆä—|’| J°A¸tÑDˆäŸš jÑ@ÂÀDÈ$ÐPTÐATÑUˆØÑ-ˆô —[’[ ´5·;²;¸zÈuÑ3UÓVˆ
ØÐr'   r   ©N)r   ç¥âìÃgØÕ?é    rZ   N)g)\�Âõ(ì?gffffffî?r   rZ   )r  Tr  r  F)3r   r   r   r    r   Úvalid_kwargsr   ÚBILINEARrþ   r   Ú
image_meanr   Ú	image_stdrÄ   r   Ú	do_resizerý   rü   r÷   Údo_padÚpad_sizeÚmask_pad_sizer   rê   r   r   r   rñ   r   r"   rõ   rÇ   r   r   r#   r  r„   r   r  r$   r^   r   r  r"  r6  r=  r3   r(  r/  r&   Ú__classcell__)rì   s   @r(   rå   rå   q  s>  ø† à+€LØ!×*Ñ*€HØ&€JØ$€IØ TÑ*€DØ¨Ñ-€IØ€IØ€JØ€LØ€Nð €FØ€HØ€Mð# Ð(@Ñ!A÷ #ð ð 04ñ
Gàð
Gð &¨Ñ,ð
Gð Ð1Ñ2ð	
Gð
 
÷
Gó ð
Gð &*ñ5à˜d‘?ð5ð 
÷	5ð 5ð& 59ñ-Màð-Mð &¨Ñ,ð-Mð ð	-Mð
 ,ð-Mð �c˜>Ð)Ñ*¨TÑ1ð-Mð Ð1Ñ2ð-Mð 
õ-Mð^aà�^Ñ$ðað ˜jÑ(¨4Ñ/ðað
 
÷að Ø)Ø&(Ø;<Ø+/ñ/Ià<ð/Ið ð	/Ið
 ð/Ið ˜t™ð/Ið )-¨S©	°DÑ(8ð/Ið ˜Ñ(õ/Iðn Ø#ØØ ôL.ðd ØØØØ*/ô3òjeð ¸U¿\¹\ð ÈeÏlÉl÷ ò r'   rå   )r*   r+   )g      4@)r   rJ  rK  rZ   rI  )F)gffffffæ?)rÝ   r+   )<rš   r  r   Ú	itertoolsr   Útypingr   r   r   Únumpyr)  r3   Útorch.nn.functionalrs   rt   r-  Útorchvision.ops.boxesr   Úimage_processing_backendsr
   Úimage_processing_utilsr   r   Úimage_utilsr   r   r   r   r   r   Úprocessing_utilsr   r   Úutilsr   r   r   ÚPILr   r^   r$   r9   rW   rn   r„   rz   Útupler˜   r‰   r(  rˆ   rŠ   r³   r"   r#   rÍ   r×   rã   rå   Ú__all__r   r'   r(   Ú<module>rb     sÐ  ðó( Ý Ý ß 'Ñ 'ã Û ß Ð Ý -å ;ß A÷÷ ÷ 5ß DÑ Dñ ×ÑÛô˜|°5ò ð Nð ÀEð Ðcfô ô.ôb,ð$8  S¡	ð 8¸ð 8Èô 8ð Ø%Ø"$Ø78ñ2Eàð2Eð ð2Eð ð	2Eð
 ˜4‘Zð2Eð %)¨¡I°Ñ$4ð2Eð ˆ4��S‘	‰?˜D ™IÐ%Ñ&õ2Eòj"ðD #ð ¨%¯,©,ô ð _cô1ð4 ]bñØðØ#Ÿl™lðØ;@ÀÀcÀ¹?ðà
‡\�\õð8 �d˜3 ˜8‘nð  ¨¯©ô  ô4ô:ð> ô{Ð+ó {ó ð{ð|	  Ð
 �r'   