§
    ezni§\  ã                   óÈ   — d Z ddlZddlZddlmc mZ ddlZddl	m
Z
 ddlmZ ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZmZmZmZmZmZmZ dd
lmZ  G d„ de¦  «        Z dS )aº  
Generate predictions using the Segment Anything Model (SAM).

SAM is an advanced image segmentation model offering features like promptable segmentation and zero-shot performance.
This module contains the implementation of the prediction logic and auxiliary utilities required to perform segmentation
using SAM. It forms an integral part of the Ultralytics framework and is designed for high-performance, real-time image
segmentation tasks.
é    N)Ú	LetterBox)ÚBasePredictor)ÚResults)ÚDEFAULT_CFGÚops)Úselect_deviceé   )	Úbatch_iteratorÚbatched_mask_to_boxÚbuild_all_layer_point_gridsÚcalculate_stability_scoreÚgenerate_crop_boxesÚis_box_near_crop_edgeÚremove_small_regionsÚuncrop_boxes_xyxyÚuncrop_masks)Ú	build_samc                   ó¤   ‡ — e Zd ZdZeddfˆ fd„	Zd„ Zd„ Zdd„Zdd„Z		 	 	 	 	 	 	 	 	 	 dd„Z
dd„Zd„ Zˆ fd„Zd„ Zd„ Zd„ Zedd„¦   «         Zˆ xZS )Ú	Predictora�  
    Predictor class for the Segment Anything Model (SAM), extending BasePredictor.

    The class provides an interface for model inference tailored to image segmentation tasks.
    With advanced architecture and promptable segmentation capabilities, it facilitates flexible and real-time
    mask generation. The class is capable of working with various types of prompts such as bounding boxes,
    points, and low-resolution masks.

    Attributes:
        cfg (dict): Configuration dictionary specifying model and task-related parameters.
        overrides (dict): Dictionary containing values that override the default configuration.
        _callbacks (dict): Dictionary of user-defined callback functions to augment behavior.
        args (namespace): Namespace to hold command-line arguments or other operational variables.
        im (torch.Tensor): Preprocessed input image tensor.
        features (torch.Tensor): Extracted image features used for inference.
        prompts (dict): Collection of various prompt types, such as bounding boxes and points.
        segment_all (bool): Flag to control whether to segment all objects in the image or only specified ones.
    Nc                 óð   •— |€i }|                      t          ddd¬¦  «        ¦  «         t          ¦   «                              |||¦  «         d| j        _        d| _        d| _        i | _        d| _	        dS )a=  
        Initialize the Predictor with configuration, overrides, and callbacks.

        The method sets up the Predictor object and applies any configuration overrides or callbacks provided. It
        initializes task-specific settings for SAM, such as retina_masks being set to True for optimal results.

        Args:
            cfg (dict): Configuration dictionary.
            overrides (dict, optional): Dictionary of values to override default configuration.
            _callbacks (dict, optional): Dictionary of callback functions to customize behavior.
        NÚsegmentÚpredicti   )ÚtaskÚmodeÚimgszTF)
ÚupdateÚdictÚsuperÚ__init__ÚargsÚretina_masksÚimÚfeaturesÚpromptsÚsegment_all)ÚselfÚcfgÚ	overridesÚ
_callbacksÚ	__class__s       €ú~/var/www/html/cool-property-finder/image-detection-backend/venv/lib/python3.11/site-packages/ultralytics/models/sam/predict.pyr   zPredictor.__init__/   s|   ø€ ð ÐØˆIØ×Ò� 9°9ÀDÐIÑIÔIÑJÔJÐJÝ‰Œ×Ò˜˜i¨Ñ4Ô4Ð4Ø!%ˆŒ	ÔØˆŒØˆŒØˆŒØ ˆÔÐÐó    c                 óþ  — | j         �| j         S t          |t          j        ¦  «         }|rot	          j        |                      |¦  «        ¦  «        }|dddd…f                              d¦  «        }t	          j        |¦  «        }t          j	        |¦  «        }| 
                    | j        ¦  «        }| j        j        r|                     ¦   «         n|                     ¦   «         }|r|| j        z
  | j        z  }|S )aª  
        Preprocess the input image for model inference.

        The method prepares the input image by applying transformations and normalization.
        It supports both torch.Tensor and list of np.ndarray as input formats.

        Args:
            im (torch.Tensor | List[np.ndarray]): BCHW tensor format or list of HWC numpy arrays.

        Returns:
            (torch.Tensor): The preprocessed image tensor.
        N.éÿÿÿÿ)r   é   r	   é   )r"   Ú
