a
    yfЖ                     @   s   d Z ddlZddlZddlm  m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 deZG d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                
       s   e Zd ZdZeddf fdd	Zdd Zdd Zd+d
dZd,ddZ	d-ddZ
d.ddZdd Zdd Z fdd Zd!d" Zd#d$ Zd%d& Zd'd( Zed/d)d*Z  ZS )0	Predictora	  
    Predictor class for SAM, enabling real-time image segmentation with promptable capabilities.

    This class extends BasePredictor and implements the Segment Anything Model (SAM) for advanced image
    segmentation tasks. It supports various input prompts like points, bounding boxes, and masks for
    fine-grained control over segmentation results.

    Attributes:
        args (SimpleNamespace): Configuration arguments for the predictor.
        model (torch.nn.Module): The loaded SAM model.
        device (torch.device): The device (CPU or GPU) on which the model is loaded.
        im (torch.Tensor): The preprocessed input image.
        features (torch.Tensor): Extracted image features.
        prompts (Dict): Dictionary to store various types of prompts (e.g., bboxes, points, masks).
        segment_all (bool): Flag to indicate if full image segmentation should be performed.
        mean (torch.Tensor): Mean values for image normalization.
        std (torch.Tensor): Standard deviation values for image normalization.

    Methods:
        preprocess: Prepares input images for model inference.
        pre_transform: Performs initial transformations on the input image.
        inference: Performs segmentation inference based on input prompts.
        prompt_inference: Internal function for prompt-based segmentation inference.
        generate: Generates segmentation masks for an entire image.
        setup_model: Initializes the SAM model for inference.
        get_model: Builds and returns a SAM model.
        postprocess: Post-processes model outputs to generate final results.
        setup_source: Sets up the data source for inference.
        set_image: Sets and preprocesses a single image for inference.
        get_im_features: Extracts image features using the SAM image encoder.
        set_prompts: Sets prompts for subsequent inference.
        reset_image: Resets the current image and its features.
        remove_small_regions: Removes small disconnected regions and holes from masks.

    Examples:
        >>> predictor = Predictor()
        >>> predictor.setup_model(model_path="sam_model.pt")
        >>> predictor.set_image("image.jpg")
        >>> masks, scores, boxes = predictor.generate()
        >>> results = predictor.postprocess((masks, scores, boxes), im, orig_img)
    Nc                    sR   |du ri }| tddd t ||| d| j_d| _d| _i | _d| _	dS )aP  
        Initialize the Predictor with configuration, overrides, and callbacks.

        Sets up the Predictor object for SAM (Segment Anything Model) and applies any configuration overrides or
        callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True
        for optimal results.

        Args:
            cfg (Dict): Configuration dictionary containing default settings.
            overrides (Dict | None): Dictionary of values to override default configuration.
            _callbacks (Dict | None): Dictionary of callback functions to customize behavior.

        Examples:
            >>> predictor = Predictor(cfg=DEFAULT_CFG)
            >>> predictor = Predictor(overrides={"imgsz": 640})
            >>> predictor = Predictor(_callbacks={"on_predict_start": custom_callback})
        NsegmentZpredict)taskmodeTF)
updatedictsuper__init__argsZretina_masksimfeaturespromptssegment_all)selfcfgZ	overrides
_callbacks	__class__ Z/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/models/sam/predict.pyr   N   s    zPredictor.__init__c                 C   s   | j dur| j S t|tj }|r^t| |}|ddddf d}t|}t	|}|
| j}| jjrz| n| }|r|| j | j }|S )a  
        Preprocess the input image for model inference.

        This 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]): Input image(s) in BCHW tensor format or list of HWC numpy arrays.

        Returns:
            (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.

        Examples:
            >>> predictor = Predictor()
            >>> image = torch.rand(1, 3, 640, 640)
            >>> preprocessed_image = predictor.preprocess(image)
        N.)r      r      )r   
