
    /jj                    ~    d dl mZ d dlZd dlZd dlmZ 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 )
    )annotationsN)Image)classify_transforms)BasePredictor)Results)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 )
ClassificationPredictora  A class extending the BasePredictor class for prediction based on a classification model.

    This predictor handles the specific requirements of classification models, including preprocessing images and
    postprocessing predictions to generate classification results.

    Attributes:
        args (dict): Configuration arguments for the predictor.

    Methods:
        preprocess: Convert input images to model-compatible format.
        postprocess: Process model predictions into Results objects.

    Examples:
        >>> from ultralytics.utils import ASSETS
        >>> from ultralytics.models.yolo.classify import ClassificationPredictor
        >>> args = dict(model="yolo26n-cls.pt", source=ASSETS)
        >>> predictor = ClassificationPredictor(overrides=args)
        >>> predictor.predict_cli()

    Notes:
        - Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'.
    N
_callbacksdict | Nonec                f    t                                          |||           d| j        _        dS )as  Initialize the ClassificationPredictor with the specified configuration and set task to 'classify'.

        This constructor initializes a ClassificationPredictor instance, which extends BasePredictor for classification
        tasks. It ensures the task is set to 'classify' regardless of input configuration.

        Args:
            cfg (dict): Default configuration dictionary containing prediction settings.
            overrides (dict, optional): Configuration overrides that take precedence over cfg.
            _callbacks (dict, optional): Dictionary of callback functions to be executed during prediction.
        classifyN)super__init__argstask)selfcfg	overridesr   	__class__s       m/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/classify/predict.pyr   z ClassificationPredictor.__init__'   s.     	i444#	    c                   t                                          |           t          | j        j        d          rat          | j        j        j        j        d         d          r7| j        j        j        j        d         j        t          | j                  k    nd}|s| j        j        dk    rt          | j                  n| j        j        j        | _        dS )z9Set up source and inference mode and classify transforms.
transformsr   sizeFptN)
r   setup_sourcehasattrmodelr   r   maximgszformatr   )r   sourceupdatedr   s      r   r   z$ClassificationPredictor.setup_source5   s    V$$$ tz'66;B4:CSC^CijkClnt;u;uDJ'215:c$*ooMM 	 07t$*:Kt:S:S
+++Y]YcYiYt 	r   c                ~    t          |t          j                  s"t          j         fd|D             d          }t          |t          j                  r|nt          j        |                               j        j                  } j        j        r|	                                n|
                                S )zVConvert input images to model-compatible tensor format with appropriate normalization.c           
         g | ]F}                     t          j        t          j        |t          j                                      GS  )r   r   	fromarraycv2cvtColorCOLOR_BGR2RGB).0imr   s     r   
<listcomp>z6ClassificationPredictor.preprocess.<locals>.<listcomp>E   s?    eee[]b#BS1T1T!U!UVVeeer   r   )dim)
isinstancetorchTensorstack
from_numpytor    devicefp16halffloat)r   imgs   ` r   
preprocessz"ClassificationPredictor.preprocessA   s    #u|,, 	+eeeeadeeekl  C !el33Nss9I#9N9NRRSWS]Sdee!Z_=sxxzzz#))++=r   c                    t          |t                    st          j        |          ddddf         }t          |t          t          f          r|d         n|} fdt          || j        d                   D             S )a  Process predictions to return Results objects with classification probabilities.

        Args:
            preds (torch.Tensor): Raw predictions from the model.
            img (torch.Tensor): Input images after preprocessing.
            orig_imgs (list[np.ndarray] | torch.Tensor): Original images before preprocessing.

        Returns:
            (list[Results]): List of Results objects containing classification results for each image.
        .Nr   c                R    g | ]#\  }}}t          ||j        j        |           $S ))pathnamesprobs)r   r    rA   )r-   predorig_imgimg_pathr   s       r   r/   z7ClassificationPredictor.postprocess.<locals>.<listcomp>Y   sE     
 
 
(h H84:3C4PPP
 
 
r   )r1   listr	   convert_torch2numpy_batchtuplezipbatch)r   predsr;   	orig_imgss   `   r   postprocessz#ClassificationPredictor.postprocessJ   s     )T** 	L5i@@dddKI&utUm<<Ga%
 
 
 
,/y$*Q-,P,P
 
 
 	
r   )r   r   )
__name__
__module____qualname____doc__r   r   r   r<   rM   __classcell__)r   s   @r   r   r      s         . '$RV $ $ $ $ $ $ $

 

 

 

 

> > >
 
 
 
 
 
 
r   r   )
__future__r   r*   r2   PILr   ultralytics.data.augmentr   ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r	   r   r(   r   r   <module>rY      s    # " " " " " 



        8 8 8 8 8 8 6 6 6 6 6 6 . . . . . . . . . . . . . .M
 M
 M
 M
 M
m M
 M
 M
 M
 M
r   