ó
    ‰“,j;  ã                   ó´   • S SK rS SKrS SKJrJr  S SKJrJrJ	r	J
r
Jr  SSKJr  SSKJr  SSKJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJ r    " S S	5      r!g)
é    N)Úbatched_nmsÚbox_area)ÚAnyÚDictÚListÚOptionalÚTupleé   )ÚSam)ÚSamPredictor)ÚMaskDataÚarea_from_rleÚbatch_iteratorÚbatched_mask_to_boxÚbox_xyxy_to_xywhÚbuild_all_layer_point_gridsÚcalculate_stability_scoreÚcoco_encode_rleÚgenerate_crop_boxesÚis_box_near_crop_edgeÚmask_to_rle_pytorchÚremove_small_regionsÚrle_to_maskÚuncrop_boxes_xyxyÚuncrop_masksÚuncrop_pointsc                   óÔ  • \ rS rSr             S#S\S\\   S\S\S\S\S	\S
\S\S\S\S\\\	R                        S\S\SS4S jjr\R                  " 5       S\	R                  S\\\\4      4S j5       rS\	R                  S\4S jrS\	R                  S\\   S\S\\S4   S\4
S jrS\	R                  S\\S4   S\\   S\\S4   S\4
S jr\S\S\S \S\4S! j5       rS"rg)$ÚSamAutomaticMaskGeneratoré#   NÚmodelÚpoints_per_sideÚpoints_per_batchÚpred_iou_threshÚstability_score_threshÚstability_score_offsetÚbox_nms_threshÚcrop_n_layersÚcrop_nms_threshÚcrop_overlap_ratioÚcrop_n_points_downscale_factorÚpoint_gridsÚmin_mask_region_areaÚoutput_modeÚreturnc                 ón  • USL USL :w  d   S5       eUb  [        UUU5      U l        OUb  XÀl        O[        S5      eUS;   d   SU S35       eUS:X  a  SS	KJn  US:”  a  SSKn[        U5      U l        X0l        X@l	        XPl
        X`l        Xpl        X€l        X�l        X l        X°l        XÐl        Xàl        g)
aœ	  
Using a SAM model, generates masks for the entire image.
Generates a grid of point prompts over the image, then filters
low quality and duplicate masks. The default settings are chosen
for SAM with a ViT-H backbone.

Arguments:
  model (Sam): The SAM model to use for mask prediction.
  points_per_side (int or None): The number of points to be sampled
    along one side of the image. The total number of points is
    points_per_side**2. If None, 'point_grids' must provide explicit
    point sampling.
  points_per_batch (int): Sets the number of points run simultaneously
    by the model. Higher numbers may be faster but use more GPU memory.
  pred_iou_thresh (float): A filtering threshold in [0,1], using the
    model's predicted mask quality.
  stability_score_thresh (float): A filtering threshold in [0,1], using
    the stability of the mask under changes to the cutoff used to binarize
    the model's mask predictions.
  stability_score_offset (float): The amount to shift the cutoff when
    calculated the stability score.
  box_nms_thresh (float): The box IoU cutoff used by non-maximal
    suppression to filter duplicate masks.
  crops_n_layers (int): 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.
  crops_nms_thresh (float): The box IoU cutoff used by non-maximal
    suppression to filter duplicate masks between different crops.
  crop_overlap_ratio (float): 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.
  crop_n_points_downscale_factor (int): The number of points-per-side
    sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
  point_grids (list(np.ndarray) or None): A list over explicit grids
    of points used for sampling, normalized to [0,1]. The nth grid in the
    list is used in the nth crop layer. Exclusive with points_per_side.
  min_mask_region_area (int): If >0, postprocessing will be applied
    to remove disconnected regions and holes in masks with area smaller
    than min_mask_region_area. Requires opencv.
  output_mode (str): The form masks are returned in. Can be 'binary_mask',
    'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.
    For large resolutions, 'binary_mask' may consume large amounts of
    memory.
Nz>Exactly one of points_per_side or point_grid must be provided.z7Can't have both points_per_side and point_grid be None.)Úbinary_maskÚuncompressed_rleÚcoco_rlezUnknown output_mode Ú.r2   r   )Úmask)r   r+   Ú
ValueErrorÚpycocotoolsr4   Úcv2r   Ú	predictorr"   r#   r$   r%   r&   r'   r(   r)   r*   r,   r-   )Úselfr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   Ú
mask_utilsr7   s                    Ú·C:\Users\johnn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\segment_anything/automatic_mask_generator.pyÚ__init__Ú"SamAutomaticMaskGenerator.__init__$   sö   € ð|   4Ð'Ø˜4Ðó
ð 	LàKó	Lð 
ð Ñ&Ü:ØØØ.ó ˆDÕð
 Ñ$Ø*ÕäÐVÓWÐWàð 
ó 
ð 	1ð " + ¨aÐ0ó		1ð 
ð
 ˜*Ó$Ý6à !Ó#Ûä% eÓ,ˆŒØ 0ÔØ.ÔØ&<Ô#Ø&<Ô#Ø,ÔØ*ÔØ.ÔØ"4ÔØ.LÔ+Ø$8Ô!Ø&Õó    Úimagec                 ó<  • U R                  U5      nU R                  S:”  a;  U R                  UU R                  [        U R                  U R
                  5      5      nU R                  S:X  a#  US    Vs/ s H  n[        U5      PM     snUS'   O;U R                  S:X  a#  US    Vs/ s H  n[        U5      PM     snUS'   OUS   US'   / n[        [        US   5      5       Hª  nUS   U   [        US   U   5      [        US   U   5      R                  5       US   U   R                  5       US   U   R                  5       /US	   U   R                  5       [        US
   U   5      R                  5       S.nUR                  U5        M¬     U$ s  snf s  snf )a  
Generates masks for the given image.

Arguments:
  image (np.ndarray): The image to generate masks for, in HWC uint8 format.

Returns:
   list(dict(str, any)): A list over records for masks. Each record is
     a dict containing the following keys:
       segmentation (dict(str, any) or np.ndarray): The mask. If
         output_mode='binary_mask', is an array of shape HW. Otherwise,
         is a dictionary containing the RLE.
       bbox (list(float)): The box around the mask, in XYWH format.
       area (int): The area in pixels of the mask.
       predicted_iou (float): The model's own prediction of the mask's
         quality. This is filtered by the pred_iou_thresh parameter.
       point_coords (list(list(float))): The point coordinates input
         to the model to generate this mask.
       stability_score (float): A measure of the mask's quality. This
         is filtered on using the stability_score_thresh parameter.
       crop_box (list(float)): The crop of the image used to generate
         the mask, given in XYWH format.
r   r2   ÚrlesÚsegmentationsr0   ÚboxesÚ	iou_predsÚpointsÚstability_scoreÚ
crop_boxes)ÚsegmentationÚareaÚbboxÚpredicted_iouÚpoint_coordsrF   Úcrop_box)Ú_generate_masksr,   Úpostprocess_small_regionsÚmaxr&   r(   r-   r   r   ÚrangeÚlenr   r   ÚtolistÚitemÚappend)r9   r?   Ú	mask_dataÚrleÚ	curr_annsÚidxÚanns          r;   ÚgenerateÚ"SamAutomaticMaskGenerator.generateˆ   s²  € ð6 ×(Ñ(¨Ó/ˆ	ð ×$Ñ$ qÓ(Ø×6Ñ6ØØ×)Ñ)Ü�D×'Ñ'¨×)=Ñ)=Ó>óˆIð ×Ñ˜zÓ)ØJSÐTZÒJ[Ó)\ÒJ[À3¬/¸#Ö*>ÑJ[Ñ)\ˆI�oÒ&Ø×Ñ Ó.ØFOÐPVÒFWÓ)XÒFW¸s¬+°cÖ*:ÑFWÑ)XˆI�oÒ&à)2°6Ñ):ˆI�oÑ&ð ˆ	Üœ˜Y Ñ7Ó8Ö9ˆCà )¨/Ñ :¸3Ñ ?Ü% i°Ñ&7¸Ñ&<Ó=Ü(¨°7Ñ);¸CÑ)@ÓA×HÑHÓJØ!*¨;Ñ!7¸Ñ!<×!AÑ!AÓ!CØ!*¨8Ñ!4°SÑ!9×!@Ñ!@Ó!BÐ CØ#,Ð->Ñ#?ÀÑ#D×#IÑ#IÓ#KÜ,¨Y°|Ñ-DÀSÑ-IÓJ×QÑQÓSñˆCð ×Ñ˜SÖ!ñ :ð Ðùò) *]ùâ)Xs   Á4FÂ'Fc           
      ó6  • UR                   S S n[        X R                  U R                  5      u  p4[	        5       n[        X45       H(  u  pgU R                  XXr5      nUR                  U5        M*     [        U5      S:”  a‡  S[        US   5      -  n	U	R                  US   R                  5      n	[        US   R                  5       U	[        R                  " [        US   5      5      U R                   S9n
UR#                  U
5        UR%                  5         U$ )Né   r
   rG   rC   ©Úiou_threshold)Úshaper   r'   r)   r   ÚzipÚ_process_cropÚcatrR   r   ÚtoÚdevicer   ÚfloatÚtorchÚzerosr(   ÚfilterÚto_numpy)r9   r?   Ú	orig_sizerG   Ú
layer_idxsÚdatarM   Ú	layer_idxÚ	crop_dataÚscoresÚkeep_by_nmss              r;   rN   Ú)SamAutomaticMaskGenerator._generate_masksÅ   sù   € Ø—K‘K  �Oˆ	Ü!4Ø×)Ñ)¨4×+BÑ+Bó"
Ñˆ
ô
 ‹zˆÜ#& zÖ#>ÑˆHØ×*Ñ*¨5¸IÓQˆIØ�H‰H�YÖñ $?ô
 ˆz‹?˜QÓàœ $ |Ñ"4Ó5Ñ5ˆFØ—Y‘Y˜t G™}×3Ñ3Ó4ˆFÜ%Ø�W‘×#Ñ#Ó%ØÜ—’œC  W¡Ó.Ó/Ø"×2Ñ2ñ	ˆKð �K‰K˜Ô$à�‰ŒØˆr>   rM   Úcrop_layer_idxrl   .c           
      ó0  • Uu  pVpxXU2XW2S S 24   n	U	R                   S S n
U R                  R                  U	5        [        R                  " U
5      S S S S24   nU R
                  U   U-  n[        5       n[        U R                  U5       H)  u  nU R                  XêX$5      nUR                  U5        AM+     U R                  R                  5         [        US   R                  5       US   [        R                  " [!        US   5      5      U R"                  S9nUR%                  U5        ['        US   U5      US'   [)        US   U5      US'   [        R*                  " [-        [!        US   5      5       Vs/ s H  nUPM     sn5      US'   U$ s  snf )	Nr^   éÿÿÿÿrC   rD   r_   rE   rA   rG   )ra   r8   Ú	set_imageÚnpÚarrayr+   r   r   r"   Ú_process_batchrd   Úreset_imager   rg   rh   ri   rR   r&   rj   r   r   ÚtensorrQ   )r9   r?   rM   rt   rl   Úx0Úy0Úx1Úy1Ú
cropped_imÚcropped_im_sizeÚpoints_scaleÚpoints_for_imagern   rE   Ú
batch_datarr   Ú_s                     r;   rc   Ú'SamAutomaticMaskGenerator._process_cropá   s†  € ð "‰ˆ�Ø˜b˜5 " %ª˜?Ñ+ˆ
Ø$×*Ñ*¨2¨AÐ.ˆØ�‰× Ñ  Ô,ô —x’x Ó0°±t¸°t°Ñ<ˆØ×+Ñ+¨NÑ;¸lÑJÐô ‹zˆÜ'¨×(=Ñ(=Ð?OÖP‰IˆVØ×,Ñ,¨VÀhÓZˆJØ�H‰H�ZÔ Úñ Qð 	�‰×"Ñ"Ô$ô "Ø�‰M×ÑÓ!Ø�ÑÜ�KŠKœ˜D ™MÓ*Ó+Ø×-Ñ-ñ	
ˆð 	�‰�KÔ ô *¨$¨w©-¸ÓBˆˆW‰Ü& t¨H¡~°xÓ@ˆˆX‰Ü"Ÿ\š\¼UÄ3ÀtÈFÁ|ÓCTÔ=UÓ*VÒ=U¸«8Ñ=UÑ*VÓWˆˆ\Ñàˆùò +Ws   Å;FrE   Úim_sizec                 ó¸  • Uu  pVU R                   R                  R                  X5      n[        R                  " XpR                   R
                  S9n[        R                  " UR                  S   [        R                  UR
                  S9n	U R                   R                  US S 2S S S 24   U	S S 2S 4   SSS9u  p«n[        U
R                  SS5      UR                  SS5      [        R                  " UR                  U
R                  S   SS95      S9nA
U R                  S	:”  a#  US
   U R                  :„  nUR                  U5        [        US   U R                   R                   R"                  U R$                  5      US'   U R&                  S	:”  a#  US   U R&                  :¬  nUR                  U5        US   U R                   R                   R"                  :„  US'   [)        US   5      US'   [+        US   USSXe/5      ) n[        R,                  " U5      (       d  UR                  U5        [/        US   X5U5      US'   [1        US   5      US'   US	 U$ )N)rf   r   )Údtyperf   T)Úmultimask_outputÚreturn_logitsr
   )Úaxis)ÚmasksrD   rE   ç        rD   rŽ   rF   rC   rA   )r8   Ú	transformÚapply_coordsrh   Ú	as_tensorrf   Úonesra   ÚintÚpredict_torchr   ÚflattenÚrepeatr#   rj   r   r    Úmask_thresholdr%   r$   r   r   Úallr   r   )r9   rE   rˆ   rM   rl   Úorig_hÚorig_wÚtransformed_pointsÚ	in_pointsÚ	in_labelsrŽ   rD   r†   rn   Ú	keep_masks                  r;   rz   Ú(SamAutomaticMaskGenerator._process_batch
  s/  € ð #‰ˆð "Ÿ^™^×5Ñ5×BÑBÀ6ÓSÐÜ—O’OÐ$6¿~¹~×?TÑ?TÑUˆ	Ü—J’J˜yŸ™¨qÑ1¼¿¹È9×K[ÑK[Ñ\ˆ	Ø"Ÿn™n×:Ñ:Ø’a˜šq�jÑ!Ø’a˜�gÑØ!Øð	 ;ð 
Ñˆ˜!ô Ø—-‘-  1Ó%Ø×'Ñ'¨¨1Ó-Ü—?’? 6§=¡=°·±¸Q±Àa =Ð#HÓIñ
ˆð
 ð ×Ñ #Ó%Ø˜[Ñ)¨D×,@Ñ,@Ñ@ˆIØ�K‰K˜	Ô"ô #<Ø�‰M˜4Ÿ>™>×/Ñ/×>Ñ>À×@[Ñ@[ó#
ˆÐÑð ×&Ñ&¨Ó,ØÐ.Ñ/°4×3NÑ3NÑNˆIØ�K‰K˜	Ô"ð ˜W™¨¯©×(<Ñ(<×(KÑ(KÑKˆˆW‰Ü+¨D°©MÓ:ˆˆW‰ô +¨4°©=¸(ÀQÈÈ6ÐDZÓ[Ð[ˆ	Ü�yŠy˜×#Ñ#Ø�K‰K˜	Ô"ô % T¨'¡]°HÀfÓMˆˆW‰Ü*¨4°©=Ó9ˆˆV‰Ø�ˆMàˆr>   rV   Úmin_areaÚ
nms_threshc           	      óÞ  • [        U S   5      S:X  a  U $ / n/ nU S    H‹  n[        U5      n[        XaSS9u  pgU(       + n[        XaSS9u  pgU=(       a    U(       + nUR                  [        R
                  " U5      R                  S5      5        UR                  [        U5      5        M�     [        R                  " USS9n	[        U	5      n
[        U
R                  5       [        R
                  " U5      [        R                  " [        U
5      5      US9nU H>  nXL   S:X  d  M  Xœ   R                  S5      n[        U5      S   U S   U'   X¬   U S	   U'   M@     U R                  U5        U $ )
z¨
Removes small disconnected regions and holes in masks, then reruns
box NMS to remove any new duplicates.

Edits mask_data in place.

Requires open-cv as a dependency.
rA   r   Úholes)ÚmodeÚislands)Údimr_   r�   rC   )rR   r   r   rU   rh   r’   Ú	unsqueezerg   rd   r   r   ri   r   rj   )rV   r¡   r¢   Ú	new_masksrq   rW   r4   ÚchangedÚ	unchangedrŽ   rC   rr   Úi_maskÚ
mask_torchs                 r;   rO   Ú3SamAutomaticMaskGenerator.postprocess_small_regionsC  s[  € ô ˆy˜Ñ Ó! QÓ&ØÐð ˆ	ØˆØ˜VÔ$ˆCÜ˜sÓ#ˆDä0°ÀgÑN‰MˆDØ#œˆIÜ0°ÀiÑP‰MˆDØ!×1¨'¤kˆIà×ÑœUŸ_š_¨TÓ2×<Ñ<¸QÓ?Ô@ð �M‰Mœ% 	Ó*Ö+ñ %ô —	’	˜)¨Ñ+ˆÜ# EÓ*ˆÜ!Ø�K‰K‹MÜ�OŠO˜FÓ#Ü�KŠKœ˜E›
Ó#Ø$ñ	
ˆó "ˆFØ‰~ Õ$Ø"™]×4Ñ4°QÓ7�
Ü,?À
Ó,KÈAÑ,N�	˜&Ñ! &Ñ)Ø-2©]�	˜'Ñ" 6Ó*ñ	 "ð
 	×Ñ˜Ô%àÐr>   )r&   r'   r*   r(   r)   r,   r-   r+   r"   r#   r8   r%   r$   )é    é@   g)\�Âõ(ì?gffffffî?g      ð?çffffffæ?r   r±   g¥âìÃgØÕ?r
   Nr   r0   )Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__r   r   r”   rg   r   rx   ÚndarrayÚstrr<   rh   Úno_gradr   r   r[   r   rN   r	   rc   rz   ÚstaticmethodrO   Ú__static_attributes__© r>   r;   r   r   #   s   † ð *,Ø "Ø!%Ø(,Ø(+Ø #ØØ!$Ø$.Ø./Ø26Ø$%Ø(ñb'àðb'ð " #™ðb'ð ð	b'ð
 ðb'ð !&ðb'ð !&ðb'ð ðb'ð ðb'ð ðb'ð "ðb'ð ),ðb'ð ˜d 2§:¡:Ñ.Ñ/ðb'ð "ðb'ð ðb'ð  
õ!b'ðH ‡]‚]ƒ_ð:˜bŸj™jð :¨T°$°s¸C°x±.Ñ-Aó :ó ð:ðx R§Z¡Zð °Hô ð8'à�z‰zð'ð �s‘)ð'ð ð	'ð
 ˜˜c˜‘?ð'ð 
ô'ðR7à—
‘
ð7ð �s˜C�x‘ð7ð �s‘)ð	7ð
 ˜˜c˜‘?ð7ð 
ô7ðr ð0Øð0Ø'*ð0Ø8=ð0à	ó0ó ó0r>   r   )"Únumpyrx   rh   Útorchvision.ops.boxesr   r   Útypingr   r   r   r   r	   Úmodelingr   r8   r   Ú	utils.amgr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r»   r>   r;   Ú<module>rÁ      sA   ðó Û ß 7ç 3Õ 3å Ý #÷÷ ÷ ÷ ó ÷(Qò Qr>   