ó
    ‰“,js-  ã                   óP   • S SK rS SKrS SKJr  S SKJrJr  SSKJ	r	   " S S5      r
g)é    N)ÚSam)ÚOptionalÚTupleé   )ÚResizeLongestSidec                   ó  ^ • \ rS rSrS\SS4U 4S jjr SS\R                  S\SS4S jjr	\
R                  " 5       S	\
R                  S
\\S4   SS4S j5       r      SS\\R                     S\\R                     S\\R                     S\\R                     S\S\S\\
R                  \
R                  \
R                  4   4S jjr\
R                  " 5           SS\\
R                     S\\
R                     S\\
R                     S\\
R                     S\S\S\\
R                  \
R                  \
R                  4   4S jj5       rS\
R                  4S jr\S\
R,                  4S j5       rSS jrSrU =r$ )ÚSamPredictoré   Ú	sam_modelÚreturnNc                 ó–   >• [         TU ]  5         Xl        [        UR                  R
                  5      U l        U R                  5         g)zÀ
Uses SAM to calculate the image embedding for an image, and then
allow repeated, efficient mask prediction given prompts.

Arguments:
  sam_model (Sam): The model to use for mask prediction.
N)ÚsuperÚ__init__Úmodelr   Úimage_encoderÚimg_sizeÚ	transformÚreset_image)Úselfr   Ú	__class__s     €Ú¨C:\Users\johnn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\segment_anything/predictor.pyr   ÚSamPredictor.__init__   s9   ø€ ô 	‰ÑÔØŒ
Ü*¨9×+BÑ+B×+KÑ+KÓLˆŒØ×ÑÕó    ÚimageÚimage_formatc                 óv  • US;   d   SU S35       eX R                   R                  :w  a
  USSSS24   nU R                  R                  U5      n[        R
                  " X0R                  S9nUR                  SS	S
5      R                  5       SSS2SS2SS24   nU R                  XAR                  SS 5        g)aG  
Calculates the image embeddings for the provided image, allowing
masks to be predicted with the 'predict' method.

Arguments:
  image (np.ndarray): The image for calculating masks. Expects an
    image in HWC uint8 format, with pixel values in [0, 255].
  image_format (str): The color format of the image, in ['RGB', 'BGR'].
)ÚRGBÚBGRz+image_format must be in ['RGB', 'BGR'], is Ú..Néÿÿÿÿ)Údeviceé   r   r   )r   r   r   Úapply_imageÚtorchÚ	as_tensorr!   ÚpermuteÚ
contiguousÚset_torch_imageÚshape)r   r   r   Úinput_imageÚinput_image_torchs        r   Ú	set_imageÚSamPredictor.set_image"   sÄ   € ð ð  
ó 
ð 	Ið 9¸¸ÀaÐHó	Ið 
ð Ÿ:™:×2Ñ2Ó2Ø˜#™t ˜t˜)Ñ$ˆEð —n‘n×0Ñ0°Ó7ˆÜ!ŸOšO¨KÇÁÑLÐØ-×5Ñ5°a¸¸AÓ>×IÑIÓKÈDÒRSÒUVÒXYÈMÑZÐà×ÑÐ.·±¸B¸Q°Õ@r   Útransformed_imageÚoriginal_image_size.c                 ó  • [        UR                  5      S:X  aJ  UR                  S   S:X  a7  [        UR                  SS 6 U R                  R                  R
                  :X  d)   SU R                  R                  R
                   S35       eU R                  5         X l        [        UR                  SS 5      U l	        U R                  R                  U5      nU R                  R	                  U5      U l        S	U l        g)
aÂ  
Calculates the image embeddings for the provided image, allowing
masks to be predicted with the 'predict' method. Expects the input
image to be already transformed to the format expected by the model.

Arguments:
  transformed_image (torch.Tensor): The input image, with shape
    1x3xHxW, which has been transformed with ResizeLongestSide.
  original_image_size (tuple(int, int)): The size of the image
    before transformation, in (H, W) format.