isinstancetorchZTensornpstackpre_transformZ	transposeZascontiguousarrayZ
from_numpytodevicemodelfp16Zhalffloatmeanstd)r    r   Z
not_tensorr%   r%   r&   
preprocessj   s    


zPredictor.preprocessc                    s8   t |dksJ dt| jjddd  fdd|D S )a9  
        Perform initial transformations on the input image for preprocessing.

        This 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 a single image in HWC numpy array format.

        Returns:
            (List[np.ndarray]): List containing the transformed image.

        Raises:
            AssertionError: If the input list contains more than one image.

        Examples:
            >>> predictor = Predictor()
            >>> image = np.random.rand(480, 640, 3)  # Single HWC image
            >>> transformed = predictor.pre_transform([image])
            >>> print(len(transformed))
            1
        r   z6SAM model does not currently support batched inferenceF)autocenterc                    s   g | ]} |d qS ))imager%   .0xZ	letterboxr%   r&   
<listcomp>       z+Predictor.pre_transform.<locals>.<listcomp>)lenr   r   imgszr    r   r%   r=   r&   r.      s    zPredictor.pre_transformFc           	      O   s|   | j d|}| j d|}| j d|}| j d|}tdd |||fD rh| 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 | None): Bounding boxes with shape (N, 4), in XYXY format.
            points (np.ndarray | List | None): Points indicating object locations with shape (N, 2), in pixels.
            labels (np.ndarray | List | None): Labels for point prompts, shape (N,). 1 = foreground, 0 = background.
            masks (np.ndarray | None): Low-resolution masks from previous predictions, shape (N, H, W). For SAM H=W=256.
            multimask_output (bool): Flag to return multiple masks. Helpful for ambiguous prompts.
            *args (Any): Additional positional arguments.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            (tuple): Contains the following three elements:
                - np.ndarray: The output masks in shape (C, H, W), 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 (C, H, W) for subsequent inference, where H=W=256.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.setup_model(model_path="sam_model.pt")
            >>> predictor.set_image("image.jpg")
            >>> masks, scores, logits = predictor.inference(im, bboxes=[[0, 0, 100, 100]])
        bboxespointsmaskslabelsc                 s   s   | ]}|d u V  qd S Nr%   r;   ir%   r%   r&   	<genexpr>   r?   z&Predictor.inference.<locals>.<genexpr>)r   popallgenerateprompt_inference)	r    r   rC   rD   rF   rE   multimask_outputr   kwargsr%   r%   r&   	inference   s    zPredictor.inferencec                 C   s  | j du r| |n| j }| jd d jdd |jdd  }}	| jrLdn t|	d |d  |	d |d  }