isinstanceÚtorchÚTensorÚnpÚstackÚpre_transformÚ	transposeÚascontiguousarrayÚ
from_numpyÚtoÚdeviceÚmodelÚfp16ÚhalfÚfloatÚmeanÚstd)r&   r"   Ú
not_tensors      r+   Ú
preprocesszPredictor.preprocessE   sá   € ð Œ7ÐØ”7ˆNÝ# B­¬Ñ5Ô5Ð5ˆ
Øð 	&Ý”˜$×,Ò,¨RÑ0Ô0Ñ1Ô1ˆBØ�C˜˜˜2˜�I”×(Ò(¨Ñ6Ô6ˆBÝÔ% bÑ)Ô)ˆBÝÔ! "Ñ%Ô%ˆBà�UŠU�4”;ÑÔˆØœ*œ/Ð9ˆR�WŠW‰YŒYˆY¨r¯xªx©z¬zˆØð 	-Ø�t”y‘. D¤HÑ,ˆBØˆ	r,   c                 ó’   ‡— t          |¦  «        dk    s
J d¦   «         ‚t          | j        j        dd¬¦  «        Šˆfd„|D ¦   «         S )aÐ  
        Perform initial transformations on the input image for preprocessing.

        The method applies transformations such as resizing to prepare the image for further preprocessing.
        Currently, batched inference is not supported; hence the list length should be 1.

        Args:
            im (List[np.ndarray]): List containing images in HWC numpy array format.

        Returns:
            (List[np.ndarray]): List of transformed images.
        r	   z6SAM model does not currently support batched inferenceF)ÚautoÚcenterc                 ó(   •— g | ]} ‰|¬ ¦  «        ‘ŒS ))Úimage© )Ú.0ÚxÚ	letterboxs     €r+   ú
<listcomp>z+Predictor.pre_transform.<locals>.<listcomp>p   s&   ø€ Ð/Ð/Ð/ q�	�	 Ð"Ñ"Ô"Ð/Ð/Ð/r,   )Úlenr   r    r   )r&   r"   rL   s     @r+   r6   zPredictor.pre_transforma   sQ   ø€ õ �2‰wŒw˜!Š|ˆ|ˆ|ÐU‰|Œ|ˆ|Ý˜dœiœo°EÀ%ÐHÑHÔHˆ	Ø/Ð/Ð/Ð/¨BÐ/Ñ/Ô/Ð/r,   Fc                 ó2  — | j                              d|¦  «        }| j                              d|¦  «        }| j                              d|¦  «        }t          d„ |||fD ¦   «         ¦  «        r | j        |g|¢R i |¤ŽS |                      ||||||¦  «        S )a­  
        Perform image segmentation inference based on the given input cues, using the currently loaded image. This
        method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and
        mask decoder for real-time and promptable segmentation tasks.

        Args:
            im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
            bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
            points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixel coordinates.
            labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 for foreground and 0 for background.
            masks (np.ndarray, optional): Low-resolution masks from previous predictions. Shape should be (N, H, W). For SAM, H=W=256.
            multimask_output (bool, optional): Flag to return multiple masks. Helpful for ambiguous prompts. Defaults to False.

        Returns:
            (tuple): Contains the following three elements.
                - np.ndarray: The output masks in shape CxHxW, where C is the number of generated masks.
                - np.ndarray: An array of length C containing quality scores predicted by the model for each mask.
                - np.ndarray: Low-resolution logits of shape CxHxW for subsequent inference, where H=W=256.
        ÚbboxesÚpointsÚmasksc              3   ó   K  — | ]}|d u V — Œ	d S ©NrI   ©rJ   Úis     r+   ú	<genexpr>z&Predictor.inference.<locals>.<genexpr>‹   s&   è è € Ð:Ð:˜Qˆq�DˆyÐ:Ð:Ð:Ð:Ð:Ð:r,   )r$   ÚpopÚallÚgenerateÚprompt_inference)	r&   r"   rP   rQ   ÚlabelsrR   Úmultimask_outputr    Úkwargss	            r+   Ú	inferencezPredictor.inferencer   s°   € ð* ”×!Ò! (¨FÑ3Ô3ˆØ”×!Ò! (¨FÑ3Ô3ˆØ”× Ò  ¨%Ñ0Ô0ˆåÐ:Ð: 6¨6°5Ð"9Ð:Ñ:Ô:Ñ:Ô:ð 	6Ø �4”= Ð5 dÐ5Ð5Ð5¨fÐ5Ð5Ð5à×$Ò$ R¨°¸ÀÐHXÑYÔYÐYr,   c                 ó„  — | j         €| j                             |¦  «        n| j         }| j        d         d         j        dd…         |j        dd…         }	}| j        rdn-t          |	d         |d         z  |	d         |d         z  ¦  «        }