é   r   é   r"   Nz2set_torch_image input must be BCHW with long side r   éþÿÿÿT)Úlenr)   Úmaxr   r   r   r   Úoriginal_sizeÚtupleÚ
input_sizeÚ
preprocessÚfeaturesÚis_image_set)r   r.   r/   r*   s       r   r(   ÚSamPredictor.set_torch_image>   sê   € ô$ Ð!×'Ñ'Ó(¨AÓ-Ø!×'Ñ'¨Ñ*¨aÓ/ÜÐ&×,Ñ,¨Q¨RÐ0Ð1°T·Z±Z×5MÑ5M×5VÑ5VÓVð	eð @ÀÇ
Á
×@XÑ@X×@aÑ@aÐ?bÐbcÐdó		eðWð 	×ÑÔà0ÔÜÐ 1× 7Ñ 7¸¸Ð <Ó=ˆŒØ—j‘j×+Ñ+Ð,=Ó>ˆØŸ
™
×0Ñ0°Ó=ˆŒØ ˆÕr   Úpoint_coordsÚpoint_labelsÚboxÚ
mask_inputÚmultimask_outputÚreturn_logitsc           	      ó  • U R                   (       d  [        S5      eSu  pxpšUbŸ  Uc   S5       eU R                  R                  XR                  5      n[
        R                  " U[
        R                  U R                  S9n[
        R                  " U[
        R                  U R                  S9nUSSS2SS24   USSS24   p‡Ub\  U R                  R                  X0R                  5      n[
        R                  " U[
        R                  U R                  S9n	U	SSS24   n	Ub=  [
        R                  " U[
        R                  U R                  S9n
U
SSS2SS2SS24   n
U R                  UUU	U
UUS9u  p¼nUS   R                  5       R                  5       R                  5       nUS   R                  5       R                  5       R                  5       nUS   R                  5       R                  5       R                  5       nX¼U4$ )a&  
Predict masks for the given input prompts, using the currently set image.

Arguments:
  point_coords (np.ndarray or None): A Nx2 array of point prompts to the
    model. Each point is in (X,Y) in pixels.
  point_labels (np.ndarray or None): A length N array of labels for the
    point prompts. 1 indicates a foreground point and 0 indicates a
    background point.
  box (np.ndarray or None): A length 4 array given a box prompt to the
    model, in XYXY format.
  mask_input (np.ndarray): A low resolution mask input to the model, typically
    coming from a previous prediction iteration. Has form 1xHxW, where
    for SAM, H=W=256.
  multimask_output (bool): If true, the model will return three masks.
    For ambiguous input prompts (such as a single click), this will often
    produce better masks than a single prediction. If only a single
    mask is needed, the model's predicted quality score can be used
    to select the best mask. For non-ambiguous prompts, such as multiple
    input prompts, multimask_output=False can give better results.
  return_logits (bool): If true, returns un-thresholded masks logits
    instead of a binary mask.

Returns:
  (np.ndarray): The output masks in CxHxW format, where C is the
    number of masks, and (H, W) is the original image size.
  (np.ndarray): An array of length C containing the model's
    predictions for the quality of each mask.
  (np.ndarray): An array of shape CxHxW, where C is the number
    of masks and H=W=256. These low resolution logits can be passed to
    a subsequent iteration as mask input.
úAAn image must be set with .set_image(...) before mask prediction.)NNNNNz:point_labels must be supplied if point_coords is supplied.)Údtyper!   )rB   r   )r;   ÚRuntimeErrorr   Úapply_coordsr6   r$   r%   Úfloatr!   ÚintÚapply_boxesÚpredict_torchÚdetachÚcpuÚnumpy)r   r=   r>   r?   r@   rA   rB   Úcoords_torchÚlabels_torchÚ	box_torchÚmask_input_torchÚmasksÚiou_predictionsÚlow_res_maskss                 r   ÚpredictÚSamPredictor.predict\   sÜ  € ðR × × ÜÐbÓcÐcð CYÑ?ˆ IØÑ#àÑ(ðLàKóLØ(àŸ>™>×6Ñ6°|×EWÑEWÓXˆLÜ Ÿ?š?¨<¼u¿{¹{ÐSW×S^ÑS^Ñ_ˆLÜ Ÿ?š?¨<¼u¿y¹yÐQU×Q\ÑQ\Ñ]ˆLØ)5°dºAºq°jÑ)AÀ<ÐPTÒVWÐPWÑCX˜,Ø‰?Ø—.‘.×,Ñ,¨S×2DÑ2DÓEˆCÜŸš¨´5·;±;ÀtÇ{Á{ÑSˆIØ! $ª 'Ñ*ˆIØÑ!Ü$Ÿš¨zÄÇÁÐUY×U`ÑU`ÑaÐØ/°²aººA°Ñ>Ðà04×0BÑ0BØØØØØØ'ð 1Cð 1
Ñ-ˆ ð �a‘—‘Ó!×%Ñ%Ó'×-Ñ-Ó/ˆØ)¨!Ñ,×3Ñ3Ó5×9Ñ9Ó;×AÑAÓCˆØ% aÑ(×/Ñ/Ó1×5Ñ5Ó7×=Ñ=Ó?ˆØ }Ð4Ð4r   Úboxesc                 óÂ  • U R                   (       d  [        S5      eUb  X4nOSnU R                  R                  UUUS9u  p‰U R                  R	                  U R
                  U R                  R                  R                  5       UU	US9u  p«U R                  R                  X R                  U R                  5      nU(       d  XÀR                  R                  :„  nXËU
4$ )a  
Predict masks for the given input prompts, using the currently set image.
Input prompts are batched torch tensors and are expected to already be
transformed to the input frame using ResizeLongestSide.

Arguments:
  point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
    model. Each point is in (X,Y) in pixels.
  point_labels (torch.Tensor or None): A BxN array of labels for the
    point prompts. 1 indicates a foreground point and 0 indicates a
    background point.
  box (np.ndarray or None): A Bx4 array given a box prompt to the
    model, in XYXY format.
  mask_input (np.ndarray): A low resolution mask input to the model, typically
    coming from a previous prediction iteration. Has form Bx1xHxW, where
    for SAM, H=W=256. Masks returned by a previous iteration of the
    predict method do not need further transformation.
  multimask_output (bool): If true, the model will return three masks.
    For ambiguous input prompts (such as a single click), this will often
    produce better masks than a single prediction. If only a single
    mask is needed, the model's predicted quality score can be used
    to select the best mask. For non-ambiguous prompts, such as multiple
    input prompts, multimask_output=False can give better results.
  return_logits (bool): If true, returns un-thresholded masks logits
    instead of a binary mask.

Returns:
  (torch.Tensor): The output masks in BxCxHxW format, where C is the
    number of masks, and (H, W) is the original image size.
  (torch.Tensor): An array of shape BxC containing the model's
    predictions for the quality of each mask.
  (torch.Tensor): An array of shape BxCxHxW, where C is the number
    of masks and H=W=256. These low res logits can be passed to
    a subsequent iteration as mask input.
rD   N)ÚpointsrX   rS   )Úimage_embeddingsÚimage_peÚsparse_prompt_embeddingsÚdense_prompt_embeddingsrA   )r;   rF   r   Úprompt_encoderÚmask_decoderr:   Úget_dense_peÚpostprocess_masksr8   r6   Úmask_threshold)r   r=   r>   rX   r@   rA   rB   rZ   Úsparse_embeddingsÚdense_embeddingsrU   rT   rS   s                r   rK   ÚSamPredictor.predict_torch¨   sÝ   € ðZ × × ÜÐbÓcÐcàÑ#Ø"Ð1‰FàˆFð /3¯j©j×.GÑ.GØØØð /Hð /
Ñ+Ðð *.¯©×)@Ñ)@Ø!Ÿ]™]Ø—Z‘Z×.Ñ.×;Ñ;Ó=Ø%6Ø$4Ø-ð *Að *
Ñ&ˆð —
‘
×,Ñ,¨]¿O¹OÈT×M_ÑM_Ó`ˆæØŸJ™J×5Ñ5Ñ5ˆEà }Ð4Ð4r   c                 óz   • U R                   (       d  [        S5      eU R                  c   S5       eU R                  $ )zÂ
Returns the image embeddings for the currently set image, with
shape 1xCxHxW, where C is the embedding dimension and (H,W) are
the embedding spatial dimension of SAM (typically C=256, H=W=64).
zCAn image must be set with .set_image(...) to generate an embedding.z-Features must exist if an image has been set.)r;   rF   r:   ©r   s    r   Úget_image_embeddingÚ SamPredictor.get_image_embeddingõ   s?   € ð × × ÜØUóð ð �}‰}Ñ(ÐYÐ*YÓYÐ(Ø�}‰}Ðr   c                 ó.   • U R                   R                  $ )N)r   r!   rh   s    r   r!   ÚSamPredictor.device  s   € à�z‰z× Ñ Ð r   c                 óX   • SU l         SU l        SU l        SU l        SU l        SU l        g)zResets the currently set image.FN)r;   r:   Úorig_hÚorig_wÚinput_hÚinput_wrh   s    r   r   ÚSamPredictor.reset_image  s-   € à!ˆÔØˆŒØˆŒØˆŒØˆŒØˆ�r   )
r:   rp   r8   rq   r;   r   rn   ro   r6   r   )r   )NNNNTF)NNTF)r   N)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__r   r   ÚnpÚndarrayÚstrr,   r$   Úno_gradÚTensorr   rI   r(   r   ÚboolrV   rK   ri   Úpropertyr!   r   Ú__static_attributes__Ú__classcell__)r   s   @r   r	   r	      s  ø† ðàðð 
÷ð& "ñAà�z‰zðAð ðAð 
õ	Að8 ‡]‚]ƒ_ð!à Ÿ<™<ð!ð # 3¨ 8™_ð!ð 
ó	!ó ð!ð> .2Ø-1Ø$(Ø+/Ø!%Ø#ñJ5à˜rŸz™zÑ*ðJ5ð ˜rŸz™zÑ*ðJ5ð �b—j‘jÑ!ð	J5ð
 ˜RŸZ™ZÑ(ðJ5ð ðJ5ð ðJ5ð 
ˆu�|‰|˜UŸ\™\¨5¯<©<Ð7Ñ	8õJ5ðX ‡]‚]ƒ_ð
 )-Ø-1Ø!%Ø#ñJ5à˜uŸ|™|Ñ,ðJ5ð ˜uŸ|™|Ñ,ðJ5ð ˜Ÿ™Ñ%ð	J5ð
 ˜UŸ\™\Ñ*ðJ5ð ðJ5ð ðJ5ð 
ˆu�|‰|˜UŸ\™\¨5¯<©<Ð7Ñ	8ôJ5ó ðJ5ðX U§\¡\ô ð ð!˜Ÿ™ó !ó ð!÷ò r   r	   )rN   rw   r$   Úsegment_anything.modelingr   Útypingr   r   Úutils.transformsr   r	   © r   r   Ú<module>r„      s"   ðó Û å )ç "å /÷|ò |r   