|du rtj|tj| j	d}|j
dkr|d n|}|du rt|jd }tj|tj| j	d}||
9 }|dddddf |dddf  }}|dur<tj|tj| j	d}|j
dkr0|d n|}||
9 }|dur`tj|tj| j	dd}|durr||fnd}| jj|||d\}}| jj|| jj |||d\}}|dd|ddfS )	aF  
        Performs image segmentation inference based on input cues using SAM's specialized architecture.

        This internal function leverages the Segment Anything Model (SAM) for prompt-based, real-time segmentation.
        It processes various input prompts such as bounding boxes, points, and masks to generate segmentation masks.

        Args:
            im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
            bboxes (np.ndarray | List | None): Bounding boxes in XYXY format with shape (N, 4).
            points (np.ndarray | List | None): Points indicating object locations with shape (N, 2), in pixels.
            labels (np.ndarray | List | None): Point prompt labels with shape (N,). 1 for foreground, 0 for background.
            masks (np.ndarray | None): Low-res masks from previous predictions with shape (N, H, W). For SAM, H=W=256.
            multimask_output (bool): Flag to return multiple masks for ambiguous prompts.

        Returns:
            (tuple): Tuple containing:
                - np.ndarray: Output masks with shape (C, H, W), where C is the number of generated masks.
                - np.ndarray: Quality scores predicted by the model for each mask, with length C.
                - np.ndarray: Low-resolution logits with shape (C, H, W) for subsequent inference, where H=W=256.

        Examples:
            >>> predictor = Predictor()
            >>> im = torch.rand(1, 3, 1024, 1024)
            >>> bboxes = [[100, 100, 200, 200]]
            >>> masks, scores, logits = predictor.prompt_inference(im, bboxes=bboxes)
        Nr   r   r)         ?dtyper0   rD   boxesrE   )image_embeddingsimage_pesparse_prompt_embeddingsdense_prompt_embeddingsrO   )r   get_im_featuresbatchshaper   minr+   	as_tensorfloat32r0   ndimr,   onesint32	unsqueezer1   Zprompt_encoderZmask_decoderget_dense_peflatten)r    r   rC   rD   rF   rE   rO   r   	src_shape	dst_shapersparse_embeddingsdense_embeddings
pred_maskspred_scoresr%   r%   r&   rN      s6    (,
(




zPredictor.prompt_inferencer   g?r       @   )\(?ffffff?ffffff?c           -   	   C   s  ddl }d| _|jdd \}}t||f||\}}|du rHt|||}g g g g f\}}}}t||D ]\}}|\}}}}|| ||  }}tj|| |jd}t	
||gg}tj|d||||f ||fddd	}|| | } g g g   }!}"}#t|| D ]\}$| j||$dd
\}%}&tj|%d ||fddd	d }%|&|k}'|%|' |&|'  }%}&t|%| jj|
}(|(|	k}'|%|' |&|'  }%}&|%| jjk}%t|% })t|)|dd||g }*t|*s|)|* |%|* |&|*   })}%}&|!|% |#|) |"|& q t|!}!t|#}#t|"}"|j|#|"| jj}+t|#|+ |}#t|!|+ |||}!|"|+ }"||! ||# ||" ||t|! qft|}t|}t|}t|}t|dkrd| },|j||,|}+||+ ||+ ||+   }}}|||fS )a  
        Perform image segmentation using the Segment Anything Model (SAM).

        This method 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 shape (N, C, H, W).
            crop_n_layers (int): Number of layers for additional mask predictions on image crops.
            crop_overlap_ratio (float): Overlap between crops, scaled down in subsequent layers.
            crop_downscale_factor (int): Scaling factor for sampled points-per-side in each layer.
            point_grids (List[np.ndarray] | None): Custom grids for point sampling normalized to [0,1].
            points_stride (int): Number of points to sample along each side of the image.
            points_batch_size (int): Batch size for the number of points processed simultaneously.
            conf_thres (float): Confidence threshold [0,1] for filtering based on mask quality prediction.
            stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on stability.
            stability_score_offset (float): Offset value for calculating stability score.
            crop_nms_thresh (float): IoU cutoff for NMS to remove duplicate masks between crops.

        Returns:
            (Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): A tuple containing:
                - pred_masks (torch.Tensor): Segmented masks with shape (N, H, W).
                - pred_scores (torch.Tensor): Confidence scores for each mask with shape (N,).
                - pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 4).

        Examples:
            >>> predictor = Predictor()
            >>> im = torch.rand(1, 3, 1024, 1024)  # Example input image
            >>> masks, scores, boxes = predictor.generate(im)
        r   NTr)   )r0   .ZbilinearF)r   Zalign_corners)rD   rO   r   ) torchvisionr   r]   r   r   zipr+   tensorr0   r,   arrayFZinterpolater	   rN   r   r1   mask_thresholdr
   r3   r   rL   appendcatr   nmsr   Ziour   r   expandr@   )-r    r   Zcrop_n_layersZcrop_overlap_ratioZcrop_downscale_factorZpoint_gridsZpoints_strideZpoints_batch_sizeZ
conf_thresZstability_score_threshZstability_score_offsetZcrop_nms_threshrt   ZihiwZcrop_regionsZ
layer_idxsrl   rm   pred_bboxesZregion_areasZcrop_regionZ	layer_idxx1y1Zx2y2whZareaZpoints_scaleZcrop_imZpoints_for_imageZ
crop_masksZcrop_scoresZcrop_bboxesrD   Z	pred_maskZ
pred_scoreidxZstability_scoreZ	pred_bboxZ	keep_maskkeepscoresr%   r%   r&   rM     sj    ,(












zPredictor.generateTc                 C   s   t | jj|d}|du r |  }|  ||| _|| _tg d	ddd|| _
tg d	ddd|| _d| j_d| j_d| j_d| j_d	| _dS )
ah  
        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.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.setup_model(model=sam_model, verbose=True)
        )verboseN)g33333^@gR]@gRY@r'   r   )g(\2M@g(\L@g     L@Fro   T)r   r   r0   	get_modelevalr/   r1   r+   rv   viewr4   r5   ptZtritonZstrider2   Zdone_warmup)r    r1   r   r0   r%   r%   r&   setup_model  s      zPredictor.setup_modelc                 C   s   t | jjS )zRRetrieves or builds the Segment Anything Model (SAM) for image segmentation tasks.r   r   r1   r    r%   r%   r&   r     s    zPredictor.get_modelc              
   C   sV  |dd \}}| j r|d nd}ttdd tt|D }t|tsTt|}g }t	|g|| j
d D ]\}	}
}t|	dkrd}	ntj|	d  |
jdd ddd }	|	| jjk}	|durtj|jdd | |
jdd}nt|	}tjt|tj|jd}tj||dddf |dddf gd	d
}|t|
|||	|d qld| _ |S )a  
        Post-processes SAM's inference outputs to generate object detection masks and bounding boxes.

        This method scales masks and boxes to the original image size and applies a threshold to the mask
        predictions. It leverages SAM's advanced architecture for real-time, promptable segmentation tasks.

        Args:
            preds (Tuple[torch.Tensor]): The output from SAM model inference, containing:
                - pred_masks (torch.Tensor): Predicted masks with shape (N, 1, H, W).
                - pred_scores (torch.Tensor): Confidence scores for each mask with shape (N, 1).
                - pred_bboxes (torch.Tensor, optional): Predicted bounding boxes if segment_all is True.
            img (torch.Tensor): The processed input image tensor with shape (C, H, W).
            orig_imgs (List[np.ndarray] | torch.Tensor): The original, unprocessed images.

        Returns:
            (List[Results]): List of Results objects containing detection masks, bounding boxes, and other
                metadata for each processed image.

        Examples:
            >>> predictor = Predictor()
            >>> preds = predictor.inference(img)
            >>> results = predictor.postprocess(preds, img, orig_imgs)
        Nr)   c                 s   s   | ]}t |V  qd S rG   )strrH   r%   r%   r&   rJ     r?   z(Predictor.postprocess.<locals>.<genexpr>r   F)paddingrS   r'   dim)pathnamesrE   rV   )r   r   	enumerateranger@   r*   listr   Zconvert_torch2numpy_batchru   r\   Zscale_masksr3   r]   r1   ry   Zscale_boxesr
   r+   Zarangerc   r0   r{   rz   r   )r    predsZimgZ	orig_imgsrl   rm   r   r   resultsrE   Zorig_imgZimg_pathclsr%   r%   r&   postprocess  s&    

&$,zPredictor.postprocessc                    s   |durt  | dS )a  
        Sets up the data source for inference.

        This method configures the data source from which images will be fetched for inference. It supports
        various input types such as image files, directories, video files, and other compatible data sources.

        Args:
            source (str | Path | None): The path or identifier for the image data source. Can be a file path,
                directory path, URL, or other supported source types.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.setup_source("path/to/images")
            >>> predictor.setup_source("video.mp4")
            >>> predictor.setup_source(None)  # Uses default source if available

        Notes:
            - If source is None, the method may use a default source if configured.
            - The method adapts to different source types and prepares them for subsequent inference steps.
            - Supported source types may include local files, directories, URLs, and video streams.
        N)r   setup_source)r    sourcer#   r%   r&   r     s    zPredictor.setup_sourcec                 C   sd   | j du r| jdd | | t| jdks6J d| jD ]"}| |d }| || _ q`q<dS )a  
        Preprocesses and sets a single image for inference.

        This method prepares the model for inference on a single image by setting up the model if not already
        initialized, configuring the data source, and preprocessing the image for feature extraction. It
        ensures that only one image is set at a time and extracts image features for subsequent use.

        Args:
            image (str | np.ndarray): Path to the image file as a string, or a numpy array representing
                an image read by cv2.

        Raises:
            AssertionError: If more than one image is attempted to be set.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.set_image("path/to/image.jpg")
            >>> predictor.set_image(cv2.imread("path/to/image.jpg"))

        Notes:
            - This method should be called before performing inference on a new image.
            - The extracted features are stored in the `self.features` attribute for later use.
        Nr1   r   ,`set_image` only supports setting one image!r1   r   r   r@   Zdatasetr6   r[   r   r    r9   r\   r   r%   r%   r&   	set_image  s    


zPredictor.set_imagec                 C   sP   t | jttfr$| jd | jd ks6J d| j d| j| j | j|S )z[Extracts image features using the SAM model's image encoder for subsequent mask prediction.r   r   z3SAM models only support square image size, but got .)r*   rA   tupler   r1   	set_imgszZimage_encoderrB   r%   r%   r&   r[     s    zPredictor.get_im_featuresc                 C   s
   || _ dS )z1Sets prompts for subsequent inference operations.N)r   )r    r   r%   r%   r&   set_prompts  s    zPredictor.set_promptsc                 C   s   d| _ d| _dS )zRResets the current image and its features, clearing them for subsequent inference.N)r   r   r   r%   r%   r&   reset_image  s    zPredictor.reset_imagec                 C   s   ddl }t| dkr| S g }g }| D ]p}|  tj}t||dd\}}| }t||dd\}}|on| }|t	