|�¢t          j        |t          j	        | j
        ¬¦  «        }|j        dk    r|d         n|}|€t          j        |j        d         ¦  «        }t          j        |t          j        | j
        ¬¦  «        }||
z  }|dd…ddd…f         |dd…df         }}|�@t          j        |t          j	        | j
        ¬¦  «        }|j        dk    r|d         n|}||
z  }|�9t          j        |t          j	        | j
        ¬¦  «                             d¦  «        }|�||fnd}| j                             |||¬¦  «        \  }}| j                             || j        j                             ¦   «         |||¬¦  «        \  }}|                     dd¦  «        |                     dd¦  «        fS )	aJ  
        Internal function for image segmentation inference based on cues like bounding boxes, points, and masks.
        Leverages SAM's specialized architecture for prompt-based, real-time segmentation.

        Args:
            im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
            bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
            points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixel coordinates.
            labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 for foreground and 0 for background.
            masks (np.ndarray, optional): Low-resolution masks from previous predictions. Shape should be (N, H, W). For SAM, H=W=256.
            multimask_output (bool, optional): Flag to return multiple masks. Helpful for ambiguous prompts. Defaults to False.

        Returns:
            (tuple): Contains the following three elements.
                - np.ndarray: The output masks in shape CxHxW, where C is the number of generated masks.
                - np.ndarray: An array of length C containing quality scores predicted by the model for each mask.
                - np.ndarray: Low-resolution logits of shape CxHxW for subsequent inference, where H=W=256.
        Nr	   r   r0   g      ð?©Údtyper;   )rQ   ÚboxesrR   )Úimage_embeddingsÚimage_peÚsparse_prompt_embeddingsÚdense_prompt_embeddingsr]   )r#   r<   Úimage_encoderÚbatchÚshaper%   Úminr2   Ú	as_tensorÚfloat32r;   Úndimr4   ÚonesÚint32Ú	unsqueezeÚprompt_encoderÚmask_decoderÚget_dense_peÚflatten)r&   r"   rP   rQ   r\   rR   r]   r#   Ú	src_shapeÚ	dst_shapeÚrÚsparse_embeddingsÚdense_embeddingsÚ
