
    |h5                     j    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y)	    N)Image)classify_transforms)BasePredictor)Results)DEFAULT_CFGopsc                   @     e Zd ZdZeddf 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.

    Notes:
        - Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'.

    Examples:
        >>> from ultralytics.utils import ASSETS
        >>> from ultralytics.models.yolo.classify import ClassificationPredictor
        >>> args = dict(model="yolo11n-cls.pt", source=ASSETS)
        >>> predictor = ClassificationPredictor(overrides=args)
        >>> predictor.predict_cli()
    Nc                 J    t         |   |||       d| j                  _        y)av  
        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 (list, optional): List of callback functions to be executed during prediction.
        classifyN)super__init__argstask)selfcfg	overrides
_callbacks	__class__s       g/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/predict.pyr   z ClassificationPredictor.__init__&   s!     	i4#		    c                     t         |   |       t        | j                  j                  d      rt        | j                  j                  j                  j                  d   d      rM| j                  j                  j                  j                  d   j
                  t        | j                        k7  nd}|s| j                  j                  st        | j                        | _        y| j                  j                  j                  | _        y)z9Set up source and inference mode and classify transforms.
transformsr   sizeFN)
r   setup_sourcehasattrmodelr   r   maximgszptr   )r   sourceupdatedr   s      r   r   z$ClassificationPredictor.setup_source5   s    V$ tzz''674::CSCSC^C^CiCijkClnt;u JJ''2215::c$**oM 	 07djjmm

+ 	QUQ[Q[QaQaQlQl 	r   c                 &   t        |t        j                        sit        j                  |D cg c]H  }| j	                  t        j                  t        j                  |t        j                                    J c}d      }t        |t        j                        r|nt        j                  |      j                  | j                  j                        }| j                  j                  r|j                         S |j!                         S c c}w )zVConvert input images to model-compatible tensor format with appropriate normalization.r   )dim)
isinstancetorchTensorstackr   r   	fromarraycv2cvtColorCOLOR_BGR2RGB
from_numpytor   devicefp16halffloat)r   imgims      r   
preprocessz"ClassificationPredictor.preprocessA   s    #u||,++ade[]b#BSBS1T!UVeklC !ell3s9I9I#9NRRSWS]S]SdSde!ZZ__sxxz=#))+= fs   ADc                 6   t        |t              st        j                  |      }t        |t        t        f      r|d   n|}t        ||| j                  d         D cg c])  \  }}}t        ||| j                  j                  |      + c}}}S c c}}}w )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.
        r   )pathnamesprobs)
r%   listr   convert_torch2numpy_batchtuplezipbatchr   r   r8   )r   predsr3   	orig_imgspredorig_imgimg_paths          r   postprocessz#ClassificationPredictor.postprocessJ   s     )T*55i@I&utUm<a% -0y$**Q-,P
 
(h H84::3C3C4P
 	
 
s   !.B)
__name__
__module____qualname____doc__r   r   r   r5   rD   __classcell__)r   s   @r   r
   r
      s%    0 '$4 $

>
r   r
   )r*   r&   PILr   ultralytics.data.augmentr   ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r   r
    r   r   <module>rP      s*       8 6 . .P
m P
r   