o
    Wh"                     @   s<   d dl mZ d dlmZ d dlmZmZ G dd deZdS )    )Results)DetectionPredictor)DEFAULT_CFGopsc                       sD   e Zd ZdZeddf fdd	Z fddZdd Zd	d
 Z  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: Applies non-max suppression and processes detections.
        construct_results: Constructs a list of result objects from predictions.
        construct_result: Constructs 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                    s   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. Defaults to Ultralytics DEFAULT_CFG.
            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__ [/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/models/yolo/segment/predict.pyr	   !   s   zSegmentationPredictor.__init__c                    s:   t |d tr|d d n|d }t j|d |||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   r   r   r   0   s   "z!SegmentationPredictor.postprocessc                    s$    fddt ||jd |D S )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.
        c              	      s&   g | ]\}}}} | |||qS r   )construct_result).0predorig_imgimg_pathprotor   r   r   r   
<listcomp>S   s    
z;SegmentationPredictor.construct_results.<locals>.<listcomp>r   )zipbatchr   r   r$   r   construct_resultsE   s   z'SegmentationPredictor.construct_resultsc                 C   sR  t |sd}n{| jjrFt|jdd |ddddf |j|ddddf< t||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d}t|jdd |ddddf |j|ddddf< |dur|ddk}|| || }}t	||| j
j|ddddf |d	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   modelr/   )r   r    r   r!   r"   r#   r1   keepr   r   r   r   X   s   :<>:&z&SegmentationPredictor.construct_result)
__name__
__module____qualname____doc__r   r	   r   r(   r   __classcell__r   r   r   r   r      s    r   N)ultralytics.engine.resultsr   &ultralytics.models.yolo.detect.predictr   ultralytics.utilsr   r   r   r   r   r   r   <module>   s   