pred_masksÚpred_scoress                  r+   r[   zPredictor.prompt_inference�   sB  € ð& 48´=Ð3H�4”:×+Ò+¨BÑ/Ô/Ð/ÈdÌmˆà#œz¨!œ}¨QÔ/Ô5°b°q°bÔ9¸2¼8ÀAÀBÀB¼<�9ˆ	ØÔ#ÐfˆCˆC­¨Y°q¬\¸IÀa¼LÑ-HÈ)ÐTUÌ,ÐYbÐcdÔYeÑJeÑ)fÔ)fˆàÐÝ”_ Vµ5´=ÈÌÐUÑUÔUˆFØ%+¤[°AÒ%5Ð%5�V˜D”\�\¸6ˆFàˆ~Ýœ ¤¨a¤Ñ1Ô1�Ý”_ Vµ5´;ÀtÄ{ÐSÑSÔSˆFØ�a‰KˆFà# A A A t¨Q¨Q¨Q JÔ/°¸¸¸¸4¸´�FˆFØÐÝ”_ Vµ5´=ÈÌÐUÑUÔUˆFØ%+¤[°AÒ%5Ð%5�V˜D”\�\¸6ˆFØ�a‰KˆFØÐÝ”O Eµ´ÀtÄ{ÐSÑSÔS×]Ò]Ð^_Ñ`Ô`ˆEà%+Ð%7�&˜&Ð!Ð!¸Tˆà.2¬j×.GÒ.GÈvÐ]cÐkpÐ.GÑ.qÔ.qÑ+ÐÐ+ð #'¤*×"9Ò"9Ø%Ø”ZÔ.×;Ò;Ñ=Ô=Ø%6Ø$4Ø-ð #:ñ #
ô #
Ñˆ
�Kð ×!Ò! ! QÑ'Ô'¨×)<Ò)<¸QÀÑ)BÔ)BÐBÐBr,   r   ç¥âìÃgØÕ?r	   é    é@   ç)\�Âõ(ì?çffffffî?çffffffæ?c           
      óØ  — d| _         |j        dd…         \  }}t          ||f||¦  «        \  }}|€t          |||¦  «        }g g g g f\  }}}}t	          ||¦  «        D �]æ\  }}|\  }}}}||z
  ||z
  }}t          j        ||z  |j        ¬¦  «        }t          j	        ||gg¦  «        }t          j        |d||…||…f         ||fdd¬¦  «        }||         |z  }g g g }"}!} t          ||¦  «        D �]?\  }#|                      ||#d¬	¦  «        \  }$}%t          j        |$d         ||fdd¬¦  «        d
         }$|%|k    }&|$|&         |%|&         }%}$t          |$| j        j        |
¦  «        }'|'|	k    }&|$|&         |%|&         }%}$|$| j        j        k    }$t#          |$¦  «                             ¦   «         }(t'          |(|d
d
||g¦  «         })t          j        |)¦  «        s|(|)         |$|)         |%|)         }%}$}(|                      |$¦  «         |"                     |(¦  «         |!                     |%¦  «         �ŒAt          j        | ¦  «        } t          j        |"¦  «        }"t          j        |!¦  «        }!t.          j                             |"|!| j        j        ¦  «        }*t9          |"|*         |¦  «        }"t;          | |*         |||¦  «        } |!|*         }!|                     | ¦  «         |                     |"¦  «         |                     |!¦  «         |                     |                     t?          | ¦  «        ¦  «        ¦  «         �Œèt          j        |¦  «        }t          j        |¦  «        }t          j        |¦  «        }t          j        |¦  «        }t?          |¦  «        dk    r>d|z  }+t.          j                             ||+|¦  «        }*||*         ||*         ||*         }}}|||fS )a_  
        Perform image segmentation using the Segment Anything Model (SAM).

        This function segments an entire image into constituent parts by leveraging SAM's advanced architecture
        and real-time performance capabilities. It can optionally work on image crops for finer segmentation.

        Args:
            im (torch.Tensor): Input tensor representing the preprocessed image with dimensions (N, C, H, W).
            crop_n_layers (int): Specifies the number of layers for additional mask predictions on image crops.
                                 Each layer produces 2**i_layer number of image crops.
            crop_overlap_ratio (float): Determines the extent of overlap between crops. Scaled down in subsequent layers.
            crop_downscale_factor (int): Scaling factor for the number of sampled points-per-side in each layer.
            point_grids (list[np.ndarray], optional): Custom grids for point sampling normalized to [0,1].
                                                      Used in the nth crop layer.
            points_stride (int, optional): Number of points to sample along each side of the image.
                                           Exclusive with 'point_grids'.
            points_batch_size (int): Batch size for the number of points processed simultaneously.
            conf_thres (float): Confidence threshold [0,1] for filtering based on the model's mask quality prediction.
            stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on mask stability.
            stability_score_offset (float): Offset value for calculating stability score.
            crop_nms_thresh (float): IoU cutoff for Non-Maximum Suppression (NMS) to remove duplicate masks between crops.

        Returns:
            (tuple): A tuple containing segmented masks, confidence scores, and bounding boxes.
        Tr0   N)r;   .ÚbilinearF)r   Úalign_corners)rQ   r]   r   r	   ) r%   rj   r   r   Úzipr2   Útensorr;   r4   ÚarrayÚFÚinterpolater
   r[   r   r<   Úmask_thresholdr   r?   r   rY   ÚappendÚcatÚtorchvisionr   Únmsr    Úiour   r   ÚexpandrN   ),r&   r"   Úcrop_n_layersÚcrop_overlap_ratioÚcrop_downscale_factorÚpoint_gridsÚpoints_strideÚpoints_batch_sizeÚ