|d |t| q$t	j|dd}t|}	|j|	 t	
||}
||
 j| j| jd|
fS )a  
        Remove small disconnected regions and holes from segmentation masks.

        This function performs post-processing on segmentation masks generated by the Segment Anything Model (SAM).
        It 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): Segmentation masks to be processed, with shape (N, H, W) where N is the number of
                masks, H is height, and W is width.
            min_area (int): Minimum area threshold for removing disconnected regions and holes. Regions smaller than
                this will be removed.
            nms_thresh (float): IoU threshold for the NMS algorithm to remove duplicate boxes.

        Returns:
            (tuple):
                - new_masks (torch.Tensor): Processed masks with small regions removed, shape (N, H, W).
                - keep (List[int]): Indices of remaining masks after NMS, for filtering corresponding boxes.

        Examples:
            >>> masks = torch.rand(5, 640, 640) > 0.5  # 5 random binary masks
            >>> new_masks, keep = remove_small_regions(masks, min_area=100, nms_thresh=0.7)
            >>> print(f"Original masks: {masks.shape}, Processed masks: {new_masks.shape}")
            >>> print(f"Indices of kept masks: {keep}")
        r   NZholes)r   Zislandsr   )r0   rT   )rt   r@   cpunumpyZastyper,   Zuint8r   rz   r+   r_   rd   r3   r{   r
   r   r|   r/   r0   rT   )rE   Zmin_areaZ
