
    |h                     B    d dl mZ d dlmZ d dlmZmZ  G d de      Zy)    )Results)DetectionPredictor)DEFAULT_CFGopsc                   @     e Zd ZdZeddf fd	Z fdZd Zd Z xZ	S )SegmentationPredictora  
    A class extending the DetectionPredictor class for prediction based on a segmentation model.

    This class specializes in processing segmentation model outputs, handling both bounding boxes and masks in the
    prediction results.

    Attributes:
        args (dict): Configuration arguments for the predictor.
        model (torch.nn.Module): The loaded YOLO segmentation model.
        batch (list): Current batch of images being processed.

    Methods:
        postprocess: Apply non-max suppression and process segmentation detections.
        construct_results: Construct a list of result objects from predictions.
        construct_result: Construct a single result object from a prediction.

    Examples:
        >>> from ultralytics.utils import ASSETS
        >>> from ultralytics.models.yolo.segment import SegmentationPredictor
        >>> args = dict(model="yolo11n-seg.pt", source=ASSETS)
        >>> predictor = SegmentationPredictor(overrides=args)
        >>> predictor.predict_cli()
    Nc                 J    t         |   |||       d| j                  _        y)a  
        Initialize the SegmentationPredictor with configuration, overrides, and callbacks.

        This class specializes in processing segmentation model outputs, handling both bounding boxes and masks in the
        prediction results.

        Args:
            cfg (dict): Configuration for the predictor.
            overrides (dict, optional): Configuration overrides that take precedence over cfg.
            _callbacks (list, optional): List of callback functions to be invoked during prediction.
        segmentN)super__init__argstask)selfcfg	overrides
_callbacks	__class__s       f/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/models/yolo/segment/predict.pyr   zSegmentationPredictor.__init__!   s!     	i4"		    c                 p    t        |d   t              r|d   d   n|d   }t        |   |d   |||      S )a;  
        Apply non-max suppression and process segmentation detections for each image in the input batch.

        Args:
            preds (tuple): Model predictions, containing bounding boxes, scores, classes, and mask coefficients.
            img (torch.Tensor): Input image tensor in model format, with shape (B, C, H, W).
            orig_imgs (list | torch.Tensor | np.ndarray): Original image or batch of images.

        Returns:
            (list): List of Results objects containing the segmentation predictions for each image in the batch.
                Each Results object includes both bounding boxes and segmentation masks.

        Examples:
            >>> predictor = SegmentationPredictor(overrides=dict(model="yolo11n-seg.pt"))
            >>> results = predictor.postprocess(preds, img, orig_img)
           r   )protos)
isinstancetupler   postprocess)r   predsimg	orig_imgsr   r   s        r   r   z!SegmentationPredictor.postprocess0   sB    $ ",E!He!<q"%(w"58S)F"KKr   c                     t        ||| j                  d   |      D cg c]  \  }}}}| j                  |||||       c}}}}S c c}}}}w )a:  
        Construct a list of result objects from the predictions.

        Args:
            preds (List[torch.Tensor]): List of predicted bounding boxes, scores, and masks.
            img (torch.Tensor): The image after preprocessing.
            orig_imgs (List[np.ndarray]): List of original images before preprocessing.
            protos (List[torch.Tensor]): List of prototype masks.

        Returns:
            (List[Results]): List of result objects containing the original images, image paths, class names,
                bounding boxes, and masks.
        r   )zipbatchconstruct_result)	r   r   r   r   r   predorig_imgimg_pathprotos	            r   construct_resultsz'SegmentationPredictor.construct_resultsE   sY      47uiTUX^3_
 
/h% !!$XxG
 	
 
s   !A
c           	         t        |      sd}n| j                  j                  rxt        j                  |j
                  dd |ddddf   |j
                        |ddddf<   t        j                  ||ddddf   |ddddf   |j
                  dd       }nyt        j                  ||ddddf   |ddddf   |j
                  dd d      }t        j                  |j
                  dd |ddddf   |j
                        |ddddf<   ||j                  d      dkD  }||   ||   }}t        ||| j                  j                  |ddddf   |	      S )
a.  
        Construct a single result object from the prediction.

        Args:
            pred (np.ndarray): The predicted bounding boxes, scores, and masks.
            img (torch.Tensor): The image after preprocessing.
            orig_img (np.ndarray): The original image before preprocessing.
            img_path (str): The path to the original image.
            proto (torch.Tensor): The prototype masks.

        Returns:
            (Results): Result object containing the original image, image path, class names, bounding boxes, and masks.
        N         T)upsample)r   r   )pathnamesboxesmasks)lenr   retina_masksr   scale_boxesshapeprocess_mask_nativeprocess_masksumr   modelr0   )r   r$   r   r%   r&   r'   r2   keeps           r   r#   z&SegmentationPredictor.construct_resultX   sZ    4yEYY##//#))AB-a!ehnnUDBQBK++E412;QUX^^\^]^M_`E$$UDABKa!eciiPQPRm^bcE//#))AB-a!ehnnUDBQBK99X&*Dt*eDk%Dxhdjj6F6FdSTVXWXVXSXkafggr   )
__name__
__module____qualname____doc__r   r   r   r(   r#   __classcell__)r   s   @r   r   r      s'    0 '$4 #L*
&hr   r   N)ultralytics.engine.resultsr   &ultralytics.models.yolo.detect.predictr   ultralytics.utilsr   r   r    r   r   <module>rE      s!    / E .ih. ihr   