
    |h                     >    d dl mZ d dlmZ d dlmZ  G d de      Zy)    )BasePredictor)Results)opsc                   (    e Zd ZdZd Zd Zd Zd Zy)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.
        get_obj_feats: Extract object features from the feature maps.

    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                    t        | dd      du}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(  |
      }t        |t              st        j                  |      }|r$| j!                  | j"                  |d	         }|d   } | j$                  |||fi |}|rt'        |      D ]  \  }}	|	|_         |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="yolo11n.pt"))
            >>> results = predictor.predict("path/to/image.jpg")
            >>> processed_results = predictor.postprocess(preds, img, orig_imgs)
        _featsNdetectr   end2endF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_featsr	   construct_resultszipfeats)
selfpredsimg	orig_imgskwargs
save_feats	obj_featsresultsrfs
             e/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/models/yolo/detect/predict.pypostprocesszDetectionPredictor.postprocess"   s5   * T8T2$>
''IINNIIMMIIII""II%%IINNh.qC

8H8H4IDJJ	59IINNe+"
 )T*55i@I**4;;aAI!HE($((YI&IGY/ 1     c                    ddl }t        |D cg c]  }|j                  d    c}      }|j                  |D cg c]U  }|j	                  dddd      j                  |j                  d   d||j                  d   |z        j                  d      W c}d      }t        ||      D cg c]  \  }}t        |      r||   ng  c}}S c c}w c c}w c c}}w )z.Extract object features from the feature maps.r   Nr         )dim)	torchminshapecatpermutereshapemeanr"   r   )	r$   	feat_mapsidxsr6   xsr*   r#   idxs	            r.   r    z DetectionPredictor.get_obj_featsT   s    Y//0IIeno`aQYYq!Q"**1771:r1aggajAoNSSXZS[ouv  
	 BEYPTAUV:5#c#hc
B.VV	 0oVs   CAC,Cc                     t        ||| j                  d         D cg c]  \  }}}| j                  ||||       c}}}S c c}}}w )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.
        r   )r"   batchconstruct_result)r$   r%   r&   r'   predorig_imgimg_paths          r.   r!   z$DetectionPredictor.construct_results^   sQ     -0y$**Q-,P
 
(h !!$Xx@
 	
 
s   Ac           	          t        j                  |j                  dd |ddddf   |j                        |ddddf<   t        ||| j                  j
                  |ddddf         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.
        r2   N      )pathr   boxes)r   scale_boxesr8   r   r   r   )r$   rE   r&   rF   rG   s        r.   rD   z#DetectionPredictor.construct_resulto   sh     oociimT!RaR%[(..QQUxhdjj6F6FdSTVXWXVXSXkZZr0   N)__name__
__module____qualname____doc__r/   r    r!   rD    r0   r.   r   r      s    20dW
"[r0   r   N)ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r   rR   r0   r.   <module>rV      s     7 . !u[ u[r0   