o
    Wh                     @   sX   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	m
Z
 G dd deZdS )    N)Image)BasePredictor)Results)DEFAULT_CFGopsc                       s8   e Zd ZdZeddf fdd	Zdd Zdd Z  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.
        _legacy_transform_name (str): Name of the legacy transform class for backward compatibility.

    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                    s"   t  ||| d| j_d| _dS )a  
        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. Defaults to DEFAULT_CFG.
            overrides (dict, optional): Configuration overrides that take precedence over cfg.
            _callbacks (list, optional): List of callback functions to be executed during prediction.
        classifyz&ultralytics.yolo.data.augment.ToTensorN)super__init__argstask_legacy_transform_name)selfcfg	overrides
_callbacks	__class__ \/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/models/yolo/classify/predict.pyr
   &   s   
z ClassificationPredictor.__init__c                    s   t |tjs2t fdd jjD }|r$tj fdd|D dd}ntj fdd|D dd}t |tjr:|nt| jj	} jj
rL| S | S )zVConvert input images to model-compatible tensor format with appropriate normalization.c                 3   s    | ]
} j t|v V  qd S )N)r   str).0	transformr   r   r   	<genexpr>9   s    
z5ClassificationPredictor.preprocess.<locals>.<genexpr>c                    s   g | ]}  |qS r   )
transformsr   imr   r   r   
<listcomp>=   s    z6ClassificationPredictor.preprocess.<locals>.<listcomp>r   )dimc              
      s&   g | ]}  tt|tjqS r   )r   r   	fromarraycv2cvtColorCOLOR_BGR2RGBr   r   r   r   r   @   s   & )
isinstancetorchTensoranyr   stack
from_numpytomodeldevicefp16halffloat)r   imgis_legacy_transformr   r   r   
preprocess6   s   $z"ClassificationPredictor.preprocessc                    sN   t |ts
t|}t |ttfr|d n|} fd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.
        r   c                    s&   g | ]\}}}t || jj|d qS ))pathnamesprobs)r   r+   r4   )r   predorig_imgimg_pathr   r   r   r   U   s    z7ClassificationPredictor.postprocess.<locals>.<listcomp>)r$   listr   convert_torch2numpy_batchtuplezipbatch)r   predsr0   	orig_imgsr   r   r   postprocessE   s   


z#ClassificationPredictor.postprocess)	__name__
__module____qualname____doc__r   r
   r2   r@   __classcell__r   r   r   r   r      s
    r   )r!   r%   PILr   ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r   r   r   r   r   r   <module>   s   