
    /j	                     J    d dl mZ d dlmZ d dlmZmZ  G d de          ZdS )    )BasePredictor)Results)nmsopsc                   :    e Zd ZdZd Zed             Zd Zd ZdS )DetectionPredictora5  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="yolo26n.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        |          d	ddd
f         }|r)|                     | j        |d                   }|d         } | j        |||fi |}|rt)          ||          D ]\  }}	|	|_        |S )ap  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="yolo26n.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listr   convert_torch2numpy_batchget_obj_featsr
   construct_resultszipfeats)
selfpredsimg	orig_imgskwargs
save_feats	obj_featsresultsrfs
             k/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/detect/predict.pypostprocesszDetectionPredictor.postprocess!   sM   ( T8T22$>
'INIMII"I%INh..qqC
8H4I4IDJ	599INe+"
 
 
 )T** 	L5i@@dddKI 	**4;aAAI!HE($(YII&II 	GY//  1    c                     ddl }t          d | D                       |                    fd| D             d          }d t          ||          D             S )z.Extract object features from the feature maps.r   Nc              3   0   K   | ]}|j         d          V  dS )r   Nshape).0xs     r0   	<genexpr>z3DetectionPredictor.get_obj_feats.<locals>.<genexpr>W   s(      ..q
......r2   c           	          g | ]]}|                     d ddd                              |j        d          d|j        d         z                                d          ^S )r         r   r   dim)permutereshaper6   mean)r7   r8   ss     r0   
<listcomp>z4DetectionPredictor.get_obj_feats.<locals>.<listcomp>Y   sb    ooo`aQYYq!Q""**171:r1agajAoNNSSXZS[[ooor2   r   r=   c                 B    g | ]\  }}|j         d          r||         ng S )r   r5   )r7   r%   idxs      r0   rC   z4DetectionPredictor.get_obj_feats.<locals>.<listcomp>[   s/    ZZZzuccil2c

ZZZr2   )torchmincatr$   )	feat_mapsidxsrF   r,   rB   s       @r0   r"   z DetectionPredictor.get_obj_featsR   s     	..I.....IIooooenooouv  
 
	 [ZSTXEYEYZZZZr2   c                 X      f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                 H    g | ]\  }}}                     |||          S  )construct_result)r7   predorig_imgimg_pathr(   r&   s       r0   rC   z8DetectionPredictor.construct_results.<locals>.<listcomp>h   sC     
 
 
(h !!$Xx@@
 
 
r2   r   )r$   batch)r&   r'   r(   r)   s   ` ` r0   r#   z$DetectionPredictor.construct_results]   sF    
 
 
 
 
,/y$*Q-,P,P
 
 
 	
r2   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.
        r;   N      )pathr   boxes)r   scale_boxesr6   r   r   r   )r&   rO   r(   rP   rQ   s        r0   rN   z#DetectionPredictor.construct_resultm   sv     ocimT!!!RaR%[(.QQQQQUxhdj6FdSTSTSTVXWXVXSXkZZZZr2   N)	__name__
__module____qualname____doc__r1   staticmethodr"   r#   rN   rM   r2   r0   r   r      so         0/ / /b [ [ \[
 
 
 [ [ [ [ [r2   r   N)ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r   r   rM   r2   r0   <module>ra      s    7 6 6 6 6 6 . . . . . . & & & & & & & &r[ r[ r[ r[ r[ r[ r[ r[ r[ r[r2   