nms_threshrt   Z	new_masksr   maskchangedZ	unchangedrV   r   r%   r%   r&   r   "  s"    
zPredictor.remove_small_regions)NNNNF)NNNNF)
r   rn   r   Nro   rp   rq   rr   rr   rs   )T)r   rs   )__name__
__module____qualname____doc__r   r   r6   r.   rQ   rN   rM   r   r   r   r   r   r[   r   r   staticmethodr   __classcell__r%   r%   r#   r&   r   #   s6   *!
(
E          
q
3!r   c                   @   s:   e Zd ZdZg dZdd Zddd	Zd
d Zdd ZdS )SAM2Predictora  
    SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture.

    This class extends the base Predictor class to implement SAM2-specific functionality for image
    segmentation tasks. It provides methods for model initialization, feature extraction, and
    prompt-based inference.

    Attributes:
        _bb_feat_sizes (List[Tuple[int, int]]): Feature sizes for different backbone levels.
        model (torch.nn.Module): The loaded SAM2 model.
        device (torch.device): The device (CPU or GPU) on which the model is loaded.
        features (Dict[str, torch.Tensor]): Cached image features for efficient inference.
        segment_all (bool): Flag to indicate if all segments should be predicted.
        prompts (Dict): Dictionary to store various types of prompts for inference.

    Methods:
        get_model: Retrieves and initializes the SAM2 model.
        prompt_inference: Performs image segmentation inference based on various prompts.
        set_image: Preprocesses and sets a single image for inference.
        get_im_features: Extracts and processes image features using SAM2's image encoder.

    Examples:
        >>> predictor = SAM2Predictor(cfg)
        >>> predictor.set_image("path/to/image.jpg")
        >>> bboxes = [[100, 100, 200, 200]]
        >>> masks, scores, _ = predictor.prompt_inference(predictor.im, bboxes=bboxes)
        >>> print(f"Predicted {len(masks)} masks with average score {scores.mean():.2f}")
    ))   r   )   r   )rp   rp   c                 C   s   t | jjS )z[Retrieves and initializes the Segment Anything Model 2 (SAM2) for image segmentation tasks.r   r   r%   r%   r&   r   |  s    zSAM2Predictor.get_modelNFr'   c              	      sp  | j du r| |n| j }| jd d jdd |jdd  }	}
| jrLdn t|
d |	d  |
d |	d  }|durtj|tj| j	d}|j
dkr|d n|}|du rt|jd }tj|tj| j	d}||9 }|dddf |dddf  }}|durtj|tj| j	d}|j
dkr(|d n|}|ddd| }tjddggtj|j	dt|d}|durtj||gdd	}tj||gdd	}n
|| }}|durtj|tj| j	dd}|dur||fnd}| jj|d|d
\}}|duo|d jd dk} fdd|d D }| jj|d   d| jj |||||d\}}}}|dd|ddfS )a  
        Performs image segmentation inference based on various prompts using SAM2 architecture.

        This method leverages the Segment Anything Model 2 (SAM2) to generate segmentation masks for input images
        based on provided prompts such as bounding boxes, points, or existing masks. It supports both single and
        multi-object prediction scenarios.

        Args:
            im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
            bboxes (np.ndarray | List[List[float]] | None): Bounding boxes in XYXY format with shape (N, 4).
            points (np.ndarray | List[List[float]] | None): Object location points with shape (N, 2), in pixels.
            labels (np.ndarray | List[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background.
            masks (np.ndarray | None): Low-resolution masks from previous predictions with shape (N, H, W).
            multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
            img_idx (int): Index of the image in the batch to process.

        Returns:
            (tuple): Tuple containing:
                - np.ndarray: Output masks with shape (C, H, W), where C is the number of generated masks.
                - np.ndarray: Quality scores for each mask, with length C.
                - np.ndarray: Low-resolution logits with shape (C, 256, 256) for subsequent inference.

        Examples:
            >>> predictor = SAM2Predictor(cfg)
            >>> image = torch.rand(1, 3, 640, 640)
            >>> bboxes = [[100, 100, 200, 200]]
            >>> masks, scores, logits = predictor.prompt_inference(image, bboxes=bboxes)
            >>> print(f"Generated {masks.shape[0]} masks with average score {scores.mean():.2f}")

        Notes:
            - The method supports batched inference for multiple objects when points or bboxes are provided.
            - Input prompts (bboxes, points) are automatically scaled to match the input image dimensions.
            - When both bboxes and points are provided, they are merged into a single 'points' input for the model.

        References:
            - SAM2 Paper: [Add link to SAM2 paper when available]
        Nr   r   r)   rR   rS   r'   r(   r   rU   c                    s   g | ]}|   d qS )r   )rd   )r;   Z
feat_levelimg_idxr%   r&   r>     r?   z2SAM2Predictor.prompt_inference.<locals>.<listcomp>high_res_featsimage_embed)rW   rX   rY   rZ   rO   Zrepeat_imagehigh_res_features)r   r[   r\   r]   r   r^   r+   r_   r`   r0   ra   rb   rc   r   rv   r}   r@   r{   rd   r1   Zsam_prompt_encoderZsam_mask_decoderre   rf   )r    r   rC   rD   rF   rE   rO   r   r   rg   rh   ri   Zbbox_labelsrj   rk   Zbatched_moder   rl   rm   _r%   r   r&   rN     sP    /(,"
&




zSAM2Predictor.prompt_inferencec                 C   sd   | j du r| jdd | | t| jdks6J d| jD ]"}| |d }| || _ q`q<dS )a#  
        Preprocesses and sets a single image for inference using the SAM2 model.

        This method initializes the model if not already done, configures the data source to the specified image,
        and preprocesses the image for feature extraction. It supports setting only one image at a time.

        Args:
            image (str | np.ndarray): Path to the image file as a string, or a numpy array representing the image.

        Raises:
            AssertionError: If more than one image is attempted to be set.

        Examples:
            >>> predictor = SAM2Predictor()
            >>> predictor.set_image("path/to/image.jpg")
            >>> predictor.set_image(np.array([...]))  # Using a numpy array

        Notes:
            - This method must be called before performing any inference on a new image.
            - The method caches the extracted features for efficient subsequent inferences on the same image.
            - Only one image can be set at a time. To process multiple images, call this method for each new image.
        Nr   r   r   r   r   r%   r%   r&   r     s    


