o
    Wh                     @   s8   d dl mZ d dlmZ d dlmZ G dd deZdS )    )BasePredictor)Results)opsc                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )DetectionPredictora  
    A class extending the BasePredictor class for prediction based on a detection model.

    This predictor specializes in object detection tasks, processing model outputs into meaningful detection results
    with bounding boxes and class predictions.

    Attributes:
        args (namespace): Configuration arguments for the predictor.
        model (nn.Module): The detection model used for inference.
        batch (list): Batch of images and metadata for processing.

    Methods:
        postprocess: Process raw model predictions into detection results.
        construct_results: Build Results objects from processed predictions.
        construct_result: Create a single Result object from a prediction.

    Examples:
        >>> from ultralytics.utils import ASSETS
        >>> from ultralytics.models.yolo.detect import DetectionPredictor
        >>> args = dict(model="yolo11n.pt", source=ASSETS)
        >>> predictor = DetectionPredictor(overrides=args)
        >>> predictor.predict_cli()
    c           
      K   s   t | dd}tj|| jj| jj| jj| jj| jj| jj	dkr dnt
| jjt | jdd| jj	dk|d
}t|ts>t|}|rM| | j|d }|d }| j|||fi |}|rgt||D ]\}}	|	|_q_|S )	ay  
        Post-process predictions and return a list of Results objects.

        This method applies non-maximum suppression to raw model predictions and prepares them for visualization and
        further analysis.

        Args:
            preds (torch.Tensor): Raw predictions from the model.
            img (torch.Tensor): Processed input image tensor in model input format.
            orig_imgs (torch.Tensor | list): Original input images before preprocessing.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            (list): List of Results objects containing the post-processed predictions.

        Examples:
            >>> predictor = DetectionPredictor(overrides=dict(model="yolov8n.pt"))
            >>> results = predictor.predict("path/to/image.jpg")
            >>> processed_results = predictor.postprocess(preds, img, orig_imgs)
        
save_featsFdetectr   end2endobb)max_detncr   rotatedreturn_idxs   )getattrr   non_max_suppressionargsconfiouclassesagnostic_nmsr
   tasklenmodelnames
isinstancelistconvert_torch2numpy_batchget_obj_feats_featsconstruct_resultszipfeats)
selfpredsimg	orig_imgskwargsr   	obj_featsresultsrf r+   Z/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/models/yolo/detect/predict.pypostprocess!   s.   


zDetectionPredictor.postprocessc                    sV   ddl m} ddl}|dd |D   |j fdd|D dd}d	d t||D S )
z.Extract object features from the feature maps.r   )gcdNc                 S   s   g | ]}|j d  qS )r   )shape.0xr+   r+   r,   
<listcomp>Y   s    z4DetectionPredictor.get_obj_feats.<locals>.<listcomp>c              	      s@   g | ]}| d ddd|jd  d |jd   jddqS )r         r   dim)permutereshaper/   meanr0   sr+   r,   r3   [   s   @ r   r7   c                 S   s   g | ]\}}|| qS r+   r+   )r1   r!   idxr+   r+   r,   r3   ]   s    )mathr.   torchcatr    )r"   	feat_mapsidxsr.   r@   r'   r+   r<   r,   r   S   s   z DetectionPredictor.get_obj_featsc                    s"    fddt ||jd D S )a  
        Construct a list of Results objects from model predictions.

        Args:
            preds (List[torch.Tensor]): List of predicted bounding boxes and scores for each image.
            img (torch.Tensor): Batch of preprocessed images used for inference.
            orig_imgs (List[np.ndarray]): List of original images before preprocessing.

        Returns:
            (List[Results]): List of Results objects containing detection information for each image.
        c                    s"   g | ]\}}} | ||qS r+   )construct_result)r1   predorig_imgimg_pathr$   r"   r+   r,   r3   k   s    z8DetectionPredictor.construct_results.<locals>.<listcomp>r   )r    batch)r"   r#   r$   r%   r+   rH   r,   r   _   s   z$DetectionPredictor.construct_resultsc                 C   s^   t |jdd |ddddf |j|ddddf< t||| jj|ddddf dS )a.  
        Construct a single Results object from one image prediction.

        Args:
            pred (torch.Tensor): Predicted boxes and scores with shape (N, 6) where N is the number of detections.
            img (torch.Tensor): Preprocessed image tensor used for inference.
            orig_img (np.ndarray): Original image before preprocessing.
            img_path (str): Path to the original image file.

        Returns:
            (Results): Results object containing the original image, image path, class names, and scaled bounding boxes.
        r4   N      )pathr   boxes)r   scale_boxesr/   r   r   r   )r"   rE   r$   rF   rG   r+   r+   r,   rD   p   s   :$z#DetectionPredictor.construct_resultN)__name__
__module____qualname____doc__r-   r   r   rD   r+   r+   r+   r,   r      s    2r   N)ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r   r+   r+   r+   r,   <module>   s   