
    /j~                    V    d dl mZ d dlmZ d dlmZ d dlmZmZ  G d de          Z	dS )    )annotations)Results)DetectionPredictor)DEFAULT_CFGopsc                  B     e Zd ZdZeddfd	 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="yolo26n-seg.pt", source=ASSETS)
        >>> predictor = SegmentationPredictor(overrides=args)
        >>> predictor.predict_cli()
    N
_callbacksdict | Nonec                f    t                                          |||           d| j        _        dS )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 (dict, optional): Dictionary of callback functions to be invoked during prediction.
        segmentN)super__init__argstask)selfcfg	overridesr
   	__class__s       l/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/segment/predict.pyr   zSegmentationPredictor.__init__"   s.     	i444"	    c                    t          |d         t                    r|d         d         n|d         }t                                          |d         |||          S )a2  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="yolo26n-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   sR    " !+58U ; ;Iq!qww""58S)F"KKKr   c                Z      fdt          || j        d         |          D             S )aB  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 (torch.Tensor): Prototype masks tensor with shape (B, C, H, W).

        Returns:
            (list[Results]): List of result objects containing the original images, image paths, class names, bounding
                boxes, and masks.
        c           	     L    g | ] \  }}}}                     ||||          !S  )construct_result).0predorig_imgimg_pathprotor   r   s        r   
<listcomp>z;SegmentationPredictor.construct_results.<locals>.<listcomp>Q   sG     
 
 
/h% !!$XxGG
 
 
r   r   )zipbatch)r   r   r   r    r   s   ` `  r   construct_resultsz'SegmentationPredictor.construct_resultsD   sJ    
 
 
 
 
36uiTUX^3_3_
 
 
 	
r   c           	        |j         d         dk    rd}n| j        j        rzt          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                   }n{t          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<   |8|                    d          dk    }t          |          s||         ||         }}t          ||| j
        j        |ddddf         |	          S )
a'  Construct a single result object from the prediction.

        Args:
            pred (torch.Tensor): 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.
        r   N         T)upsample))pathnamesboxesmasks)shaper   retina_masksr   scale_boxesprocess_mask_nativeprocess_maskamaxallr   modelr6   )r   r&   r   r'   r(   r)   r8   keeps           r   r$   z&SegmentationPredictor.construct_resultV   s    :a=AEEY# 	V/#)ABB-aaa!ehnUUDBQBK+E4122;QQQUX^\^]^\^M_``EE$UDABBKaaa!eciPQPRPRm^bcccE/#)ABB-aaa!ehnUUDBQBK::h''!+Dt99 6"4j%+exhdj6FdSTSTSTVXWXVXSXkafggggr   )r
   r   )
__name__
__module____qualname____doc__r   r   r   r-   r$   __classcell__)r   s   @r   r	   r	   
   s         . '$RV # # # # # # #L L L L L(
 
 
$h h h h h h hr   r	   N)

__future__r   ultralytics.engine.resultsr   &ultralytics.models.yolo.detect.predictr   ultralytics.utilsr   r   r	   r#   r   r   <module>rK      s    # " " " " " . . . . . . E E E E E E . . . . . . . .eh eh eh eh eh. eh eh eh eh ehr   