zSAM2Predictor.set_imagec                    s   t  jttfr$ jd  jd ks6J d j d j j  fdddD  _ j|} j|\}}}} jj	r|d  jj
 |d< d	d t|d
d
d  jd
d
d D d
d
d }|d |d
d dS )zMExtracts image features from the SAM image encoder for subsequent processing.r   r   z5SAM 2 models only support square image size, but got r   c                    s    g | ]  fd dj D qS )c                    s   g | ]}|d    qS )   r%   r:   rI   r%   r&   r>   
  r?   z<SAM2Predictor.get_im_features.<locals>.<listcomp>.<listcomp>)rA   )r;   r   r   r&   r>   
  r?   z1SAM2Predictor.get_im_features.<locals>.<listcomp>)r   r)   r   r'   c                 S   s.   g | ]&\}}| d ddjd dg|R  qS )r   r)   r   r'   )Zpermuter   )r;   ZfeatZ	feat_sizer%   r%   r&   r>     s   N)r   r   )r*   rA   r   r   r1   r   _bb_feat_sizesZforward_imageZ_prepare_backbone_featuresZdirectly_add_no_mem_embedZno_mem_embedru   )r    r   Zbackbone_outr   Zvision_featsZfeatsr%   r   r&   r[     s$    zSAM2Predictor.get_im_features)NNNNFr'   )	r   r   r   r   r   r   rN   r   r[   r%   r%   r%   r&   r   X  s         
d r   )!r   r   r,   r+   Ztorch.nn.functionalnnZ
functionalrx   Zultralytics.data.augmentr   Zultralytics.engine.predictorr   Zultralytics.engine.resultsr   Zultralytics.utilsr   r   Zultralytics.utils.torch_utilsr   Zamgr	   r
   r   r   r   r   r   r   r   buildr   r   r   r%   r%   r%   r&   <module>   s    	,    9