conf_thresÚstability_score_threshÚstability_score_offsetÚcrop_nms_threshÚihÚiwÚcrop_regionsÚ
layer_idxsr{   r|   Úpred_bboxesÚregion_areasÚcrop_regionÚ	layer_idxÚx1Úy1Úx2Úy2ÚwÚhÚareaÚpoints_scaleÚcrop_imÚpoints_for_imageÚ
crop_masksÚcrop_scoresÚcrop_bboxesrQ   Ú	pred_maskÚ
pred_scoreÚidxÚstability_scoreÚ	pred_bboxÚ	keep_maskÚkeepÚscoress,                                               r+   rZ   zPredictor.generateÊ   s  € ðJ  ˆÔØ”˜!˜"˜"”‰ˆˆBÝ#6¸¸B°xÀÐPbÑ#cÔ#cÑ ˆ�jØÐÝ5°mÀ]ÐTiÑjÔjˆKØ=?ÀÀRÈ¸^Ñ:ˆ
�K ¨lÝ&)¨,¸
Ñ&CÔ&Cð -	>ñ -	>Ñ"ˆK˜Ø(‰NˆB��B˜Ø˜‘7˜B ™GˆqˆAÝ”<  A¡¨b¬iÐ8Ñ8Ô8ˆDÝœ8 a¨ V HÑ-Ô-ˆLå”m B s¨B¨r¨E°2°b°5Ð'8Ô$9¸BÀ¸8È*ÐdiÐjÑjÔjˆGà*¨9Ô5¸ÑDÐØ35°r¸2 [˜ˆJÝ,Ð->Ð@PÑQÔQð /ñ /‘
�Ø(,×(=Ò(=¸gÈfÐgkÐ(=Ñ(lÔ(lÑ%�	˜:åœM¨)°D¬/¸A¸q¸6È
ÐbgÐhÑhÔhÐijÔk�	Ø  :Ò-�Ø(1°#¬¸
À3¼˜:�	å";¸IÀtÄzÔG`Ø<Rñ#Tô #T�à%Ð(>Ò>�Ø(1°#¬¸
À3¼˜:�	à%¨¬
Ô(AÒA�	å/°	Ñ:Ô:×@Ò@ÑBÔB�	Ý2°9¸kÈAÈqÐRTÐVXÈ>ÑZÔZÐZ�	Ý”y Ñ+Ô+ð yØ7@ÀÔ7KÈYÐW`ÔMaÐcmÐnwÔcx¨*˜y�Ià×!Ò! )Ñ,Ô,Ð,Ø×"Ò" 9Ñ-Ô-Ð-Ø×"Ò" :Ñ.Ô.Ð.Ñ.õ œ :Ñ.Ô.ˆJÝœ) KÑ0Ô0ˆKÝœ) KÑ0Ô0ˆKÝ”?×&Ò& {°KÀÄÄÑOÔOˆDÝ+¨K¸Ô,=¸{ÑKÔKˆKÝ% j°Ô&6¸ÀRÈÑLÔLˆJØ% dÔ+ˆKà×Ò˜jÑ)Ô)Ð)Ø×Ò˜{Ñ+Ô+Ð+Ø×Ò˜{Ñ+Ô+Ð+Ø×Ò §¢­C°
©O¬OÑ <Ô <Ñ=Ô=Ð=Ñ=å”Y˜zÑ*Ô*ˆ
Ý”i Ñ,Ô,ˆÝ”i Ñ,Ô,ˆÝ”y Ñ.Ô.ˆõ ˆ|ÑÔ˜qÒ Ð Ø˜Ñ%ˆFÝ”?×&Ò& {°F¸OÑLÔLˆDØ3=¸dÔ3CÀ[ÐQUÔEVÐXcÐdhÔXi [˜ˆJà˜;¨Ð3Ð3r,   Tc                 óV  — t          | j        j        |¬¦  «        }|€t          | j        j        ¦  «        }|                     ¦   «          |                     |¦  «        | _        || _        t          j        g d¢¦  «         	                    ddd¦  «                             |¦  «        | _
        t          j        g d¢¦  «         	                    ddd¦  «                             |¦  «        | _        d| j        _        d| j        _        d| j        _        d| j        _        d	| _        dS )
a[  
        Initializes the Segment Anything Model (SAM) for inference.

        This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary
        parameters for image normalization and other Ultralytics compatibility settings.

        Args:
            model (torch.nn.Module): A pre-trained SAM model. If None, a model will be built based on configuration.
            verbose (bool): If True, prints selected device information.

        Attributes:
            model (torch.nn.Module): The SAM model allocated to the chosen device for inference.
            device (torch.device): The device to which the model and tensors are allocated.
            mean (torch.Tensor): The mean values for image normalization.
            std (torch.Tensor): The standard deviation values for image normalization.
        )ÚverboseN)g33333ë^@gR¸…ë]@gR¸…ëáY@r.   r	   )gÃõ(\�2M@g�Âõ(\�L@g     °L@Fr~   T)r   r    r;   r   r<   Úevalr:   r2   r‡   Úviewr@   rA   ÚptÚtritonÚstrider=   Údone_warmup)r&   r<   rº   r;   s       r+   Úsetup_modelzPredictor.setup_model1  sþ   € õ" ˜tœyÔ/¸ÐAÑAÔAˆØˆ=Ý˜dœiœoÑ.Ô.ˆEØ�
Š
‰ŒˆØ—X’X˜fÑ%Ô%ˆŒ
ØˆŒÝ”LÐ!:Ð!:Ð!:Ñ;Ô;×@Ò@ÀÀQÈÑJÔJ×MÒMÈfÑUÔUˆŒ	Ý”<Ð 7Ð 7Ð 7Ñ8Ô8×=Ò=¸bÀ!ÀQÑGÔG×JÒJÈ6ÑRÔRˆŒð ˆŒ
ŒØ!ˆŒ
ÔØˆŒ
ÔØˆŒ
ŒØˆÔÐÐr,   c           
      óº  — |dd…         \  }}| j         r|d         nd}t          t          d„ t          t	          |¦  «        ¦  «        D ¦   «         ¦  «        ¦  «        }t          |t          ¦  «        st          j        |¦  «        }g }t          |g¦  «        D �]8\  }	}
||	         }|�œt          j	        |j
        dd…         |                     ¦   «         |j
        d¬¦  «        }t          j        t	          |¦  «        t          j        |j        ¬¦  «        }t          j        ||dd…df         |dd…df         gd¬¦  «        }t          j        |
d                              ¦   «         |j
        dd…         d¬¦  «        d	         }
|
| j        j        k    }
| j        d	         |	         }|                     t-          ||||
|¬
¦  «        ¦  «         �Œ:d| _         |S )að  
        Post-processes SAM's inference outputs to generate object detection masks and bounding boxes.

        The method scales masks and boxes to the original image size and applies a threshold to the mask predictions. The
        SAM model uses advanced architecture and promptable segmentation tasks to achieve real-time performance.

        Args:
            preds (tuple): The output from SAM model inference, containing masks, scores, and optional bounding boxes.
            img (torch.Tensor): The processed input image tensor.
            orig_imgs (list | torch.Tensor): The original, unprocessed images.

        Returns:
            (list): List of Results objects containing detection masks, bounding boxes, and other metadata.
        Nr0   c              3   ó4   K  — | ]}t          |¦  «        V — Œd S rT   )ÚstrrU   s     r+   rW   z(Predictor.postprocess.<locals>.<genexpr>d  s(   è è € ÐFÐF¨!�s 1™vœvÐFÐFÐFÐFÐFÐFr,   F)Úpaddingra   r.   ©Údimr   )ÚpathÚnamesrR   rc   )r%   r   Ú	enumerateÚrangerN   r1   Úlistr   Úconvert_torch2numpy_batchÚscale_boxesrj   r?   r2   Úarangerp   r;   r�   Úscale_masksr<   r‹   ri   rŒ   r   )r&   ÚpredsÚimgÚ	orig_imgsr{   r|   r    rÉ   ÚresultsrV   rR   Úorig_imgÚclsÚimg_paths                 r+   ÚpostprocesszPredictor.postprocessR  sÎ  € ð  #(¨¨¨¤)Ñˆ
�KØ"&Ô"2Ð<�e˜A”h�h¸ˆÝ•YÐFÐF­uµS¸±_´_Ñ/EÔ/EÐFÑFÔFÑFÔFÑGÔGˆå˜)¥TÑ*Ô*ð 	AÝÔ5°iÑ@Ô@ˆIàˆÝ! : ,Ñ/Ô/ð 
	jñ 
	j‰HˆAˆuØ  ”|ˆHØÐ&Ý!œo¨c¬i¸¸¸¬m¸[×=NÒ=NÑ=PÔ=PÐRZÔR`ÐjoÐpÑpÔp�Ý”l¥3 z¡?¤?½%¼+ÈjÔN_Ð`Ñ`Ô`�Ý#œi¨°kÀ!À!À!ÀTÀ'Ô6JÈCÐPQÐPQÐPQÐSWÐPWÌLÐ(YÐ_aÐbÑbÔb�å”O E¨$¤K×$5Ò$5Ñ$7Ô$7¸¼ÈÈÈÔ9KÐUZÐ[Ñ[Ô[Ð\]Ô^ˆEØ˜DœJÔ5Ò5ˆEØ”z !”} QÔ'ˆHØ�NŠN�7 8°(À%ÈuÐ\gÐhÑhÔhÑiÔiÐiÑià ˆÔØˆr,   c                 óR   •— |�#t          ¦   «                              |¦  «         dS dS )aW  
        Sets up the data source for inference.

        This method configures the data source from which images will be fetched for inference. The source could be a
        directory, a video file, or other types of image data sources.

        Args:
            source (str | Path): The path to the image data source for inference.
        N)r   Úsetup_source)r&   Úsourcer*   s     €r+   rÚ   zPredictor.setup_sourcey  s1   ø€ ð ÐÝ‰GŒG× Ò  Ñ(Ô(Ð(Ð(Ð(ð Ðr,   c                 óx  — | j         €.t          | j        j         ¦  «        }|                      |¦  «         |                      |¦  «         t          | j        ¦  «        dk    s
J d¦   «         ‚| j        D ]E}|                      |d         ¦  «        }| j                              |¦  «        | _	        || _
         dS dS )aÞ  
        Preprocesses and sets a single image for inference.

        This function sets up the model if not already initialized, configures the data source to the specified image,
        and preprocesses the image for feature extraction. Only one image can be set at a time.

        Args:
            image (str | np.ndarray): Image file path as a string, or a np.ndarray image read by cv2.

        Raises:
            AssertionError: If more than one image is set.
        Nr	   z,`set_image` only supports setting one image!)r<   r   r    rÁ   rÚ   rN   ÚdatasetrC   rh   r#   r"   )r&   rH   r<   ri   r"   s        r+   Ú	set_imagezPredictor.set_image†  s¾   € ð Œ:ÐÝ˜dœiœoÑ.Ô.ˆEØ×Ò˜UÑ#Ô#Ð#Ø×Ò˜%Ñ Ô Ð Ý�4”<Ñ Ô  AÒ%Ð%Ð%Ð'UÑ%Ô%Ð%Ø”\ð 	ð 	ˆEØ—’  q¤Ñ*Ô*ˆBØ œJ×4Ò4°RÑ8Ô8ˆDŒMØˆDŒGØˆEˆEð		ð 	r,   c                 ó   — || _         dS )zSet prompts in advance.N)r$   )r&   r$   s     r+   Úset_promptszPredictor.set_promptsž  s   € àˆŒˆˆr,   c                 ó"   — d| _         d| _        dS )z*Resets the image and its features to None.N)r"   r#   )r&   s    r+   Úreset_imagezPredictor.reset_image¢  s   € àˆŒØˆŒˆˆr,   c                 ó  — t          | ¦  «        dk    r| S g }g }| D ]Ó}|                     ¦   «                              ¦   «                              t          j        ¦  «        }t          ||d¬¦  «        \  }}| }t          ||d¬¦  «        \  }}|o| }|                     t          j	        |¦  «         
                    d¦  «        ¦  «         |                     t          |¦  «        ¦  «         ŒÔt          j        |d¬¦  «        }t          |¦  «        }t          j                             |                     ¦   «         t          j	        |¦  «        |¦  «        }	||	                              | j        | j        ¬¦  «        |	fS )a  
        Perform post-processing on segmentation masks generated by the Segment Anything Model (SAM). Specifically, this
        function removes small disconnected regions and holes from the input masks, and then performs Non-Maximum
        Suppression (NMS) to eliminate any newly created duplicate boxes.

        Args:
            masks (torch.Tensor): A tensor containing the masks to be processed. Shape should be (N, H, W), where N is
                                  the number of masks, H is height, and W is width.
            min_area (int): The minimum area below which disconnected regions and holes will be removed. Defaults to 0.
            nms_thresh (float): The IoU threshold for the NMS algorithm. Defaults to 0.7.

        Returns:
            (tuple([torch.Tensor, List[int]])):
                - new_masks (torch.Tensor): The processed masks with small regions removed. Shape is (N, H, W).
                - keep (List[int]): The indices of the remaining masks post-NMS, which can be used to filter the boxes.
        r   Úholes)r   ÚislandsrÆ   )r;   rb   )rN   ÚcpuÚnumpyÚastyper4   Úuint8r   rŒ   r2   rl   rq   r?   r�   r   rŽ   r   r�   r:   r;   rb   )
rR   Úmin_areaÚ
nms_threshÚ	new_masksr¸   ÚmaskÚchangedÚ	unchangedrc   r·   s
             r+   r   zPredictor.remove_small_regions§  s\  € õ$ ˆu‰:Œ:˜Š?ˆ?ØˆLð ˆ	ØˆØð 		,ð 		,ˆDØ—8’8‘:”:×#Ò#Ñ%Ô%×,Ò,­R¬XÑ6Ô6ˆDÝ0°°xÀgÐNÑNÔN‰MˆD�'Ø#˜ˆIÝ0°°xÀiÐPÑPÔP‰MˆD�'Ø!Ð1¨' kˆIà×Ò�Uœ_¨TÑ2Ô2×<Ò<¸QÑ?Ô?Ñ@Ô@Ð@à�MŠM�% 	Ñ*Ô*Ñ+Ô+Ð+Ð+õ ”I˜i¨QÐ/Ñ/Ô/ˆ	Ý# IÑ.Ô.ˆÝŒ×"Ò" 5§;¢;¡=¤=µ%´/À&Ñ2IÔ2IÈ:ÑVÔVˆà˜Œ×!Ò!¨¬¸U¼[Ð!ÑIÔIÈ4ÐOÐOr,   )NNNNF)
r   r}   r	   Nr~   r   r€   r�   r�   r‚   )T)r   r‚   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   rC   r6   r_   r[   rZ   rÁ   rØ   rÚ   rÞ   rà   râ   Ústaticmethodr   Ú__classcell__)r*   s   @r+   r   r      sk  ø€ € € € € ðð ð& '°$À4ð !ð !ð !ð !ð !ð !ð,ð ð ð80ð 0ð 0ð"Zð Zð Zð Zð<8Cð 8Cð 8Cð 8Cðx  !Ø$.Ø'(Ø!Ø!Ø#%Ø Ø(,Ø(,Ø!$ðe4ð e4ð e4ð e4ðN ð  ð  ð  ðB%ð %ð %ðN)ð )ð )ð )ð )ðð ð ð0ð ð ðð ð ð
 ð'Pð 'Pð 'Pñ „\ð'Pð 'Pð 'Pð 'Pð 'Pr,   r   )!ró   rç   r4   r2   Útorch.nn.functionalÚnnÚ
functionalr‰   rŽ   Úultralytics.data.augmentr   Úultralytics.engine.predictorr   Úultralytics.engine.resultsr   Úultralytics.utilsr   r   Úultralytics.utils.torch_utilsr   Úamgr
   r   r   r   r   r   r   r   r   Úbuildr   r   rI   r,   r+   ú<module>r      s‹  ððð ð Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð Ø Ð Ð Ð à .Ð .Ð .Ð .Ð .Ð .Ø 6Ð 6Ð 6Ð 6Ð 6Ð 6Ø .Ð .Ð .Ð .Ð .Ð .Ø .Ð .Ð .Ð .Ð .Ð .Ð .Ð .Ø 7Ð 7Ð 7Ð 7Ð 7Ð 7ðuð uð uð uð uð uð uð uð uð uð uð uð uð uð uð uð uð uð uð uð uð uà Ð Ð Ð Ð Ð ðtPð tPð tPð tPð tP�ñ tPô tPð tPð tPð tPr,   