
    v-j                   0   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Zd dl	Z
d dlZd dlmZ d dlmZ d dlmZmZ d dlmZmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZm Z m!Z! d dl"m#Z#m$Z$m%Z% dZ&dZ' G d d          Z( G d d          Z) G d de(          Z* G d de*          Z+ G d de*          Z, G d de*          Z- G d de(          Z. G d de(          Z/ G d  d!e(          Z0 G d" d#e(          Z1 G d$ d%e*          Z2 G d& d'e(          Z3 G d( d)e(          Z4 G d* d+e4          Z5 G d, d-e(          Z6 G d. d/e(          Z7d\d]d7Z8d8e&e'd9dfd^dCZ9d8e&e'dddDdEddFdGdGd0dEd9fd_dUZ: G dV dW          Z; G dX dY          Z< G dZ d[          Z=dS )`    )annotationsN)deepcopy)Any)Image)
functional)polygons2maskspolygons2masks_overlap)LOGGERIterableSimpleNamespacecolorstr)check_version)	Instances)bbox_ioa)segment2box	xywh2xyxyxyxyxyxy2xywhr)TORCHVISION_0_10TORCHVISION_0_11TORCHVISION_0_13)        r   r   )      ?r   r   c                  6    e Zd ZdZd Zd ZddZddZddZdS )	BaseTransforman  Base class for image transformations in the Ultralytics library.

    This class provides a unified interface for applying transformations to images, object instances, and semantic
    segmentation masks. Subclasses should override `apply_image`, `apply_instances`, and/or `apply_semantic` for simple
    transforms, or override `__call__` directly for complex transforms that need shared state between image and
    annotation modifications.

    Methods:
        get_params: Compute transformation parameters shared across image, instances, and semantic mask.
        apply_image: Apply transformation to the image in labels['img'].
        apply_instances: Apply transformation to object instances in labels['instances'].
        apply_semantic: Apply transformation to semantic mask in labels['semantic_mask'].
        __call__: Orchestrate the transformation pipeline.
    c                    |                      |          }|                     ||          }|                     ||          }|                     ||          }|S )zApply transformation to labels dict.

        Args:
            labels (dict): Dictionary containing 'img', optionally 'instances' and 'semantic_mask'.

        Returns:
            (dict): Transformed labels dictionary.
        )
get_paramsapply_imageapply_instancesapply_semanticselflabelsparamss      X/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/ultralytics/data/augment.py__call__zBaseTransform.__call__,   sY     ((!!&&11%%ff55$$VV44    c                    i S )a  Compute and return transformation parameters.

        This method allows sharing random state or computed matrices (e.g. affine matrix, flip
        decision) between image, instances, and semantic mask transformations.

        Args:
            labels (dict): Input labels dictionary.

        Returns:
            (dict): Parameters to pass to apply_image, apply_instances, and apply_semantic.
         )r    r!   s     r#   r   zBaseTransform.get_params;   s	     	r%   Nc                    |S )zApply transformation to image.

        Args:
            labels (dict): Dictionary containing 'img'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels dictionary.
        r'   r   s      r#   r   zBaseTransform.apply_imageI   	     r%   c                    |S )zApply transformation to object instances.

        Args:
            labels (dict): Dictionary containing 'instances'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels dictionary.
        r'   r   s      r#   r   zBaseTransform.apply_instancesU   r)   r%   c                    |S )a  Apply transformation to semantic segmentation mask.

        Args:
            labels (dict): Dictionary containing 'semantic_mask'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels dictionary.
        r'   r   s      r#   r   zBaseTransform.apply_semantica   r)   r%   N)	__name__
__module____qualname____doc__r$   r   r   r   r   r'   r%   r#   r   r      sx             
 
 
 

 
 
 

 
 
 
 
 
r%   r   c                  F    e Zd ZdZd Zd Zd Zd Zdd	ZddZ	d Z
d ZdS )Composea  A class for composing multiple image transformations.

    Attributes:
        transforms (list[Callable]): A list of transformation functions to be applied sequentially.

    Methods:
        __call__: Apply a series of transformations to input data.
        append: Append a new transform to the existing list of transforms.
        insert: Insert a new transform at a specified index in the list of transforms.
        __getitem__: Retrieve a specific transform or a set of transforms using indexing.
        __setitem__: Set a specific transform or a set of transforms using indexing.
        tolist: Convert the list of transforms to a standard Python list.

    Examples:
        >>> transforms = [RandomFlip(), RandomPerspective(30)]
        >>> compose = Compose(transforms)
        >>> transformed_data = compose(data)
        >>> compose.append(CenterCrop((224, 224)))
        >>> compose.insert(0, RandomFlip())
    c                D    t          |t                    r|n|g| _        dS )zInitialize the Compose object with a list of transforms.

        Args:
            transforms (list[Callable]): A list of callable transform objects to be applied sequentially.
        N)
isinstancelist
transforms)r    r6   s     r#   __init__zCompose.__init__   s$     )3:t(D(DV**:,r%   c                0    | j         D ]} ||          }|S )aw  Apply a series of transformations to input data.

        This method sequentially applies each transformation in the Compose object's transforms to the input data.

        Args:
            data (Any): The input data to be transformed. This can be of any type, depending on the transformations in
                the list.

        Returns:
            (Any): The transformed data after applying all transformations in sequence.

        Examples:
            >>> transforms = [Transform1(), Transform2(), Transform3()]
            >>> compose = Compose(transforms)
            >>> transformed_data = compose(input_data)
        r6   )r    datats      r#   r$   zCompose.__call__   s)    "  	 	A1T77DDr%   c                :    | j                             |           dS )a2  Append a new transform to the existing list of transforms.

        Args:
            transform (BaseTransform): The transformation to be added to the composition.

        Examples:
            >>> compose = Compose([RandomFlip(), RandomPerspective()])
            >>> compose.append(RandomHSV())
        N)r6   append)r    	transforms     r#   r=   zCompose.append   s      	y)))))r%   c                <    | j                             ||           dS )a  Insert a new transform at a specified index in the existing list of transforms.

        Args:
            index (int): The index at which to insert the new transform.
            transform (BaseTransform): The transform object to be inserted.

        Examples:
            >>> compose = Compose([Transform1(), Transform2()])
            >>> compose.insert(1, Transform3())
            >>> len(compose.transforms)
            3
        N)r6   insert)r    indexr>   s      r#   r@   zCompose.insert   s"     	ui00000r%   rA   
list | intreturnc                     t          |t          t          f          sJ dt          |                       t          |t                    rt	           fd|D                       n j        |         S )a	  Retrieve a specific transform or a set of transforms using indexing.

        Args:
            index (int | list[int]): Index or list of indices of the transforms to retrieve.

        Returns:
            (Compose | Any): A new Compose object if index is a list, or a single transform if index is an int.

        Raises:
            AssertionError: If the index is not of type int or list.

        Examples:
            >>> transforms = [RandomFlip(), RandomPerspective(10), RandomHSV(0.5, 0.5, 0.5)]
            >>> compose = Compose(transforms)
            >>> single_transform = compose[1]  # Returns the RandomPerspective transform directly
            >>> multiple_transforms = compose[[0, 1]]  # Returns a Compose object with RandomFlip and RandomPerspective
        6The indices should be either list or int type but got c                *    g | ]}j         |         S r'   r9   .0ir    s     r#   
<listcomp>z'Compose.__getitem__.<locals>.<listcomp>   s     :::q*:::r%   )r4   intr5   typer2   r6   )r    rA   s   ` r#   __getitem__zCompose.__getitem__   s|    $ %#t--uu/uhlmrhshs/u/uuu-?I%QU?V?Vrw::::E:::;;;\`\klq\rrr%   valueNonec                   t          |t          t          f          sJ dt          |                       t          |t                    r?t          |t                    s*J dt          |           dt          |                       t          |t                    r|g|g}}t	          ||          D ]J\  }}|t          | j                  k     s#J d| dt          | j                   d            || j        |<   KdS )a  Set one or more transforms in the composition using indexing.

        Args:
            index (int | list[int]): Index or list of indices to set transforms at.
            value (Any | list[Any]): Transform or list of transforms to set at the specified index(es).

        Raises:
            AssertionError: If index type is invalid, value type doesn't match index type, or index is out of range.

        Examples:
            >>> compose = Compose([Transform1(), Transform2(), Transform3()])
            >>> compose[1] = NewTransform()  # Replace second transform
            >>> compose[[0, 1]] = [NewTransform1(), NewTransform2()]  # Replace first two transforms
        rE   z7The indices should be the same type as values, but got z and zlist index z out of range .N)r4   rK   r5   rL   ziplenr6   )r    rA   rN   rI   vs        r#   __setitem__zCompose.__setitem__   s,    %#t--uu/uhlmrhshs/u/uuu-eT"" 	eT**  i$u++ii\`af\g\gii * eS!! 	,!7UG5Eu%% 	# 	#DAqs4?+++++-c1-c-cCPTP_L`L`-c-c-c+++!"DOA	# 	#r%   c                    | j         S )a  Convert the list of transforms to a standard Python list.

        Returns:
            (list): A list containing all the transform objects in the Compose instance.

        Examples:
            >>> transforms = [RandomFlip(), RandomPerspective(10), CenterCrop()]
            >>> compose = Compose(transforms)
            >>> transform_list = compose.tolist()
            >>> print(len(transform_list))
            3
        r9   r    s    r#   tolistzCompose.tolist   s     r%   c                j    | j         j         dd                    d | j        D                        dS )a  Return a string representation of the Compose object.

        Returns:
            (str): A string representation of the Compose object, including the list of transforms.

        Examples:
            >>> transforms = [RandomFlip(), RandomPerspective(degrees=10, translate=0.1, scale=0.1)]
            >>> compose = Compose(transforms)
            >>> print(compose)
            Compose([
                RandomFlip(),
                RandomPerspective(degrees=10, translate=0.1, scale=0.1)
            ])
        (, c                    g | ]}| S r'   r'   )rH   r;   s     r#   rJ   z$Compose.__repr__.<locals>.<listcomp>	  s    6W6W6W!!v6W6W6Wr%   ))	__class__r-   joinr6   rW   s    r#   __repr__zCompose.__repr__   s=     .)[[DII6W6Wt6W6W6W,X,X[[[[r%   N)rA   rB   rC   r2   )rA   rB   rN   rB   rC   rO   )r-   r.   r/   r0   r7   r$   r=   r@   rM   rU   rX   r`   r'   r%   r#   r2   r2   n   s         *W W W  *
* 
* 
*1 1 1s s s s*# # # #4  \ \ \ \ \r%   r2   c                  J    e Zd ZdZdddZdd	Zdd
Zd Zedd            Z	dS )BaseMixTransforma  Base class for mix transformations like Cutmix, MixUp and Mosaic.

    This class provides a foundation for implementing mix transformations on datasets. It handles the probability-based
    application of transforms and manages the mixing of multiple images and labels.

    Attributes:
        dataset (Any): The dataset object containing images and labels.
        pre_transform (Callable | None): Optional transform to apply before mixing.
        p (float): Probability of applying the mix transformation.

    Methods:
        __call__: Apply the mix transformation to the input labels.
        get_params: Prepare mixed labels and update text labels.
        get_indexes: Abstract method to get indexes of images to be mixed.
        _update_label_text: Update label text for mixed images.

    Examples:
        >>> class CustomMixTransform(BaseMixTransform):
        ...     def apply_image(self, labels, params=None):
        ...         # Implement custom image mixing here
        ...         return labels
        ...
        ...     def get_indexes(self):
        ...         return [random.randint(0, len(self.dataset) - 1) for _ in range(3)]
        >>> dataset = YourDataset()
        >>> transform = CustomMixTransform(dataset, p=0.5)
        >>> mixed_labels = transform(original_labels)
    Nr   rC   rO   c                0    || _         || _        || _        dS )a  Initialize the BaseMixTransform object for mix transformations like CutMix, MixUp and Mosaic.

        This class serves as a base for implementing mix transformations in image processing pipelines.

        Args:
            dataset (Any): The dataset object containing images and labels for mixing.
            pre_transform (Callable | None): Optional transform to apply before mixing.
            p (float): Probability of applying the mix transformation. Should be in the range [0.0, 1.0].
        Ndatasetpre_transformp)r    re   rf   rg   s       r#   r7   zBaseMixTransform.__init__*  s     *r%   r!   dict[str, Any]c                    t          j        dd          | j        k    r|S |                     |          }|                     ||          }|                     ||          }|                     ||          }|                    dd           |S )a  Apply pre-processing transforms and cutmix/mixup/mosaic transforms to labels data.

        This method determines whether to apply the mix transform based on a probability factor. If applied, it selects
        additional images, applies pre-transforms if specified, and then performs the mix transform.

        Args:
            labels (dict[str, Any]): A dictionary containing label data for an image.

        Returns:
            (dict[str, Any]): The transformed labels dictionary, which may include mixed data from other images.

        Examples:
            >>> transform = BaseMixTransform(dataset, pre_transform=None, p=0.5)
            >>> result = transform({"image": img, "bboxes": boxes, "cls": classes})
        r      
mix_labelsN)randomuniformrg   r   r   r   r   popr   s      r#   r$   zBaseMixTransform.__call__8  s      >!Q$&((M((!!&&11%%ff55$$VV44

<&&&r%   c                                                      }t          |t                    r|g} fd|D             } j        -t	          |          D ]\  }}                     |          ||<   ||d<                        |           d|iS )a  Prepare mixed labels and update text labels.

        Args:
            labels (dict[str, Any]): A dictionary containing label data for an image.

        Returns:
            (dict[str, Any]): Parameters for apply_image, apply_instances, and apply_semantic.
        c                D    g | ]}j                             |          S r'   )re   get_image_and_labelrG   s     r#   rJ   z/BaseMixTransform.get_params.<locals>.<listcomp>a  s)    KKKadl66q99KKKr%   Nrk   )get_indexesr4   rK   rf   	enumerate_update_label_text)r    r!   indexesrk   rI   r:   s   `     r#   r   zBaseMixTransform.get_paramsR  s     ""$$gs## 	 iG LKKK7KKK
)$Z00 9 94 $ 2 24 8 8
1)| 	'''j))r%   c                V    t          j        dt          | j                  dz
            S )a  Get a random index for mosaic augmentation.

        Returns:
            (int): A random index from the dataset.

        Examples:
            >>> transform = BaseMixTransform(dataset)
            >>> index = transform.get_indexes()
            >>> print(index)  # 7
        r   rj   rl   randintrS   re   rW   s    r#   rr   zBaseMixTransform.get_indexesl  s%     ~aT\!2!2Q!6777r%   c                   d| vr| S g | d         d | d         D             }t          d |D                       }d t          |          D             }| g| d         z   D ]}t          |d                             d                                                    D ]>\  }}|d         t	          |                   }|t          |                   |d         |<   ?||d<   | S )a  Update label text and class IDs for mixed labels in image augmentation.

        This method processes the 'texts' and 'cls' fields of the input labels dictionary and any mixed labels, creating
        a unified set of text labels and updating class IDs accordingly.

        Args:
            labels (dict[str, Any]): A dictionary containing label information, including 'texts' and 'cls' fields, and
                optionally a 'mix_labels' field with additional label dictionaries.

        Returns:
            (dict[str, Any]): The updated labels dictionary with unified text labels and updated class IDs.

        Examples:
            >>> labels = {
            ...     "texts": [["cat"], ["dog"]],
            ...     "cls": torch.tensor([[0], [1]]),
            ...     "mix_labels": [{"texts": [["bird"], ["fish"]], "cls": torch.tensor([[0], [1]])}],
            ... }
            >>> updated_labels = BaseMixTransform._update_label_text(labels)
            >>> print(updated_labels["texts"])
            [['cat'], ['dog'], ['bird'], ['fish']]
            >>> print(updated_labels["cls"])
            tensor([[0],
                    [1]])
            >>> print(updated_labels["mix_labels"][0]["cls"])
            tensor([[2],
                    [3]])
        textsc              3  0   K   | ]}|d          D ]}|V  dS )rz   Nr'   )rH   xitems      r#   	<genexpr>z6BaseMixTransform._update_label_text.<locals>.<genexpr>  s7      (c(c!XYZaXb(c(cPT(c(c(c(c(c(c(cr%   rk   c                ,    h | ]}t          |          S r'   )tuplerH   r|   s     r#   	<setcomp>z6BaseMixTransform._update_label_text.<locals>.<setcomp>  s    666q%((666r%   c                    i | ]\  }}||	S r'   r'   )rH   rI   texts      r#   
<dictcomp>z7BaseMixTransform._update_label_text.<locals>.<dictcomp>  s    ???wq$4???r%   cls)r5   rs   squeezerX   rK   r   )r!   	mix_textstext2idlabelrI   r   r   s          r#   rt   z#BaseMixTransform._update_label_texty  s   < &  MdfWod(c(cvl7K(c(c(cd	66I66677	??)I*>*>???X| 44 	' 	'E#E%L$8$8$<$<$C$C$E$EFF 7 73W~c#hh/")%++"6eQ&E'NNr%   Nr   )rC   rO   r!   rh   rC   rh   )
r-   r.   r/   r0   r7   r$   r   rr   staticmethodrt   r'   r%   r#   rb   rb     s         :       4* * * *48 8 8 ) ) ) \) ) )r%   rb   c                  x     e Zd ZdZdd fd
Zd Zd  fdZd!d"dZd!d"dZd!d"dZ	e
d!d#d            Zd$dZ xZS )%Mosaica  Mosaic augmentation for image datasets.

    This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image. The
    augmentation is applied to a dataset with a given probability.

    Attributes:
        dataset: The dataset on which the mosaic augmentation is applied.
        imgsz (int): Image size (height and width) after mosaic pipeline of a single image.
        p (float): Probability of applying the mosaic augmentation. Must be in the range 0-1.
        n (int): The grid size, either 4 (for 2x2) or 9 (for 3x3).
        border (tuple[int, int]): Border size for height and width.

    Methods:
        get_indexes: Return a list of random indexes from the dataset.
        get_params: Compute mosaic layout parameters.
        apply_image: Allocate canvas and paste images into mosaic.
        apply_instances: Concatenate and clip instances for mosaic.
        _update_labels: Update labels with padding.
        _cat_labels: Concatenate labels and clips mosaic border instances.

    Examples:
        >>> from ultralytics.data.augment import Mosaic
        >>> dataset = YourDataset(...)  # Your image dataset
        >>> mosaic_aug = Mosaic(dataset, imgsz=640, p=0.5, n=4)
        >>> augmented_labels = mosaic_aug(original_labels)
      r      imgszrK   rg   floatnc                   d|cxk    rdk    sn J d| d            |dv s
J d            t                                          ||           || _        | dz  | dz  f| _        || _        | j        j        d	k    | _        d
S )a]  Initialize the Mosaic augmentation object.

        This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image. The
        augmentation is applied to a dataset with a given probability.

        Args:
            dataset (Any): The dataset on which the mosaic augmentation is applied.
            imgsz (int): Image size (height and width) after mosaic pipeline of a single image.
            p (float): Probability of applying the mosaic augmentation. Must be in the range 0-1.
            n (int): The grid size, either 4 (for 2x2) or 9 (for 3x3).
        r   r   3The probability should be in range [0, 1], but got rQ   >   r   	   zgrid must be equal to 4 or 9.)re   rg      ramN)superr7   r   borderr   re   cachebuffer_enabled)r    re   r   rg   r   r^   s        r#   r7   zMosaic.__init__  s     A}}}}}}}}}XTUXXX}}}F{{{;{{{A...
v{UFaK0"l0E9r%   c                      j         r5t          j        t           j        j                   j        dz
            S  fdt           j        dz
            D             S )a  Return a list of random indexes from the dataset for mosaic augmentation.

        This method selects random image indexes either from a buffer or from the entire dataset, depending on the
        'buffer_enabled' attribute. It is used to choose images for creating mosaic augmentations.

        Returns:
            (list[int]): A list of random image indexes. The length of the list is n-1, where n is the number of images
                used in the mosaic (either 3 or 8, depending on whether n is 4 or 9).

        Examples:
            >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
            >>> indexes = mosaic.get_indexes()
            >>> print(len(indexes))  # Output: 3
        rj   kc                d    g | ],}t          j        d t          j                  dz
            -S r   rj   rw   )rH   _r    s     r#   rJ   z&Mosaic.get_indexes.<locals>.<listcomp>  s4    XXXFN1c$,&7&7!&;<<XXXr%   )r   rl   choicesr5   re   bufferr   rangerW   s   `r#   rr   zMosaic.get_indexes  sb      	Y>$t|':";";tvzJJJJXXXXeDFUVJFWFWXXXXr%   r!   rh   rC   c                t   t                                          |          }|                    d          
J d            t          |                    dg                     s
J d            | j        g }| j        dk    rfd| j        D             \  }}t          d          D ]}|dk    r|n|d         |d	z
           }|d
         }|                    d|j        dd                   \  }	}
|dk    rFt          ||
z
  d          t          ||	z
  d          ||f\  }}}}|
||z
  z
  |	||z
  z
  |
|	f\  }}}}n|d	k    rS|t          ||	z
  d          t          ||
z   dz            |f\  }}}}d|	||z
  z
  t          |
||z
            |	f\  }}}}n|dk    rSt          ||
z
  d          ||t          dz  ||	z             f\  }}}}|
||z
  z
  d|
t          ||z
  |	          f\  }}}}nf|dk    r`||t          ||
z   dz            t          dz  ||	z             f\  }}}}ddt          |
||z
            t          ||z
  |	          f\  }}}}||z
  }||z
  }|                    ||||||||||||	|
fd           ސn| j        dk    rd\  }}d\  }}t          d          D ]}|dk    r|n|d         |d	z
           }|d
         }|                    d|j        dd                   \  }	}
|dk    r|
z   |	z   f}|	|
}}n|d	k    r|	z
  |
z   f}n|dk    r|z   |	z
  |z   |
z   f}n|dk    r|z   |z   |
z   |	z   f}n|dk    r|z   |z   |z   |
z   |z   |	z   f}n{|dk    r|z   |
z
  |z   |z   |z   |	z   f}n\|dk    r|z   |z
  |
z
  |z   |z   |z
  |z   |	z   f}n7|dk    r|
z
  |z   |	z
  |z   f}n|dk    r|
z
  |z   |z
  |	z
  |z   |z
  f}|dd         \  }}d |D             \  }}}}|                    ||||||||	|
fd           |	|
}}||d<   |S )zCompute mosaic layout parameters.

        Args:
            labels (dict[str, Any]): Input labels dictionary.

        Returns:
            (dict[str, Any]): Parameters including 'layout' with per-patch geometry.
        
rect_shapeNz'rect and mosaic are mutually exclusive.rk   z-There are no other images for mosaic augment.r   c              3  j   K   | ]-}t          t          j        | d z  |z                       V  .dS )r   N)rK   rl   rm   )rH   r|   ss     r#   r~   z$Mosaic.get_params.<locals>.<genexpr>  sA      NNQc&.!QUQY7788NNNNNNr%   r   rj   imgresized_shaper      )labels_patchx1ay1ax2ay2ax1by1bx2by2bpadwpadh	img_shaper   )r   r   NN            c              3  6   K   | ]}t          |d           V  dS )r   N)maxr   s     r#   r~   z$Mosaic.get_params.<locals>.<genexpr>8  s*      !7!7#a))!7!7!7!7!7!7r%   )r   x1y1x2y2r   r   r   layout)r   r   getrS   r   r   r   r   shaper   minr=   ) r    r!   r"   r   ycxcrI   r   r   hwr   r   r   r   r   r   r   r   r   r   hpwph0w0cr   r   r   r   r   r^   s                                  @r#   r   zMosaic.get_params  s    ##F++zz,''//1Z///6::lB//00aa2aaa0J6Q;;NNNN$+NNNFB1XX ! !)*avvVL5I!a%5P"5)#''2A2GG166),R!VQR!VQR)O&Cc3)*cCi!sSy/1a)O&Cc33!VV)+Sa^^SaQ=O=OQS)S&Cc3)*AsOSC#I=N=NPQ)Q&Cc33!VV),R!VQRQUBQRFASAS)S&Cc3)*cCi!QC#Iq@Q@Q)Q&Cc33!VV)+RR!VQU1C1CSQPRUVPVEWEW)W&Cc3)*As1cCi/@/@#cCiQRBSBS)S&Cc3SySy(4"""""""" $ $&'V    %!D Vq[[FBFB1XX % %)*avvVL5I!a%5P"5)#''2A2GG1661a!eQU*ABB!VV1q5!a%*AA!VVBAq2vz14AA!VVB1r6A:q1u4AA!VVBBB
AFQJ>AA!VVB
AFAFAFQJ>AA!VVBaRR"a"fqjHAA!VVAq2vz1a"f4AA!VVAq2v{Q1r6B;>ArrU
d!7!7Q!7!7!7BB(4     $ $&'V	 	   AB!xr%   Nr"   dict[str, Any] | Nonec                   |d         }| j         dk    rt          j        | j        dz  | j        dz  |d         j        d         fdt          j                  }|D ]o}|d         }|d         }|d         |d	         |d
         |d         f\  }}	}
}|d         |d         |d         |d         f\  }}}}|||||f         ||	|||
f<   p||d<   n| j         dk    rt          j        | j        dz  | j        dz  |d         j        d         fdt          j                  }|D ]v}|d         }|d         }|d         |d         |d         |d         f\  }}}}|d         |d         }}||z
  ||z
  }}|||z
  z   |||z
  z   }}|||||f         |||||f<   w|| j        d          | j        d         | j        d          | j        d         f         |d<   |S )a  Apply mosaic augmentation to the image.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img'.
            params (dict | None): Parameters from get_params, including 'layout'.

        Returns:
            (dict): Updated labels with mosaic image.
        r   r   r   r   r   dtyper   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   )r   npfullr   r   uint8r   )r    r!   r"   r   img4r}   r   r   r   r   r   r   r   r   r   r   img9r   r   r   r   r   r   s                          r#   r   zMosaic.apply_imageI  s6    !6Q;;7DJNDJNF5M<OPQ<RSUX`b`hiiiD ? ?#N3"5)%)%[$u+tE{DQVK%W"S#s%)%[$u+tE{DQVK%W"S#s),SWc#g-=)>SWc#g%&& F5MMVq[[7DJNDJNF5M<OPQ<RSUX`b`hiiiD ; ;#N3"5)!%dT$ZdT$Z!OBB!&\4<d9b4iS"r'?C27OS%(S#c')9%:RUBrE\"" $+a.4;q>!ADKPQN?UYU`abUcCc!cdF5Mr%   c           	        |d         }g }|D ]}| j         dk    r|d         }|d         }n,|d         | j        d         z   }|d         | j        d         z   }|                     |d         |||                    d                    }|                    |           |                     |          }	|                    |	           |S )	a5  Apply mosaic augmentation to instances.

        Args:
            labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'.
            params (dict | None): Parameters from get_params, including 'layout'.

        Returns:
            (dict): Updated labels with concatenated instances.
        r   r   r   r   r   rj   r   r   )r   r   _update_labelsr   r=   _cat_labelsupdate)
r    r!   r"   r   mosaic_labelsr}   r   r   r   final_labelss
             r#   r   zMosaic.apply_instancesj  s     ! 	/ 	/Dv{{F|F|F|dk!n4F|dk!n4..tN/CT4QUQYQYZeQfQfggL  ....''66l###r%   c                8   |                     d          /t          d |                     dg           D                       r|S |d         }| j        dk    rt          j        | j        dz  | j        dz  fdt          j        	          }|D ]}|d
         }|                     d          }|"|d         |d         |d         |d         f\  }}	}
}|d         |d         |d         |d         f\  }}}}|||||f         ||	|||
f<   ||d<   n| j        dk    rt          j        | j        dz  | j        dz  fdt          j        	          }|D ]}|d
         }|                     d          }|"|d         |d         |d         |d         f\  }}}}|d         |d         }}||z
  ||z
  }}|||z
  z   |||z
  z   }}|||||f         |||||f<   || j        d          | j        d         | j        d          | j        d         f         |d<   |S )a#  Apply mosaic augmentation to semantic mask.

        Args:
            labels (dict[str, Any]): Dictionary containing 'semantic_mask'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels with concatenated semantic mask.
        semantic_maskNc              3  D   K   | ]}|                     d           du V  dS )r   N)r   )rH   ms     r#   r~   z(Mosaic.apply_semantic.<locals>.<genexpr>  sD       7
 7
/0AEE/""d*7
 7
 7
 7
 7
 7
r%   rk   r   r   r      r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   )r   allr   r   r   r   r   r   )r    r!   r"   r   mask4r}   r   maskr   r   r   r   r   r   r   r   mask9r   r   r   r   r   r   s                          r#   r   zMosaic.apply_semantic  s    ::o&&.3 7
 7
4:JJ|R4P4P7
 7
 7
 4
 4
. M!6Q;;GTZ!^TZ!^<cRRRE A A#N3#''88<%)%[$u+tE{DQVK%W"S#s%)%[$u+tE{DQVK%W"S#s*.s3wC/?*@c#gs3w&''&+F?##Vq[[GTZ!^TZ!^<cRRRE 	= 	=#N3#''88<!%dT$ZdT$Z!OBB!&\4<d9b4iS"r'?C27OS&*3s7CG+;&<beRUl##&+T[^Odk!n,Lt{[\~o`d`klm`nNn,n&oF?#r%   r   r   r   tuple[int, int] | Nonec                    ||n| d         j         dd         \  }}| d                             d           | d                             ||           | d                             ||           | S )a  Update label coordinates with padding values.

        This method adjusts the bounding box coordinates of object instances in the labels by adding padding
        values. It also denormalizes the coordinates if they were previously normalized.

        Args:
            labels (dict[str, Any]): A dictionary containing image and instance information.
            padw (int): Padding width to be added to the x-coordinates.
            padh (int): Padding height to be added to the y-coordinates.
            img_shape (tuple[int, int] | None): Optional (h, w) of the original patch image. Needed because apply_image
                may overwrite labels["img"] with the mosaic canvas before apply_instances runs.

        Returns:
            (dict): Updated labels dictionary with adjusted instance coordinates.

        Examples:
            >>> labels = {"img": np.zeros((100, 100, 3)), "instances": Instances(...)}
            >>> padw, padh = 50, 50
            >>> updated_labels = Mosaic._update_labels(labels, padw, padh)
        Nr   r   	instancesxyxyformat)r   convert_bboxdenormalizeadd_padding)r!   r   r   r   nhnws         r#   r   zMosaic._update_labels  s}    , (39LRaR9PB{(((777{''B///{''d333r%   r   list[dict[str, Any]]c                   |si S g }g }| j         dz  }|D ]8}|                    |d                    |                    |d                    9|d         d         |d         d         ||ft          j        |d          t	          j        |d          d}|d                             ||           |d                                         }|d         |         |d<   d	|d         v r|d         d	         |d	<   |S )
a=  Concatenate and process labels for mosaic augmentation.

        This method combines labels from multiple images used in mosaic augmentation, clips instances to the mosaic
        border, and removes zero-area boxes.

        Args:
            mosaic_labels (list[dict[str, Any]]): A list of label dictionaries for each image in the mosaic.

        Returns:
            (dict[str, Any]): A dictionary containing concatenated and processed labels for the mosaic image, including:
                - im_file (str): File path of the first image in the mosaic.
                - ori_shape (tuple[int, int]): Original shape of the first image.
                - resized_shape (tuple[int, int]): Shape of the mosaic image (imgsz * 2, imgsz * 2).
                - cls (np.ndarray): Concatenated class labels.
                - instances (Instances): Concatenated instance annotations.
                - texts (list[str], optional): Text labels if present in the original labels.

        Examples:
            >>> mosaic = Mosaic(dataset, imgsz=640)
            >>> mosaic_labels = [{"cls": np.array([0, 1]), "instances": Instances(...)} for _ in range(4)]
            >>> result = mosaic._cat_labels(mosaic_labels)
            >>> print(result.keys())
            dict_keys(['im_file', 'ori_shape', 'resized_shape', 'cls', 'instances'])
        r   r   r   r   im_file	ori_shapeaxis)r   r   r   r   r   rz   )r   r=   r   concatenater   clipremove_zero_area_boxes)r    r   r   r   r   r!   r   goods           r#   r   zMosaic._cat_labels  s)   2  	I	
Q# 	2 	2FJJve}%%%VK01111 %Q'	2&q)+6#U^>#q))".yqAAA
 
 	[!&&ue444K(??AA*51$7UmA&&&$1!$4W$=L!r%   )r   r   r   )r   rK   rg   r   r   rK   r   r,   r!   rh   r"   r   rC   rh   )r   rK   r   rK   r   r   rC   rh   )r   r   rC   rh   )r-   r.   r/   r0   r7   rr   r   r   r   r   r   r   r   __classcell__r^   s   @r#   r   r     s	        6: : : : : : :(Y Y Y(] ] ] ] ] ]~    B    2( ( ( ( (T     \6. . . . . . . .r%   r   c                  P     e Zd ZdZdd fdZd fdZdddZdddZdddZ xZ	S )MixUpa  Apply MixUp augmentation to image datasets.

    This class implements the MixUp augmentation technique as described in the paper [mixup: Beyond Empirical Risk
    Minimization](https://arxiv.org/abs/1710.09412). MixUp combines two images and their labels using a random weight.

    Attributes:
        dataset (Any): The dataset to which MixUp augmentation will be applied.
        pre_transform (Callable | None): Optional transform to apply before MixUp.
        p (float): Probability of applying MixUp augmentation.

    Methods:
        get_params: Compute MixUp parameters including blend ratio.
        apply_image: Blend images using MixUp.
        apply_instances: Concatenate instances for MixUp.

    Examples:
        >>> from ultralytics.data.augment import MixUp
        >>> dataset = YourDataset(...)  # Your image dataset
        >>> mixup = MixUp(dataset, p=0.5)
        >>> augmented_labels = mixup(original_labels)
    Nr   rg   r   rC   rO   c                P    t                                          |||           dS )a=  Initialize the MixUp augmentation object.

        MixUp is an image augmentation technique that combines two images by taking a weighted sum of their pixel values
        and labels. This implementation is designed for use with the Ultralytics YOLO framework.

        Args:
            dataset (Any): The dataset to which MixUp augmentation will be applied.
            pre_transform (Callable | None): Optional transform to apply to images before MixUp.
            p (float): Probability of applying MixUp augmentation to an image. Must be in the range [0, 1].
        rd   N)r   r7   )r    re   rf   rg   r^   s       r#   r7   zMixUp.__init__  s*     	KKKKKr%   r!   rh   c                    t                                          |          }t          j                            dd          |d<   |S )zCompute MixUp parameters.

        Args:
            labels (dict[str, Any]): Input labels dictionary.

        Returns:
            (dict[str, Any]): Parameters including mix ratio 'r'.
        g      @@r)r   r   r   rl   betar    r!   r"   r^   s      r#   r   zMixUp.get_params  s:     ##F++innT400sr%   r"   r   c                    |d         }|d         d         }|d         |z  |d         d|z
  z  z                        t          j                  |d<   |S )a	  Blend images using MixUp.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img'.
            params (dict | None): Parameters from get_params, including 'r'.

        Returns:
            (dict): Updated labels with blended image.
        r  rk   r   r   rj   )astyper   r   )r    r!   r"   r  labels2s        r#   r   zMixUp.apply_image+  sU     3K&q)*WU^q1u-EEMMbhWWur%   c                    |d         d         }t          j        |d         |d         gd          |d<   t          j        |d         |d         gd          |d<   |S )a  Concatenate instances for MixUp.

        Args:
            labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels with concatenated instances.
        rk   r   r   r   r   )r   r   r   )r    r!   r"   r  s       r#   r   zMixUp.apply_instances:  se     &q)'3VK5H'R]J^4_fghhh{uwu~'FJJur%   c                    |                     d          |S |d         d         }|                     d          |S |d         }|dk     r|d                                         |d<   |S )a  Apply MixUp augmentation to semantic segmentation masks.

        Args:
            labels (dict[str, Any]): Primary image labels containing 'semantic_mask' and 'mix_labels'.
            params (dict[str, Any] | None): Parameters dict with key 'r' (mix ratio). Defaults to None.

        Returns:
            (dict[str, Any]): Updated labels with the semantic mask replaced by the mixed image's mask if r < 0.5.
        r   Nrk   r   r        ?)r   copy)r    r!   r"   r  r  s        r#   r   zMixUp.apply_semanticI  ss     ::o&&.M&q);;''/M3Ks77&-o&>&C&C&E&EF?#r%   r   )rg   r   rC   rO   r   r,   r  )
r-   r.   r/   r0   r7   r   r   r   r   r  r  s   @r#   r  r    s         ,L L L L L L L                     r%   r  c                  X     e Zd ZdZdd fdZddZd fdZdddZdddZdddZ	 xZ
S ) CutMixa  Apply CutMix augmentation to image datasets as described in the paper https://arxiv.org/abs/1905.04899.

    CutMix combines two images by replacing a random rectangular region of one image with the corresponding region from
    another image, and adjusts the labels proportionally to the area of the mixed region.

    Attributes:
        dataset (Any): The dataset to which CutMix augmentation will be applied.
        pre_transform (Callable | None): Optional transform to apply before CutMix.
        p (float): Probability of applying CutMix augmentation.
        beta (float): Beta distribution parameter for sampling the mixing ratio.
        num_areas (int): Number of areas to try to cut and mix.

    Methods:
        get_params: Compute CutMix parameters including cut area and filtered indexes.
        apply_image: Copy patch from secondary image into primary image.
        apply_instances: Clip and concatenate instances for CutMix.
        _rand_bbox: Generate random bounding box coordinates for the cut region.

    Examples:
        >>> from ultralytics.data.augment import CutMix
        >>> dataset = YourDataset(...)  # Your image dataset
        >>> cutmix = CutMix(dataset, p=0.5)
        >>> augmented_labels = cutmix(original_labels)
    Nr   r   r   rg   r   r	  	num_areasrK   rC   rO   c                l    t                                          |||           || _        || _        dS )a  Initialize the CutMix augmentation object.

        Args:
            dataset (Any): The dataset to which CutMix augmentation will be applied.
            pre_transform (Callable | None): Optional transform to apply before CutMix.
            p (float): Probability of applying CutMix augmentation.
            beta (float): Beta distribution parameter for sampling the mixing ratio.
            num_areas (int): Number of areas to try to cut and mix.
        rd   N)r   r7   r	  r  )r    re   rf   rg   r	  r  r^   s         r#   r7   zCutMix.__init__y  s6     	KKK	"r%   widthheighttuple[int, int, int, int]c                4   t           j                            | j        | j                  }t          j        d|z
            }t	          ||z            }t	          ||z            }t           j                            |          }t           j                            |          }t          j        ||dz  z
  d|          }	t          j        ||dz  z
  d|          }
t          j        ||dz  z   d|          }t          j        ||dz  z   d|          }|	|
||fS )a  Generate random bounding box coordinates for the cut region.

        Args:
            width (int): Width of the image.
            height (int): Height of the image.

        Returns:
            (tuple[int]): (x1, y1, x2, y2) coordinates of the bounding box.
        r   r   r   )r   rl   r	  sqrtrK   rx   r   )r    r  r  lam	cut_ratiocut_wcut_hcxcyr   r   r   r   s                r#   
_rand_bboxzCutMix._rand_bbox  s     innTY	22GC#I&&	EI%&&FY&'' Yu%%Yv&& WR%1*_a//WR%1*_a00WR%1*_a//WR%1*_a002r2~r%   r!   rh   c                l   
 t                                          |          }|d         j        dd         \  
t          j        
 fdt           j                  D             t          j                  }t          ||d         j	                  }t          j
        |                    d          d	k              d	         }t          |          d	k    rd
|d<   |S |d         d	         }|t          j                            |                   }t          |d         |d         j	                                      d	          }t          j
        |t          |d         j                  rdndk              d	         }	t          |	          d	k    rd
|d<   |S ||d<   |	|d<   |d<   
|d<   |S )zCompute CutMix parameters.

        Args:
            labels (dict[str, Any]): Input labels dictionary.

        Returns:
            (dict[str, Any]): Parameters including 'skip', 'area', and 'indexes2'.
        r   Nr   c                <    g | ]}                               S r'   )r!  )rH   r   r   r    r   s     r#   rJ   z%CutMix.get_params.<locals>.<listcomp>  s'    UUU!1 5 5UUUr%   r   r   rj   r   r   Tskiprk   {Gz?皙?areaindexes2r   r   )r   r   r   r   asarrayr   r  float32r   bboxesnonzerosumrS   rl   choicer   segments)r    r!   r"   	cut_areasioa1idxr  r'  ioa2r(  r   r   r^   s   `         @@r#   r   zCutMix.get_params  s    ##F++e}"2A2&1JUUUUUUuT^?T?TUUU]_]ghhh		6+#6#=>>jq))Q.//2s88q==!F6NM&q)))#../T
GK$8$?@@HHKK:ds6+3F3O/P/P'YttVYZ[[\]^x==A!F6NMv%zssr%   r"   r   c                    |                     d          r|S |d                             t          j                  \  }}}}|d         d         }|d         ||||f         |d         ||||f<   |S )zApply CutMix to the image.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels with mixed image.
        r$  r'  rk   r   r   )r   r  r   int32)r    r!   r"   r   r   r   r   r  s           r#   r   zCutMix.apply_image  s     ::f 	M..rx88BB&q)&-enRUBrE\&BubeRUl#r%   c                z   |                     d          r|S |d         d         }|d         |d         }}|d         }|d         }|d         |         }|                    d	           |                    ||           |                    t          j                  \  }	}
}}|                    |	 |
            |                    ||	z
  ||
z
             |                    |	|
           t	          j        |d
         |d
         |         gd          |d
<   t          j        |d         |gd          |d<   |S )a  Apply CutMix to instances.

        Args:
            labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels with mixed instances.
        r$  rk   r   r   r   r'  r(  r   r   r   r   )
r   r   r   r  r   r5  r   r   r   r   )r    r!   r"   r  r   r   r'  r(  
instances2r   r   r   r   s                r#   r   zCutMix.apply_instances  sE    ::f 	M&q)c{F3K1f~*%[)(3
'''q!$$$RX..BBsRC(((Rb)))r2&&&uwu~h7O'PWXYYYu'3VK5H*4U\]^^^{r%   c                t   |                     d          r|S |                     d          |S |d                             t          j                  \  }}}}|d         d         }|                     d          <|d                                         }|d         ||||f         |||||f<   ||d<   |S )a  Apply CutMix augmentation to semantic segmentation masks.

        Args:
            labels (dict[str, Any]): Primary image labels containing 'semantic_mask' and 'mix_labels'.
            params (dict[str, Any] | None): Parameters dict with 'area' (bounding box coordinates) and 'skip' (bool
                flag). Defaults to None.

        Returns:
            (dict[str, Any]): Updated labels with the semantic mask region replaced by the mixed image's mask.
        r$  r   Nr'  rk   r   )r   r  r   r5  r  )	r    r!   r"   r   r   r   r   r  r   s	            r#   r   zCutMix.apply_semantic  s     ::f 	M::o&&.M..rx88BB&q);;''3/*//11D!(!9"R%B,!GDB2&*F?#r%   )Nr   r   r   )rg   r   r	  r   r  rK   rC   rO   )r  rK   r  rK   rC   r  r   r,   r  )r-   r.   r/   r0   r7   r!  r   r   r   r   r  r  s   @r#   r  r  _  s         2# # # # # # #   :     B    "    <        r%   r  c                      e Zd ZdZ	 	 	 	 	 	 d1d2dZd3dZd4dZd5d6dZd5d6dZd7dZ	d8d"Z
d9d$Zd5d6d%Ze	 	 	 	 d:d;d0            ZdS )<RandomPerspectiveaj  Implement random perspective and affine transformations on images and corresponding annotations.

    This class applies random rotations, translations, scaling, shearing, and perspective transformations to images and
    their associated bounding boxes, segments, and keypoints. It can be used as part of an augmentation pipeline for
    object detection and instance segmentation tasks.

    Attributes:
        degrees (float): Maximum absolute degree range for random rotations.
        translate (float): Maximum translation as a fraction of the image size.
        scale (float): Scaling factor range, e.g., scale=0.1 means 0.9-1.1.
        shear (float): Maximum shear angle in degrees.
        perspective (float): Perspective distortion factor.
        size (tuple[int, int] | None): Output size (width, height). If None, uses the input image size.

    Methods:
        get_params: Compute affine transformation matrix and related parameters.
        apply_image: Warp the image using the affine matrix.
        apply_instances: Transform bounding boxes, segments, and keypoints.
        apply_semantic: Placeholder for semantic segmentation mask transformation.
        apply_bboxes: Transform bounding boxes using the affine matrix.
        apply_segments: Transform segments and generate new bounding boxes.
        apply_keypoints: Transform keypoints using the affine matrix.
        box_candidates: Filter transformed bounding boxes based on size and aspect ratio.

    Examples:
        >>> transform = RandomPerspective(degrees=10, translate=0.1, scale=0.1, shear=10)
        >>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
        >>> labels = {"img": image, "cls": np.array([0, 1]), "instances": Instances(...)}
        >>> result = transform(labels)
        >>> transformed_image = result["img"]
        >>> transformed_instances = result["instances"]
    r   r&  r  Ndegreesr   	translatescalefloat | tuple[float, float]shearperspectivesizer   c                Z    || _         || _        || _        || _        || _        || _        dS )a  Initialize RandomPerspective object with transformation parameters.

        This class implements random perspective and affine transformations on images and corresponding bounding boxes,
        segments, and keypoints. Transformations include rotation, translation, scaling, and shearing.

        Args:
            degrees (float): Degree range for random rotations.
            translate (float): Fraction of total width and height for random translation.
            scale (float | tuple[float, float]): Scaling factor interval. If float, e.g. 0.5 means resize between
                50%-150%. If tuple, interpreted as absolute (min, max) scale factors.
            shear (float): Shear intensity (angle in degrees).
            perspective (float): Perspective distortion factor.
            size (tuple[int, int] | None): Output size (width, height). If None, uses the input image size.
        Nr;  r<  r=  r?  r@  rA  )r    r;  r<  r=  r?  r@  rA  s          r#   r7   zRandomPerspective.__init__.  s3    . "

&			r%   r   
np.ndarraytuple[int, int]rC   tuple[np.ndarray, float]c                v   t          j        dt           j                  }|j        d          dz  |d<   |j        d          dz  |d<   t          j        dt           j                  }t	          j        | j         | j                  |d<   t	          j        | j         | j                  |d	<   t          j        dt           j                  }t	          j        | j         | j                  }t          | j	        t          t          f          r,t	          j        | j	        d         | j	        d                   }n%t	          j        d| j	        z
  d| j	        z             }t          j        |d
|          |dd<   t          j        dt           j                  }t          j        t	          j        | j         | j                  t          j        z  dz            |d<   t          j        t	          j        | j         | j                  t          j        z  dz            |d<   t          j        dt           j                  }	t	          j        d| j        z
  d| j        z             |d         z  |	d<   t	          j        d| j        z
  d| j        z             |d         z  |	d<   |	|z  |z  |z  |z  }
|
|fS )at  Compute the affine transformation matrix without applying it.

        Args:
            img (np.ndarray): Input image used to determine center and dimensions.
            size (tuple[int, int]): Size of the output image (width, height) used for clipping translation transform.

        Returns:
            (M, scale): 3x3 transformation matrix and scale factor.
        r   r   rj   r   )r   r   r   rj   r   )r   r   )r   rj   r   r   )anglecenterr=  N   r   )rj   r   r  )r   eyer*  r   rl   rm   r@  r;  r4   r=  r   r5   cv2getRotationMatrix2Dmathtanr?  pir<  )r    r   rA  CPRar   STMs              r#   _compute_affine_matrixz(RandomPerspective._compute_affine_matrixL  sI    F1BJ'''9Q<-!#$9Q<-!#$ F1BJ'''.$"2!2D4DEE$.$"2!2D4DEE$ F1BJ'''NDL=$,77dj5$-00 	?tz!}djm<<AAq4:~q4:~>>A'aaHHH"1" F1BJ'''(6>4:+tzBBTWLsRSS$(6>4:+tzBBTWLsRSS$ F1BJ'''.t~!5sT^7KLLtTUwV$.t~!5sT^7KLLtTUwV$ EAIMA!tr%   r!   rh   c                    |d         }| j         |j        d         |j        d         fn| j         }|j        dd         }|                     ||          \  }}||||dS )a%  Compute affine transformation parameters shared across image and instances.

        Args:
            labels (dict[str, Any]): Input labels dictionary containing 'img'.

        Returns:
            (dict): Parameters including 'M' (affine matrix), 'scale', 'orig_shape', and 'size'.
        r   Nrj   r   r   )rY  r=  
orig_shaperA  )rA  r   rZ  )r    r!   r   rA  r\  rY  r=  s          r#   r   zRandomPerspective.get_paramsx  sk     Um/3y/@	!cil++diYrr]
..sD995j$OOOr%   r"   r   c                   |d         }|d         }|d         }|d         |j         d         k    sA|d         |j         d         k    s*|t          j        d          k                                    rS| j        rt          j        |||d          }n t          j        ||d	d
         |d          }|j        d
k    r|d         }||d<   |j         d	d
         |d<   |S )a-  Apply affine warp to the image.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img'.
            params (dict | None): Parameters from get_params, including 'M' and 'size'.

        Returns:
            (dict): Updated labels with warped image and 'resized_shape'.
        r   rY  rA  r   rj   r   )r   r   r   )dsizeborderValueNr   .Nr   )	r   r   rM  anyr@  rN  warpPerspective
warpAffinendim)r    r!   r"   r   rY  rA  s         r#   r   zRandomPerspective.apply_image  s     Um3Kf~Gsy|##tAw#)A,'>'>APQNCWCWCYCY'> Z)#q/ZZZnS!BQB%tYYYx1}})nu"%)BQB-r%   c                   |d         }|                     d          }|                    d            |j        |d         ddd           |d         }|d	         }|                     |j        |          }|j        }|j        }	t          |          r |                     |||d
                   \  }}|	| 	                    |	||d
                   }	t          |||	dd          }
 |
j        |d
           |                    ||d           |                     |j        j        |
j        j        t          |          rdnd          }|
|         |d<   ||         |d<   |S )aQ  Apply affine transformation to object instances.

        Args:
            labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'.
            params (dict | None): Parameters from get_params, including 'M' and 'scale'.

        Returns:
            (dict): Updated labels with transformed and filtered instances.
        r   r   r   r   r\  Nr   rY  r=  rA  F)bbox_format
normalizedT)scale_wscale_h	bbox_onlyr%  r&  )box1box2area_thr)rn   r   r   apply_bboxesr+  r/  	keypointsrS   apply_segmentsapply_keypointsr   r   r=  box_candidatesrX  )r    r!   r"   r   r   rY  r=  r+  r/  ro  new_instancesrI   s               r#   r   z!RandomPerspective.apply_instances  s    UmJJ{++	f---	vl3DDbD9::3Kw""9#3Q77%'	x== 	P#228QvOOFH ,,Y6&>JJI!&(I6^cdddF6N++ 	uEEE!#-*>*@SVW_S`S`Kj44fj   
 
 ,A.{Aur%   r+  rY  c                   t          |          }|dk    r|S t          j        |dz  df|j                  }|ddg df                             |dz  d          |ddddf<   ||j        z  }| j        r|ddddf         |ddddf         z  n|ddddf                             |d          }|ddg d	f         }|ddg d
f         }t          j        |                    d          |                    d          |	                    d          |	                    d          f|j                                      d|          j        S )a  Apply affine transformation to bounding boxes.

        This function applies an affine transformation to a set of bounding boxes using the provided transformation
        matrix.

        Args:
            bboxes (np.ndarray): Bounding boxes in xyxy format with shape (N, 4), where N is the number of bounding
                boxes.
            M (np.ndarray): Affine transformation matrix with shape (3, 3).

        Returns:
            (np.ndarray): Transformed bounding boxes in xyxy format with shape (N, 4).

        Examples:
            >>> rp = RandomPerspective()
            >>> bboxes = np.array([[10, 10, 20, 20], [30, 30, 40, 40]], dtype=np.float32)
            >>> M = np.eye(3, dtype=np.float32)
            >>> transformed_bboxes = rp.apply_bboxes(bboxes, M)
        r   r   r   r   N)r   rj   r   r   r   r   r   rj   r   r   )r   r   r   r   )rj   r   r   r   rj   )
rS   r   onesr   reshaperX  r@  r   r   r   )r    r+  rY  r   xyr|   ys          r#   rn  zRandomPerspective.apply_bboxes  sh   ( KK66MWa!eQZv|44411166667??AqII111bqb5	!#X(,(8GbBQBi"QQQ!V*$$bBQBiPPQRTUVV qqq,,,qqq,,,~quuQxxq15588QUU1XXFfl[[[ccdeghiikkr%   r/  tuple[np.ndarray, np.ndarray]c                `   |j         dd         \  }}|dk    rg |fS t          j        ||z  df|j                  }|                    dd          }||ddddf<   ||j        z  }|ddddf         |ddddf         z  }|                    |dd          }t          j        fd|D             d          }|d                             |dddd	f         |ddddf                   |d<   |d
                             |ddd	df         |ddddf                   |d
<   ||fS )a  Apply affine transformations to segments and generate new bounding boxes.

        This function applies affine transformations to input segments and generates new bounding boxes based on the
        transformed segments. It clips the transformed segments to fit within the new bounding boxes.

        Args:
            segments (np.ndarray): Input segments with shape (N, M, 2), where N is the number of segments and M is the
                number of points in each segment.
            M (np.ndarray): Affine transformation matrix with shape (3, 3).
            size (tuple[int, int]): Size of the output image (width, height) used for clipping the segments.

        Returns:
            bboxes (np.ndarray): New bounding boxes with shape (N, 4) in xyxy format.
            segments (np.ndarray): Transformed and clipped segments with shape (N, M, 2).

        Examples:
            >>> rp = RandomPerspective()
            >>> segments = np.random.rand(10, 500, 2)  # 10 segments with 500 points each
            >>> M = np.eye(3)  # Identity transformation matrix
            >>> new_bboxes, new_segments = rp.apply_segments(segments, M)
        Nr   r   r   r   r   c                J    g | ]}t          |d          d                    S r   )r   )rH   rw  rA  s     r#   rJ   z4RandomPerspective.apply_segments.<locals>.<listcomp>  s-    PPP;r47DG<<PPPr%   .r   rj   .rj   r   )r   r   ru  r   rv  rX  stackr   )r    r/  rY  rA  r   numrw  r+  s      `    r#   rp  z RandomPerspective.apply_segments  sn   0 #366x<Wa#gq\888##B**111bqb5	!#X2A2YAAAqsF#::aQ''PPPPxPPPRSTT#F+001Q31Q3PP#F+001Q31Q3PPxr%   ro  c                \   |j         dd         \  }}|dk    r|S t          j        ||z  df|j                  }|d                             ||z  d          }|dddf                             ||z  d          |ddddf<   ||j        z  }|ddddf         |ddddf         z  }|dddf         dk     |dddf         dk     z  |dddf         |d         k    z  |dddf         |d         k    z  }d||<   t          j        ||gd	
                              ||d          S )au  Apply affine transformation to keypoints.

        This method transforms the input keypoints using the provided affine transformation matrix. It handles
        perspective rescaling if necessary and updates the visibility of keypoints that fall outside the image
        boundaries after transformation.

        Args:
            keypoints (np.ndarray): Array of keypoints with shape (N, K, 3), where N is the number of instances, K is
                the number of keypoints per instance, and 3 represents (x, y, visibility).
            M (np.ndarray): 3x3 affine transformation matrix.
            size (tuple[int, int]): Size of the output image (width, height) used to determine visibility of keypoints.

        Returns:
            (np.ndarray): Transformed keypoints array with the same shape as input (N, K, 3).

        Examples:
            >>> random_perspective = RandomPerspective()
            >>> keypoints = np.random.rand(5, 17, 3)  # 5 instances, 17 keypoints each
            >>> M = np.eye(3)  # Identity transformation
            >>> transformed_keypoints = random_perspective.apply_keypoints(keypoints, M)
        Nr   r   r   r   ).r   rj   .r   r   )r   r   ru  r   rv  rX  r   )	r    ro  rY  rA  r   nkptrw  visibleout_masks	            r#   rq  z!RandomPerspective.apply_keypoints  si   , /"1"%466Wa$h])/:::F#++AHa88c2A2g&..q4x;;111bqb5	!#X2A2YAAAqsF#qqq!tHqLR1X\2bAha6HIRPQPQPQSTPTXX\]^X_M_`~r7m"555==aqIIIr%   c                   d|vs|d         |S |d         }|d         }|d         }|d         |j         d         k    sA|d         |j         d         k    s*|t          j        d          k                                    rV| j        r$t          j        |||t
          j        d	          }n+t          j        ||dd
         |t
          j        d	          }||d<   |S )aK  Apply affine transformation to semantic segmentation mask.

        Args:
            labels (dict[str, Any]): Dictionary containing 'semantic_mask'.
            params (dict | None): Parameters from get_params, including 'M' and 'size'.

        Returns:
            (dict): Updated labels with transformed semantic mask.
        r   NrY  rA  r   rj   r   r   )r^  flagsr_  r   )	r   r   rM  ra  r@  rN  rb  INTER_NEARESTrc  )r    r!   r"   r   rY  rA  s         r#   r   z RandomPerspective.apply_semantic4  s     &((F?,C,KMo&3Kf~Gtz!}$$Q4:a=(@(@a26RS99nEYEYE[E[(@ i*4$cFWehiii~dAbqbESEVdghhh"&r%   r   d   缉ؗҜ<rk  rl  wh_thrrK   ar_thrrm  epsc                   | d         | d         z
  | d         | d         z
  }}|d         |d         z
  |d         |d         z
  }	}t          j        ||	|z   z  |	||z   z            }
||k    |	|k    z  ||	z  ||z  |z   z  |k    z  |
|k     z  S )a  Compute candidate boxes for further processing based on size and aspect ratio criteria.

        This method compares boxes before and after augmentation to determine if they meet specified thresholds for
        width, height, aspect ratio, and area. It's used to filter out boxes that have been overly distorted or reduced
        by the augmentation process.

        Args:
            box1 (np.ndarray): Original boxes before augmentation, shape (4, N) where N is the number of boxes. Format
                is [x1, y1, x2, y2] in absolute coordinates.
            box2 (np.ndarray): Augmented boxes after transformation, shape (4, N). Format is [x1, y1, x2, y2] in
                absolute coordinates.
            wh_thr (int): Width and height threshold in pixels. Boxes smaller than this in either dimension are
                rejected.
            ar_thr (int): Aspect ratio threshold. Boxes with an aspect ratio greater than this value are rejected.
            area_thr (float): Area ratio threshold. Boxes with an area ratio (new/old) less than this value are
                rejected.
            eps (float): Small epsilon value to prevent division by zero.

        Returns:
            (np.ndarray): Boolean array of shape (N,) indicating which boxes are candidates. True values correspond to
                boxes that meet all criteria.

        Examples:
            >>> random_perspective = RandomPerspective()
            >>> box1 = np.array([[0, 0, 100, 100], [0, 0, 50, 50]]).T
            >>> box2 = np.array([[10, 10, 90, 90], [5, 5, 45, 45]]).T
            >>> candidates = random_perspective.box_candidates(box1, box2)
            >>> print(candidates)
            [True True]
        r   r   r   rj   )r   maximum)rk  rl  r  r  rm  r  w1h1w2h2ars              r#   rr  z RandomPerspective.box_candidatesK  s    N a47"DGd1g$5Ba47"DGd1g$5BZb3hrCx99VV,R27S=0IH0TUY[^dYdeer%   )r   r&  r  r   r   N)r;  r   r<  r   r=  r>  r?  r   r@  r   rA  r   )r   rD  rA  rE  rC   rF  r   r,   r  )r+  rD  rY  rD  rC   rD  )r/  rD  rY  rD  rA  rE  rC   ry  )ro  rD  rY  rD  rA  rE  rC   rD  )r   r  r&  r  )rk  rD  rl  rD  r  rK   r  rK   rm  r   r  r   rC   rD  )r-   r.   r/   r0   r7   rZ  r   r   r   rn  rp  rq  r   r   rr  r'   r%   r#   r:  r:    sF        F -0 '+    <* * * *XP P P P    0( ( ( ( (T l  l  l  lD%  %  %  % N J  J  J  JD    .  )f )f )f )f \)f )f )fr%   r:  c                  &    e Zd ZdZddd	ZdddZd
S )	RandomHSVa  Randomly adjust the Hue, Saturation, and Value (HSV) channels of an image.

    This class applies random HSV augmentation to images within predefined limits set by hgain, sgain, and vgain.

    Attributes:
        hgain (float): Maximum variation for hue. Range is typically [0, 1].
        sgain (float): Maximum variation for saturation. Range is typically [0, 1].
        vgain (float): Maximum variation for value. Range is typically [0, 1].

    Methods:
        apply_image: Apply random HSV augmentation to an image.

    Examples:
        >>> import numpy as np
        >>> from ultralytics.data.augment import RandomHSV
        >>> augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
        >>> image = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
        >>> labels = {"img": image}
        >>> labels = augmenter(labels)
        >>> augmented_image = labels["img"]
    r  hgainr   sgainvgainrC   rO   c                0    || _         || _        || _        dS )a  Initialize the RandomHSV object for random HSV (Hue, Saturation, Value) augmentation.

        This class applies random adjustments to the HSV channels of an image within specified limits.

        Args:
            hgain (float): Maximum variation for hue. Should be in the range [0, 1].
            sgain (float): Maximum variation for saturation. Should be in the range [0, 1].
            vgain (float): Maximum variation for value. Should be in the range [0, 1].
        Nr  r  r  )r    r  r  r  s       r#   r7   zRandomHSV.__init__  s     




r%   Nr"   r   c                   |d         }|j         d         dk    r|S | j        s| j        s| j        r|j        }t
          j                            ddd          | j        | j        | j        gz  }t          j        dd|j                  }||d         dz  z   dz  	                    |          }t          j
        ||d         dz   z  dd	          	                    |          }t          j
        ||d
         dz   z  dd	          	                    |          }	d|d<   t          j        t          j        |t          j                            \  }
}}t          j        t          j        |
|          t          j        ||          t          j        ||	          f          }t          j        |t          j        |           |S )a  Apply random HSV augmentation to an image within predefined limits.

        This method modifies the input image by randomly adjusting its Hue, Saturation, and Value (HSV) channels. The
        adjustments are made within the limits set by hgain, sgain, and vgain during initialization.

        Args:
            labels (dict[str, Any]): A dictionary containing image data and metadata. Must include an 'img' key with the
                image as a numpy array.
            params (dict[str, Any] | None): Unused parameters for API compatibility.

        Returns:
            (dict[str, Any]): The labels dictionary with the HSV-augmented image.

        Examples:
            >>> hsv_augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
            >>> labels = {"img": np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)}
            >>> labels = hsv_augmenter.apply_image(labels)
            >>> augmented_img = labels["img"]
        r   r   r   rj   r      r   rL  r   r   )dst)r   r  r  r  r   r   rl   rm   aranger  r   rN  splitcvtColorCOLOR_BGR2HSVmergeLUTCOLOR_HSV2BGR)r    r!   r"   r   r   r  r|   lut_huelut_satlut_valhuesatvalim_hsvs                 r#   r   zRandomHSV.apply_image  s   ( Um9R=AM: 	= 	=tz 	=IE	!!"a++tz4:tz.RRA	!S000AAaD3J#-55e<<Gga1Q4!8na55<<UCCGga1Q4!8na55<<UCCGGAJIcl38I&J&JKKMCcYW 5 5swsG7L7LcgVY[bNcNcdeeFL!2<<<<r%   )r  r  r  )r  r   r  r   r  r   rC   rO   r,   )r"   r   )r-   r.   r/   r0   r7   r   r'   r%   r#   r  r  x  sP         ,    % % % % % % %r%   r  c                  <    e Zd ZdZdddZddZddZddZddZdS )
RandomFlipa;  Apply a random horizontal or vertical flip to an image with a given probability.

    This class performs random image flipping and updates corresponding instance annotations such as bounding boxes and
    keypoints.

    Attributes:
        p (float): Probability of applying the flip. Must be between 0 and 1.
        direction (str): Direction of flip, either 'horizontal' or 'vertical'.
        flip_idx (array-like): Index mapping for flipping keypoints, if applicable.

    Methods:
        __call__: Apply the random flip transformation to an image and its annotations.

    Examples:
        >>> transform = RandomFlip(p=0.5, direction="horizontal")
        >>> result = transform({"img": image, "instances": instances})
        >>> flipped_image = result["img"]
        >>> flipped_instances = result["instances"]
    r  
horizontalNrg   r   	directionstrflip_idxlist[int] | NonerC   rO   c                    |dv sJ d|             d|cxk    rdk    sn J d| d            || _         || _        || _        dS )a  Initialize the RandomFlip class with probability and direction.

        This class applies a random horizontal or vertical flip to an image with a given probability. It also updates
        any instances (bounding boxes, keypoints, etc.) accordingly.

        Args:
            p (float): The probability of applying the flip. Must be between 0 and 1.
            direction (str): The direction to apply the flip. Must be 'horizontal' or 'vertical'.
            flip_idx (list[int] | None): Index mapping for flipping keypoints, if any.

        Raises:
            AssertionError: If direction is not 'horizontal' or 'vertical', or if p is not between 0 and 1.
        >   verticalr  z2Support direction `horizontal` or `vertical`, got r   r   r   rQ   N)rg   r  r  )r    rg   r  r  s       r#   r7   zRandomFlip.__init__  so     66668xmv8x8x666A}}}}}}}}}XTUXXX}}}" r%   r!   rh   c                    |d         }|d         }|j         dd         \  }}|j        rdn|}|j        rdn|}t          j                    | j        k     ||| j        | j        dS )a  Compute random flip parameters.

        Args:
            labels (dict[str, Any]): Input labels dictionary containing 'img' and 'instances'.

        Returns:
            (dict): Parameters including 'flip' (bool), 'h', 'w', 'direction', and 'flip_idx'.
        r   r   Nr   rj   )flipr   r   r  r  )r   rg  rl   rg   r  r  )r    r!   r   r   r   r   s         r#   r   zRandomFlip.get_params  s{     Um;'	y!}1%,AA1%,AA1MOOdf,
 
 	
r%   r"   c                    |d         }|d         rA|d         dk    rt          j        |          }n |d         dk    rt          j        |          }t          j        |          |d<   |S )a  Apply flip to the image.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img'.
            params (dict): Parameters from get_params.

        Returns:
            (dict): Updated labels with flipped (or unchanged) image.
        r   r  r  r  r  )r   flipudfliplrascontiguousarrayr    r!   r"   r   s       r#   r   zRandomFlip.apply_image  sn     Um&> 	%k"j00inn$44inn,S11ur%   c                   |                     d          }|                    d           |d         r|d         dk    r|                    |d                    n'|d         dk    r|                    |d	                    |d
         8|j        1t          j        |j        dd|d
         ddf                   |_        ||d<   |S )a  Apply flip to object instances.

        Args:
            labels (dict[str, Any]): Dictionary containing 'instances'.
            params (dict): Parameters from get_params.

        Returns:
            (dict): Updated labels with flipped (or unchanged) instances.
        r   xywhr   r  r  r  r   r  r   r  N)rn   r   r  r  ro  r   r  )r    r!   r"   r   s       r#   r   zRandomFlip.apply_instances  s     JJ{++	f---&> 	jk"j00  ----$44  ---j!-)2E2Q&(&:9;NqqqRXYcRdfgfgfgOg;h&i&i	#'{r%   c                    d|vs|d         |S |d         rw|d         dk    r0t          j        t          j        |d                             |d<   n;|d         dk    r/t          j        t          j        |d                             |d<   |S )a$  Apply flip to semantic segmentation mask.

        Args:
            labels (dict[str, Any]): Dictionary containing 'semantic_mask'.
            params (dict): Parameters from get_params.

        Returns:
            (dict): Updated labels with flipped (or unchanged) semantic mask.
        r   Nr  r  r  r  )r   r  r  r  r   s      r#   r   zRandomFlip.apply_semantic.  s     &((F?,C,KM&> 	ck"j00*,*>ryP_I`?a?a*b*b''$44*,*>ryP_I`?a?a*b*b'r%   )r  r  N)rg   r   r  r  r  r  rC   rO   r   r!   rh   r"   rh   rC   rh   )	r-   r.   r/   r0   r7   r   r   r   r   r'   r%   r#   r  r    s         (! ! ! ! !*
 
 
 
,   &   ,     r%   r  c                  x    e Zd ZdZdddddddej        fd(dZd)d*dZd+dZd,dZ	d,dZ
d,d Zed-d'            ZdS ).	LetterBoxa  Resize image and padding for detection, instance segmentation, pose.

    This class resizes and pads images to a specified shape while preserving aspect ratio. It also updates corresponding
    labels and bounding boxes.

    Attributes:
        new_shape (tuple): Target shape (height, width) for resizing.
        auto (bool): Whether to use minimum rectangle.
        scale_fill (bool): Whether to stretch the image to new_shape.
        scaleup (bool): Whether to allow scaling up. If False, only scale down.
        stride (int): Stride for rounding padding.
        center (bool): Whether to center the image or align to top-left.

    Methods:
        __call__: Resize and pad image, update labels and bounding boxes.

    Examples:
        >>> transform = LetterBox(new_shape=(640, 640))
        >>> result = transform(labels)
        >>> resized_img = result["img"]
        >>> updated_instances = result["instances"]
    r   r   FT    r   	new_shaperE  autobool
scale_fillscaleuprK  striderK   padding_valueinterpolationc	                v    || _         || _        || _        || _        || _        || _        || _        || _        dS )a  Initialize LetterBox object for resizing and padding images.

        This class is designed to resize and pad images for object detection, instance segmentation, and pose estimation
        tasks. It supports various resizing modes including auto-sizing, scale-fill, and letterboxing.

        Args:
            new_shape (tuple[int, int]): Target size (height, width) for the resized image.
            auto (bool): If True, use minimum rectangle to resize. If False, use new_shape directly.
            scale_fill (bool): If True, stretch the image to new_shape without padding.
            scaleup (bool): If True, allow scaling up. If False, only scale down.
            center (bool): If True, center the placed image. If False, place image in top-left corner.
            stride (int): Stride of the model (e.g., 32 for YOLOv5).
            padding_value (int): Value for padding the image. Default is 114.
            interpolation (int): Interpolation method for resizing. Default is cv2.INTER_LINEAR.
        N)r  r  r  r  r  rK  r  r  )	r    r  r  r  r  rK  r  r  r  s	            r#   r7   zLetterBox.__init__Z  sD    4 #	$**r%   Nr!   r   imagerD  rC   dict[str, Any] | np.ndarrayc                   |i }t          |          dk    }|||d<   |                     |          }|                     ||          }|s|                     ||          }|                     ||          }|r|d         S |S )a  Resize and pad an image for object detection, instance segmentation, or pose estimation tasks.

        This method applies letterboxing to the input image, which involves resizing the image while maintaining its
        aspect ratio and adding padding to fit the new shape. It also updates any associated labels accordingly.

        Args:
            labels (dict[str, Any] | None): A dictionary containing image data and associated labels, or empty dict if
                None.
            image (np.ndarray | None): The input image as a numpy array. If None, the image is taken from 'labels'.

        Returns:
            (dict[str, Any] | np.ndarray): If 'labels' is provided, returns an updated dictionary with the resized and
                padded image, updated labels, and additional metadata. If 'labels' is empty, returns the resized and
                padded image only.

        Examples:
            >>> letterbox = LetterBox(new_shape=(640, 640))
            >>> result = letterbox(labels={"img": np.zeros((480, 640, 3)), "instances": Instances(...)})
            >>> resized_img = result["img"]
            >>> updated_instances = result["instances"]
        Nr   r   )rS   r   r   r   r   )r    r!   r  return_image_onlyr"   s        r#   r$   zLetterBox.__call__}  s    , >FKK1,!F5M((!!&&11  	:))&&99F$$VV44 	!%= r%   rh   c           	        |d         }|j         dd         }|                    d| j                  }t          |t                    r||f}t          |d         |d         z  |d         |d         z            }| j        st          |d          }||f}t          |d         |z            t          |d         |z            f}|d         |d         z
  |d         |d         z
  }	}| j        r5t          j
        || j                  t          j
        |	| j                  }	}n>| j        r7d\  }}	|d         |d         f}|d         |d         z  |d         |d         z  f}| j        r
|dz  }|	dz  }	| j        rt          |	d	z
            ndt          |	d	z             }}
| j        rt          |d	z
            ndt          |d	z             }}|||||
|||d
S )a   Compute letterboxing parameters.

        Args:
            labels (dict[str, Any]): Input labels dictionary containing 'img'.

        Returns:
            (dict): Parameters including 'orig_shape', 'new_shape', 'ratio', padding, and resize info.
        r   Nr   r   r   rj   r   )r   r   r&  )r\  r  ratio	new_unpadtopbottomleftright)r   rn   r  r4   rK   r   r  roundr  r   modr  r  rK  )r    r!   r   r   r  r  r  r  dwdhr  r  r  r  s                 r#   r   zLetterBox.get_params  s    Um	"1"JJ|T^<<	i%% 	/"I.I 	!uQx'1a)@AA| 	AsA 1%(Q,''uQx!|)<)<<	1	!,ilYq\.IB9 	EVB,,bfR.E.EBB_ 	EFB"1y|4IaL58+Yq\E!H-DDE; 	!GB!GB)-;eBHooo!U28__V)-;eBHooo!U28__e  ""	
 	
 		
r%   r"   c           
     &   |d         }|j         dd         }|d         }|ddd         |k    r/t          j        ||| j                  }|j        dk    r|d         }|j         \  }}}|d         |d	         }
}	|d
         |d         }}|dk    r/t          j        ||	|
||t          j        | j        fdz            }nCt          j	        ||	z   |
z   ||z   |z   |f| j        |j
                  }|||	|	|z   |||z   f<   |}||d<   |d         |d<   |S )zResize and pad the image.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img'.
            params (dict): Parameters from get_params.

        Returns:
            (dict): Updated labels with resized and padded image.
        r   Nr   r  r   r  r`  r  r  r  r  r   rN   )
fill_valuer   r  r   )r   rN  resizer  rd  copyMakeBorderBORDER_CONSTANTr  r   r   r   )r    r!   r"   r   r   r  r   r   r   r  r  r  r  pad_imgs                 r#   r   zLetterBox.apply_image  sR    Um	"1";'	2;)##*S)4;MNNNCx1}})n)1aUmVH%5VVnfWoe66$S&$s/B4K]J_bcJc  CC gq3w/TE1A1ERVRdloluvvvG69GC#'M4$(?23Cu"("5r%   c           	     F   d|vs|d         |S |d         }|d         }|d         }|ddd         |k    r!t          j        ||t           j                  }|d         |d         }}|d	         |d
         }	}t          j        |||||	t           j        d          }||d<   |S )a(  Apply letterboxing to semantic segmentation mask.

        Args:
            labels (dict[str, Any]): Dictionary containing 'semantic_mask'.
            params (dict): Parameters from get_params.

        Returns:
            (dict): Updated labels with resized and padded semantic mask.
        r   Nr\  r  r   r  r  r  r  r  r   r  )rN  r  r  r  r  )
r    r!   r"   r   r   r  r  r  r  r  s
             r#   r   zLetterBox.apply_semantic  s     &((F?,C,KMo&|$;'	2;)##:dIS=NOOODUmVH%5VVnfWoe!$VT5#BU]`aaa"&r%   c                    d|v r1|                      ||d         |d         |d         |d                   }|                    d          r|d         |d         |d         ff|d<   |S )a  Update instance coordinates after letterboxing.

        Args:
            labels (dict[str, Any]): Dictionary containing 'instances'.
            params (dict): Parameters from get_params.

        Returns:
            (dict): Updated labels with transformed instances.
        r   r  r  r  r\  	ratio_pad)r   r   r   s      r#   r   zLetterBox.apply_instances  s|     &  ((&.RXY^R_aghtauvvF::k"" 	Y#)+#6PU8W"XF;r%   r  tuple[float, float]r   r   r   r\  c                    | d                              d            | d         j        |ddd            | d         j        |  | d                             ||           | S )a  Update labels after applying letterboxing to an image.

        This method modifies the bounding box coordinates of instances in the labels to account for resizing and padding
        applied during letterboxing.

        Args:
            labels (dict[str, Any]): A dictionary containing image labels and instances.
            ratio (tuple[float, float]): Scaling ratios (width, height) applied to the image.
            padw (float): Padding width added to the image.
            padh (float): Padding height added to the image.
            orig_shape (tuple[int, int]): Original image shape (height, width) before resizing.

        Returns:
            (dict[str, Any]): Updated labels dictionary with modified instance coordinates.

        Examples:
            >>> letterbox = LetterBox(new_shape=(640, 640))
            >>> labels = {"instances": Instances(...)}
            >>> ratio = (0.5, 0.5)
            >>> padw, padh = 10, 20
            >>> updated_labels = letterbox._update_labels(labels, ratio, padw, padh, (480, 640))
        r   r   r   Nr   )r   r   r=  r   )r!   r  r   r   r\  s        r#   r   zLetterBox._update_labels  su    4 	{(((777'{'DDbD)9::!{!5)){''d333r%   )r  rE  r  r  r  r  r  r  rK  r  r  rK   r  rK   r  rK   r   )r!   r   r  rD  rC   r  r   r  )r!   rh   r  r  r   r   r   r   r\  rE  rC   rh   )r-   r.   r/   r0   rN  INTER_LINEARr7   r$   r   r   r   r   r   r   r'   r%   r#   r  r  B  s         2 &0   -!+ !+ !+ !+ !+F" " " " "H/
 /
 /
 /
b! ! ! !F   .        \  r%   r  c                  \     e Zd ZdZdd fdZd fdZd fdZdddZdddZdddZ	 xZ
S )	CopyPasteaU  CopyPaste class for applying Copy-Paste augmentation to image datasets.

    This class implements the Copy-Paste augmentation technique as described in the paper "Simple Copy-Paste is a Strong
    Data Augmentation Method for Instance Segmentation" (https://arxiv.org/abs/2012.07177). It combines objects from
    different images to create new training samples.

    Attributes:
        dataset (Any): The dataset to which Copy-Paste augmentation will be applied.
        pre_transform (Callable | None): Optional transform to apply before Copy-Paste.
        p (float): Probability of applying Copy-Paste augmentation.

    Methods:
        get_params: Compute CopyPaste parameters including selected instances and mask.
        apply_image: Draw contours and paste pixels for CopyPaste.
        apply_instances: Concatenate selected instances for CopyPaste.

    Examples:
        >>> from ultralytics.data.augment import CopyPaste
        >>> dataset = YourDataset(...)  # Your image dataset
        >>> copypaste = CopyPaste(dataset, p=0.5)
        >>> augmented_labels = copypaste(original_labels)
    Nr  r  rg   r   moder  rC   rO   c                    t                                          |||           |dv sJ d| d            || _        dS )z_Initialize CopyPaste object with dataset, pre_transform, and probability of applying CopyPaste.rd   >   r  mixupz1Expected `mode` to be `flip` or `mixup`, but got rQ   N)r   r7   r  )r    re   rf   rg   r  r^   s        r#   r7   zCopyPaste.__init__U  sT    KKK((((*e^b*e*e*e(((			r%   r!   rh   c                d   t          |d         j                  dk    s| j        dk    r|S | j        dk    rY|                     |          }|                     ||          }|                     ||          }|                     ||          }|S t                      	                    |          S )z9Apply Copy-Paste augmentation to an image and its labels.r   r   r  )
rS   r/  rg   r  r   r   r   r   r   r$   r
  s      r#   r$   zCopyPaste.__call__[  s    vk"+,,11TVq[[M9__V,,F%%ff55F))&&99F((88FMww'''r%   c                   i }| j         dk    r?t                                          |          }|                    di g          d         }ni }|d         j        dd         \  }}t          |d                   }|                    d	           |                    ||           |r"t          |                    d                    nd}|$t          |          }|                    |           t          |j
        |j
                  }t          j        |d
k                         d                    d         }	t          |	          }
t          j        |                    d          |	                   }|	|         }	|	dt#          | j        |
z                     }t          j        ||ft          j                  }||d<   ||d<   ||d<   ||d<   |                    d          |d<   |                    d          |d<   |S )zCompute CopyPaste parameters.

        Args:
            labels (dict[str, Any]): Input labels dictionary.

        Returns:
            (dict[str, Any]): Parameters including 'instances2', 'selected', and 'im_new'.
        r  rk   r   r   Nr   r   r   r   g333333?rj   r7  selectedim_newr   labels2_clslabels2_img)r  r   r   r   r   r   r   r   r  r   r+  r   r,  r   rS   argsortr   r  rg   zerosr   )r    r!   r"   r  r   r   r   r7  ioaru   r   
sorted_idxr  r  r^   s                 r#   r   zCopyPaste.get_paramsg  s    9WW''//Fjjt44Q7GGGe}"2A2&1VK011	f---a###;BLXgkk+66777
!),,Ja   z()*:;;*cDj--a0011!4LLZ

7 344
*%.U46A:.../1a&"(++'{)|%z!x 'E 2 2} 'E 2 2}r%   r"   r   c                   |d                                          }|d         }|d         }|d         }|D ]M}t          j        ||j        |g                             t
          j                  ddt          j                   N|                    d          }|t          j	        |d          }|j
        d	k    r|d
         }|                    t                    }	||	         ||	<   ||d<   |S )zApply CopyPaste to the image.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels with pasted objects.
        r   r7  r  r  r   rj   r  Nr   r`  )r  rN  drawContoursr/  r  r   r5  FILLEDr   r  rd  r  )
r    r!   r"   imr7  r  r  jresultrI   s
             r#   r   zCopyPaste.apply_image  s     E]!!L)
*%! 	c 	cAVZ%8!%=%D%DRX%N%NPRTUWZWabbbbM**>Xb!__F;!I&FMM$q	1ur%   c                   |d         }|d         }|d         }|d         }|                     d          }|D ]D}t          j        |||n||g         fd          }t          j        |||g         fd          }E||d<   ||d<   |S )	a  Apply CopyPaste to instances.

        Args:
            labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'.
            params (dict | None): Parameters from get_params.

        Returns:
            (dict): Updated labels with concatenated instances.
        r   r7  r  r   r  Nr   r   )r   r   r   r   )	r    r!   r"   r   r7  r  r   r  r  s	            r#   r   zCopyPaste.apply_instances  s     ;'	L)
*%Umjj// 	T 	TA.#{7NTWZ[Y\']!^efgggC!-y*aS/.JQRSSSIIu'{r%   c                h   |                     d          }||S | j        dk    r0|                     di g          d                              d          nt          j        |d          }||S |d                             t
                    }|                                }||         ||<   ||d<   |S )z/Apply CopyPaste to semantic segmentation masks.r   Nr  rk   r   rj   r  )r   r  rN  r  r  r  r  )r    r!   r"   r   sourcepasteds         r#   r   zCopyPaste.apply_semantic  s    zz/**<MKO9X_K_K_L2$//266GGGehemnrtuevev>M!((..yy{{f~V"&r%   )NNr  r  )rg   r   r  r  rC   rO   r   r,   r  )r-   r.   r/   r0   r7   r$   r   r   r   r   r  r  s   @r#   r  r  =  s         .      
( 
( 
( 
( 
( 
() ) ) ) ) )V    <    0        r%   r  c                  $    e Zd ZdZddd
ZddZdS )Albumentationsa<  Albumentations transformations for image augmentation.

    This class applies various image transformations using the Albumentations library. It includes operations such as
    Blur, Median Blur, conversion to grayscale, Contrast Limited Adaptive Histogram Equalization (CLAHE), random changes
    in brightness and contrast, RandomGamma, and image quality reduction through compression.

    Attributes:
        p (float): Probability of applying the transformations.
        transform (albumentations.Compose): Composed Albumentations transforms.
        contains_spatial (bool): Indicates if the transforms include spatial operations.

    Methods:
        __call__: Apply the Albumentations transformations to the input labels.

    Examples:
        >>> transform = Albumentations(p=0.5)
        >>> augmented_labels = transform(labels)

    Notes:
        - Requires Albumentations version 1.0.3 or higher.
        - Spatial transforms are handled differently to ensure bbox compatibility.
        - Some transforms are applied with very low probability (0.01) by default.
    r   Nrg   r   r6   list | NonerC   rO   c           
        || _         d| _        t          d          }	 ddl}d|j        d<   ddl}t          |j        dd           h d	||                    d
          |	                    d
          |
                    d
          |                    d
          |                    d          |                    d          |                    dd          gn|}t          fd|D                       | _        | j        r-|                    ||                    ddg                    n|                    |          | _        t'          | j        d          r+| j                            t+          j                               t/          j        |d                    d |D                       z              dS # t4          $ r Y dS t6          $ r#}t/          j        | |            Y d}~dS d}~ww xY w)ar  Initialize the Albumentations transform object for YOLO bbox formatted parameters.

        This class applies various image augmentations using the Albumentations library, including Blur, Median Blur,
        conversion to grayscale, Contrast Limited Adaptive Histogram Equalization, random changes of brightness and
        contrast, RandomGamma, and image quality reduction through compression.

        Args:
            p (float): Probability of applying the augmentations. Must be between 0 and 1.
            transforms (list | None): List of custom Albumentations transforms. If None, uses default transforms.
        Nzalbumentations: r   1NO_ALBUMENTATIONS_UPDATEz1.0.3T)hard>(   D4CropFlipNoOpr  AffineLambdaResizeRotate	Transpose	XYMasking
CenterCrop
CropAndPad
RandomCrop
SafeRotateGridDropoutMaskDropoutPadIfNeededPerspectiveRandomScalePixelDropoutVerticalFlipCoarseDropoutMorphologicalGridDistortionHorizontalFlipLongestMaxSizeRandomRotate90PiecewiseAffineRandomSizedCropSmallestMaxSizeElasticTransformShiftScaleRotateOpticalDistortionRandomGridShuffleRandomResizedCropBBoxSafeRandomCropRandomCropFromBordersRandomSizedBBoxSafeCropCropNonEmptyMaskIfExistsr%  rg   r   )K   r  )quality_rangerg   c              3  4   K   | ]}|j         j        v V  d S r,   )r^   r-   )rH   r>   spatial_transformss     r#   r~   z*Albumentations.__init__.<locals>.<genexpr>D  s0      'n'n_h	(;(DHZ(Z'n'n'n'n'n'nr%   yoloclass_labels)r   label_fields)bbox_paramsset_random_seedr[   c              3  R   K   | ]"}|j         	|                     d d          V  #dS )zalways_apply=False,  N)rg   replacer   s     r#   r~   z*Albumentations.__init__.<locals>.<genexpr>M  s>      *h*hZ[dedg*ha6>>:PRT+U+U*h*h*h*h*h*hr%   )rg   r>   r   osenvironalbumentationsr   __version__Blur
MedianBlurToGrayCLAHERandomBrightnessContrastRandomGammaImageCompressionra  contains_spatialr2   
BboxParamshasattrr9  torchinitial_seedr
   infor_   ImportError	Exception)	r    rg   r6   prefixr=  ArX  er4  s	           @r#   r7   zAlbumentations.__init__  sN    ,--Q	(III58BJ12&&&&!-t<<<<)" )" )"l % FFTFNNLL4L((HHtH$$GGdGOO...55MMCM((&&Y#&FF     %('n'n'n'nlm'n'n'n$n$nD! ("		!VSaRb)c)c	dddYYq\\ N
 t~'899 E..u/A/C/CDDDK*h*h_`*h*h*h!h!hhiiiii 	 	 	DD 	( 	( 	(K61'''''''''	(s   F)G 
H	H!G??Hr!   rh   c                
   | j         t          j                    | j        k    r|S |d         }|j        d         dk    r|S | j        r|d         }t          |          r|d                             d            |d         j        |j        dd         ddd           |d         j        }|                      |||	          }t          |d
                   dk    rb|d         |d<   t          j
        |d
                                       dd          |d<   t          j
        |d         t          j                  }|d                             |           n%|                      |d                   d         |d<   |S )a~  Apply Albumentations transformations to input labels.

        This method applies a series of image augmentations using the Albumentations library. It can perform both
        spatial and non-spatial transformations on the input image and its corresponding labels.

        Args:
            labels (dict[str, Any]): A dictionary containing image data and annotations. Expected keys are:
                - 'img': np.ndarray representing the image
                - 'cls': np.ndarray of class labels
                - 'instances': object containing bounding boxes and other instance information

        Returns:
            (dict[str, Any]): The input dictionary with augmented image and updated annotations.

        Examples:
            >>> transform = Albumentations(p=0.5)
            >>> labels = {
            ...     "img": np.random.rand(640, 640, 3),
            ...     "cls": np.array([0, 1]),
            ...     "instances": Instances(bboxes=np.array([[0, 0, 1, 1], [0.5, 0.5, 0.8, 0.8]])),
            ... }
            >>> augmented = transform(labels)
            >>> assert augmented["img"].shape == (640, 640, 3)

        Notes:
            - The method applies transformations with probability self.p.
            - Spatial transforms update bounding boxes, while non-spatial transforms only modify the image.
            - Requires the Albumentations library to be installed.
        Nr   r   r   r   r   r  r   )r  r+  r6  r6  r   r  rj   r+  r   )r+  )r  )r>   rl   rg   r   rH  rS   r   	normalizer+  r   arrayrv  r*  r   )r    r!   r  r   r+  news         r#   r$   zAlbumentations.__call__S  su   < >!V]__tv%=%=ME]8A;!M  	I-C3xx 
:{#00888-{#-rx|DDbD/ABB,3nn2f3nOOs>*++a//$'LF5M$&HS-@$A$A$I$I"a$P$PF5MXc(m2:FFFF{#**&*999 NNN??HF5Mr%   )r   N)rg   r   r6   r  rC   rO   r   )r-   r.   r/   r0   r7   r$   r'   r%   r#   r  r    sQ         0`( `( `( `( `(D5 5 5 5 5 5r%   r  c                  Z    e Zd ZdZ	 	 	 	 	 	 	 	 	 d)d*dZd+dZd,d-dZd,d-dZd.d!Zd/d(Z	dS )0Formataz  A class for formatting image annotations for object detection, instance segmentation, and pose estimation tasks.

    This class standardizes image and instance annotations to be used by the `collate_fn` in PyTorch DataLoader.

    Attributes:
        bbox_format (str): Format for bounding boxes. Options are 'xywh' or 'xyxy'.
        normalize (bool): Whether to normalize bounding boxes.
        return_mask (bool): Whether to return instance masks for segmentation.
        return_keypoint (bool): Whether to return keypoints for pose estimation.
        return_obb (bool): Whether to return oriented bounding boxes.
        mask_ratio (int): Downsample ratio for masks.
        mask_overlap (bool): Whether to overlap masks.
        batch_idx (bool): Whether to keep batch indexes.
        bgr (float): The probability to return BGR images.

    Methods:
        __call__: Format labels dictionary with image, classes, bounding boxes, and optionally masks and keypoints.
        _format_img: Convert image from Numpy array to PyTorch tensor.
        _format_segments: Convert polygon points to bitmap masks.

    Examples:
        >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True)
        >>> formatted_labels = formatter(labels)
        >>> img = formatted_labels["img"]
        >>> bboxes = formatted_labels["bboxes"]
        >>> masks = formatted_labels["masks"]
    r  TFr   r   rf  r  rT  r  return_maskreturn_keypoint
return_obb
mask_ratiorK   mask_overlap	batch_idxbgrr   c
                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        dS )a  Initialize the Format class with given parameters for image and instance annotation formatting.

        This class standardizes image and instance annotations for object detection, instance segmentation, and pose
        estimation tasks, preparing them for use in PyTorch DataLoader's `collate_fn`.

        Args:
            bbox_format (str): Format for bounding boxes. Options are 'xywh', 'xyxy', etc.
            normalize (bool): Whether to normalize bounding boxes to [0,1].
            return_mask (bool): If True, returns instance masks for segmentation tasks.
            return_keypoint (bool): If True, returns keypoints for pose estimation tasks.
            return_obb (bool): If True, returns oriented bounding boxes.
            mask_ratio (int): Downsample ratio for masks.
            mask_overlap (bool): If True, allows mask overlap.
            batch_idx (bool): If True, keeps batch indexes.
            bgr (float): Probability of returning BGR images instead of RGB.
        N)	rf  rT  rY  rZ  r[  r\  r]  r^  r_  )
r    rf  rT  rY  rZ  r[  r\  r]  r^  r_  s
             r#   r7   zFormat.__init__  sK    8 '"&.$$("r%   r!   rh   rC   c                l   |                     d          }||j        dd         nd\  }}|                    dt          j        g                     }|                    dd          }|1|                    | j                   |                    ||           |||||rt          |          ndd	S )
a  Compute formatting parameters shared across image and instance formatting.

        Extracts image dimensions and pops instance annotations from labels, converting bounding box format
        and denormalizing coordinates for downstream tensor creation.

        Args:
            labels (dict[str, Any]): Input labels dictionary containing 'img', 'cls', and 'instances'.

        Returns:
            (dict[str, Any]): Parameters including 'h', 'w', 'cls', 'instances', and 'nl'.
        r   Nr   rI  r   r   r   r   )r   r   r   r   nl)	r   r   rn   r   rU  r   rf  r   rS   )r    r!   r   r   r   r   r   s          r#   r   zFormat.get_params  s     jj #sy!}}V1jj--JJ{D11	 ""$*:";;;!!!Q'''Qs\eJl#i...klmmmr%   Nr"   r   c                f    |                     dd          }||                     |          |d<   |S )aO  Format image from Numpy array to PyTorch tensor.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img' as a numpy array.
            params (dict[str, Any] | None): Unused parameters for API compatibility.

        Returns:
            (dict[str, Any]): Updated labels with 'img' as a PyTorch tensor.
        r   N)rn   _format_imgr  s       r#   r   zFormat.apply_image  s8     jj%%? ,,S11F5Mr%   c                >   |                     dt          j        g                     }|                     d          }|
J d            |                     dd          }|                     dd          }|                     dd          }| j        r |r|                     ||||          \  }}}t          j        |          }t          j        |                    d	                    }	|j        d         r|		                                s't          j
        || j        z  || j        z            }
nB| j        r%|	|d                                         d	z
           }
n||	ddddf         z                      d          j        }
|                    d
          d	k    }|                                rk|                    d          }||ddddf         z  }|                                d	z   ||dk    <   |                    d
          }|	||                  |
|<   nTt          j
        | j        rd	n||| j        z  || j        z            }t          j
        || j        z  || j        z            }
||d<   |
                                |d<   |rt          j        |          nt          j
        |d	          |d<   |rt          j        |j                  nt          j
        |df          |d<   | j        rk|j        t          j        dd          nt          j        |j                  |d<   | j        r,|d         dxx         |z  cc<   |d         dxx         |z  cc<   | j        rQt5          |j                  r&t9          t          j        |j                            nt          j
        d          |d<   | j        r8|d         ddddgfxx         |z  cc<   |d         ddd	dgfxx         |z  cc<   | j        rt          j
        |          |d<   |S )a  Format instance annotations into PyTorch tensors.

        Converts class labels, bounding boxes, masks, and keypoints into tensors suitable for
        collation in PyTorch DataLoader.

        Args:
            labels (dict[str, Any]): Dictionary to populate with formatted tensors.
            params (dict[str, Any]): Parameters from get_params containing 'h', 'w', 'cls', 'instances', 'nl'.

        Returns:
            (dict[str, Any]): Updated labels with formatted instance tensors.
        r   r   Nz1instances are required for Format.apply_instancesr   r   r   rb  rj   )dimrH  r   masks	sem_masksr   r+  r   ro  r|  r}  )r   r   r   r^  )r   r   rU  rY  _format_segmentsrK  
from_numpyr   r   numelr  r\  r]  longr   valuesr-  ra  argminr   r+  rZ  ro  emptyrT  r[  rS   r/  r   r^  )r    r!   r"   r   r   r   r   rb  rg  
cls_tensorrh  overlapweightsweighted_maskssmallest_idxs                  r#   r   zFormat.apply_instances  s>    jj--JJ{++	$$&Y$$$JJsAJJsAZZa   	4 T(,(=(=iaQR(S(S%y#(//"-ckk!nn==
{1~ OZ-=-=-?-? O %A,@!tBV W WII& O *58==??Q+> ?II "'AAAtTM)B!B G G J J QI#iiAi..2G{{}} O"')))"8"8).D$1G)G5<[[]]Q5Fuz2'5'<'<'<'C'C-7W8M-N	'*):$BAAADXZ[_c_nZnoo!KT_(<a4?>RSS	#F7O"+//"3"3F;13K(---R9K9KuAC]5+I,<===VXZ[U\I]I]x 	1%.%8%@Aq!!!eFVW`WjFkFk ; ~ 1{#F+++q0+++{#F+++q0+++? 	HKIL^H_H_xu/	0BCCDDDejepqwexex 8 > 	-8QQQAY'''1,'''8QQQAY'''1,'''> 	2"'+b//F;r%   r   rD  torch.Tensorc                8   t          |j                  dk     r|d         }|                    ddd          }t          j        t          j        dd          | j        k    r|j        d         dk    r|ddd         n|          }t          j	        |          }|S )a  Format an image for YOLO from a Numpy array to a PyTorch tensor.

        This function performs the following operations:
        1. Ensures the image has 3 dimensions (adds a channel dimension if needed).
        2. Transposes the image from HWC to CHW format.
        3. Optionally reverses the color channels (e.g., BGR to RGB) based on the bgr probability.
        4. Converts the image to a contiguous array.
        5. Converts the Numpy array to a PyTorch tensor.

        Args:
            img (np.ndarray): Input image as a Numpy array with shape (H, W, C) or (H, W).

        Returns:
            (torch.Tensor): Formatted image as a PyTorch tensor with shape (C, H, W).

        Examples:
            >>> import numpy as np
            >>> img = np.random.rand(100, 100, 3)
            >>> formatted_img = self._format_img(img)
            >>> print(formatted_img.shape)
            torch.Size([3, 100, 100])
        r   r`  r   r   rj   Nr   )
rS   r   	transposer   r  rl   rm   r_  rK  rj  )r    r   s     r#   rd  zFormat._format_img4	  s    . sy>>Ai.CmmAq!$$"q!0D0Dtx0O0OTWT]^_T`deTeTe3ttt99knoos##
r%   r   r   r   r   r   (tuple[np.ndarray, Instances, np.ndarray]c                    |j         }| j        r5t          ||f|| j                  \  }}|d         }||         }||         }nt	          ||f|d| j                  }|||fS )aM  Convert polygon segments to bitmap masks.

        Args:
            instances (Instances): Object containing segment information.
            cls (np.ndarray): Class labels for each instance.
            w (int): Width of the image.
            h (int): Height of the image.

        Returns:
            masks (np.ndarray): Bitmap masks with shape (N, H, W) or (1, H, W) if mask_overlap is True.
            instances (Instances): Updated instances object with sorted segments if mask_overlap is True.
            cls (np.ndarray): Updated class labels, sorted if mask_overlap is True.

        Notes:
            - If self.mask_overlap is True, masks are overlapped and sorted by area.
            - If self.mask_overlap is False, each mask is represented separately.
            - Masks are downsampled according to self.mask_ratio.
        )downsample_ratioNrj   )colorrz  )r/  r]  r	   r\  r   )r    r   r   r   r   r/  rg  r  s           r#   ri  zFormat._format_segmentsR	  s    * % 	` 61vxZ^Zi j j jE:$KE!*-Ij/CC"Aq681t___Ei$$r%   )	r  TFFFr   TTr   )rf  r  rT  r  rY  r  rZ  r  r[  r  r\  rK   r]  r  r^  r  r_  r   r   r,   r  )r   rD  rC   ru  )
r   r   r   rD  r   rK   r   rK   rC   rx  )
r-   r.   r/   r0   r7   r   r   r   rd  ri  r'   r%   r#   rX  rX    s         < "! % !$ $ $ $ $Ln n n n*    @ @ @ @ @D   <% % % % % %r%   rX  c                  &    e Zd ZdZd
ddZd
dd	ZdS )SemanticFormatzFormat transform for semantic segmentation that converts images and masks to tensors.

    This transform handles the letterboxed semantic mask by resizing it to match the image dimensions and converts both
    to the appropriate tensor formats.
    Nr!   rh   r"   r   rC   c                    |                     dd          }||                     |          |d<   |                    d          }|Ft          j        |                                                              t          j                  |d<   |S )af  Format image and semantic mask for semantic segmentation.

        Args:
            labels (dict[str, Any]): Dictionary containing 'img' and 'semantic_mask'.
            params (dict[str, Any] | None): Unused parameters for API compatibility.

        Returns:
            (dict[str, Any]): Updated labels with 'img' and 'semantic_mask' as tensors.
        r   Nr   )rn   rd  r   rK  rj  r  tor5  )r    r!   r"   r   r   s        r#   r   zSemanticFormat.apply_imagez	  s|     jj%%? ,,S11F5Mzz/**&+&6tyy{{&C&C&F&Fu{&S&SF?#r%   c                <    dD ]}|                     |d           |S )aC  Remove instance-level keys not needed for semantic segmentation.

        Args:
            labels (dict[str, Any]): Dictionary to clean up.
            params (dict[str, Any] | None): Unused parameters for API compatibility.

        Returns:
            (dict[str, Any]): Updated labels with unused keys removed.
        )r   r   r   r   r  N)rn   )r    r!   r"   r   s       r#   r   zSemanticFormat.apply_instances	  s0     Q 	  	 AJJq$r%   r,   r  )r-   r.   r/   r0   r   r   r'   r%   r#   r}  r}  s	  sP             $      r%   r}  c                  R    e Zd ZdZdddZedd            ZddZd dZ	 	 d!d"dZ	dS )#LoadVisualPromptzCCreate visual prompts from bounding boxes or masks for model input.      ?scale_factorr   rC   rO   c                    || _         dS )zInitialize the LoadVisualPrompt with a scale factor.

        Args:
            scale_factor (float): Factor to scale the input image dimensions.
        N)r  )r    r  s     r#   r7   zLoadVisualPrompt.__init__	  s     )r%   boxesru  r   rK   r   c                   t          j        | dddddf         dd          \  }}}}t          j        |          ddddf         }t          j        |          ddddf         }||k    ||k     z  ||k    z  ||k     z  S )a2  Create binary masks from bounding boxes.

        Args:
            boxes (torch.Tensor): Bounding boxes in xyxy format, shape: (N, 4).
            h (int): Height of the mask.
            w (int): Width of the mask.

        Returns:
            (torch.Tensor): Binary masks with shape (N, h, w).
        Nr   rj   )rK  chunkr  )	r  r   r   r   r   r   r   r  r   s	            r#   	make_maskzLoadVisualPrompt.make_mask	  s     U111aaa:%61==BBLOOD$M*LOOD!!!TM*RAF#qBw/1r6::r%   r!   rh   c                >   |d         j         dd         }d\  }}d|v r5|d         }t          |          t          j        |          g d         z  }nd|v r|d         }|d                             d	                              t          j                  }||||d
S )zCompute visual prompt parameters.

        Args:
            labels (dict[str, Any]): Input labels dictionary.

        Returns:
            (dict): Parameters including 'imgsz', 'bboxes', 'masks', and 'cls'.
        r   rj   Nr   r+  )rj   r   rj   r   rg  r   r   )r   r+  rg  r   )r   r   rK  tensorr   r  rK   )r    r!   r   r+  rg  r   s         r#   r   zLoadVisualPrompt.get_params	  s     u#ABB'"vH%Fv&&e)<)<\\\)JJFF7OEUm##B''**5955&5MMMr%   r"   c                r    |                      |d         |d         |d         |d                   }||d<   |S )a#  Create visual prompts and add them to labels.

        Args:
            labels (dict[str, Any]): Dictionary containing image data and annotations.
            params (dict): Parameters from get_params.

        Returns:
            (dict): Updated labels with visual prompts added.
        r   r   r+  rg  )r+  rg  visuals)get_visuals)r    r!   r"   r  s       r#   r   zLoadVisualPrompt.apply_image	  sD     ""6%=&/&QYJZbhipbq"rr#yr%   Ncategoryint | np.ndarray | torch.Tensorr   rE  r+  np.ndarray | torch.Tensorrg  c                   t          |d         | j        z            t          |d         | j        z            f}|Yt          |t          j                  rt          j        |          }|| j        z  } | j        |g|R                                  }n|~t          |t          j                  rt          j        |          }t          j
        |                    d          |d                              d                                          }nt          d          t          |t
          j                  s t          j        |t
          j                   }t          j        |dd	          \  }}t          j        |j        d         g|R  }t'          ||          D ]#\  }	}
t          j        ||	         |
          ||	<   $|S )
ai  Generate visual masks based on bounding boxes or masks.

        Args:
            category (int | np.ndarray | torch.Tensor): The category labels for the objects.
            shape (tuple[int, int]): The shape of the image (height, width).
            bboxes (np.ndarray | torch.Tensor, optional): Bounding boxes for the objects, xyxy format.
            masks (np.ndarray | torch.Tensor, optional): Masks for the objects.

        Returns:
            (torch.Tensor): A tensor containing the visual masks for each category.

        Raises:
            ValueError: If neither bboxes nor masks are provided.
        r   rj   Nnearest)r  z7LoadVisualPrompt must have bboxes or masks in the labelr   T)sortedreturn_inverse)rK   r  r4   r   ndarrayrK  rj  r  r   Finterpolate	unsqueezer   
ValueErrorTensorr  uniquer  r   rR   
logical_or)r    r  r   r+  rg  masksz
cls_uniqueinverse_indicesr  r2  r   s              r#   r  zLoadVisualPrompt.get_visuals	  s   * eAh!2233SqDDU9U5V5VW&"*-- 2)&11d''F"DN63F33399;;EE%,, 0(//M%//!"4"4f9MMMUUVWXX^^``EEVWWW(EL11 	?|HEI>>>H&+l8DY]&^&^&^#
O +j.q1;F;;;_e44 	@ 	@IC +GCL$??GCLLr%   )r  )r  r   rC   rO   )r  ru  r   rK   r   rK   rC   ru  r   r  r   )
r  r  r   rE  r+  r  rg  r  rC   ru  )
r-   r.   r/   r0   r7   r   r  r   r   r  r'   r%   r#   r  r  	  s        MM) ) ) ) ) ; ; ; \;"N N N N(   $ -1+/, , , , , , ,r%   r  c                  8    e Zd ZdZdddddgfddZddZddZdS )RandomLoadTexta  Randomly sample positive and negative texts and update class indices accordingly.

    This class is responsible for sampling texts from a given set of class texts, including both positive (present in
    the image) and negative (not present in the image) samples. It updates the class indices to reflect the sampled
    texts and can optionally pad the text list to a fixed length.

    Attributes:
        prompt_format (str): Format string for text prompts.
        neg_samples (tuple[int, int]): Range for randomly sampling negative texts.
        max_samples (int): Maximum number of different text samples in one image.
        padding (bool): Whether to pad texts to max_samples.
        padding_value (list[str]): The text used for padding when padding is True.

    Methods:
        __call__: Process the input labels and return updated classes and texts.

    Examples:
        >>> loader = RandomLoadText(prompt_format="Object: {}", neg_samples=(5, 10), max_samples=20)
        >>> labels = {"cls": [0, 1, 2], "texts": [["cat"], ["dog"], ["bird"]], "instances": [...]}
        >>> updated_labels = loader(labels)
        >>> print(updated_labels["texts"])
        ['Object: cat', 'Object: dog', 'Object: bird', 'Object: elephant', 'Object: car']
    z{})P   r  r  Fr;  prompt_formatr  neg_samplesrE  max_samplesrK   paddingr  r  	list[str]rC   rO   c                L    || _         || _        || _        || _        || _        dS )a  Initialize the RandomLoadText class for randomly sampling positive and negative texts.

        This class is designed to randomly sample positive texts and negative texts, and update the class indices
        accordingly to the number of samples. It can be used for text-based object detection tasks.

        Args:
            prompt_format (str): Format string for the prompt. The format string should contain a single pair of curly
                braces {} where the text will be inserted.
            neg_samples (tuple[int, int]): A range to randomly sample negative texts. The first integer specifies the
                minimum number of negative samples, and the second integer specifies the maximum.
            max_samples (int): The maximum number of different text samples in one image.
            padding (bool): Whether to pad texts to max_samples. If True, the number of texts will always be equal to
                max_samples.
            padding_value (list[str]): The padding text to use when padding is True.
        N)r  r  r  r  r  )r    r  r  r  r  r  s         r#   r7   zRandomLoadText.__init__"
  s1    . +&&*r%   r!   rh   c           	        d|v s
J d            |d         }t          |          }t          j        |                    d          t                    }t          j        |                                          t                    | j        k    rt          j	        | j                  t          t          || j                  t                    z
  t          j        | j                   }fdt          |          D             }t          j	        ||          }|z   }d t          |          D             }t          j        t          |d                   t                     }	g }
t          |                    d	                                                    D ]+\  }}||vr
d
|	|<   |
                    ||         g           ,g }|D ]s}||         }t          |          dk    sJ | j                            |t          j        t          |                                       }|                    |           t| j        rMt                    t          |          z   }| j        |z
  }|dk    r|t          j        | j        |          z  }t          |          | j        k    sJ |	t          j        |
          |dS )a  Compute text sampling parameters.

        Args:
            labels (dict[str, Any]): Input labels dictionary containing 'texts', 'cls', and 'instances'.

        Returns:
            (dict): Parameters including 'valid_idx', 'new_cls', and 'texts'.
        rz   zNo texts found in labels.r   r   r   c                    g | ]}|v|	S r'   r'   )rH   rI   
pos_labelss     r#   rJ   z-RandomLoadText.get_params.<locals>.<listcomp>R
  s#    KKKAq
7J7Ja7J7J7Jr%   c                    i | ]\  }}||	S r'   r'   )rH   rI   r   s      r#   r   z-RandomLoadText.get_params.<locals>.<dictcomp>Y
  s    HHH(!UUAHHHr%   r   r   Tr   )	valid_idxnew_clsrz   )rS   r   r)  rn   rK   r  rX   r  rl   sampler   rx   r  r   rs   r  r  r   r=   r  r   	randranger  r   r  rU  )r    r!   class_textsnum_classesr   r  
neg_labelssampled_labels	label2idsr  r  rI   r   rz   promptspromptvalid_labelsnum_paddingr  s                     @r#   r   zRandomLoadText.get_params?
  s    &   "=   Wo+&&jE**#666Ys^^**,,
z??T---zT5EFFFJ#k4+;<<s:NPVP^`d`pPqrrKKKK{!3!3KKK
]:===
#j0 IHi.G.GHHH	HS!455TBBB	!#++b//"8"8":":;; 	/ 	/HAuI%%IaLNNIe,-.... # 	! 	!E!%(Gw<<!####'..wv7GG7U7U/VWWFLL    < 	Kz??S__<L*\9KQ(:kJJJJ5zzT-----&28G3D3DuUUUr%   r"   c                `    |d         |d                  |d<   |d         |d<   |d         |d<   |S )aJ  Filter instances and update class labels based on sampled texts.

        Args:
            labels (dict[str, Any]): Dictionary containing 'instances' and 'cls'.
            params (dict): Parameters from get_params.

        Returns:
            (dict): Updated labels with filtered instances and new class/text entries.
        r   r  r  r   rz   r'   r   s      r#   r   zRandomLoadText.apply_instancest
  s=     %[1&2EF{y)u /wr%   N)r  r  r  rE  r  rK   r  r  r  r  rC   rO   r   r  )r-   r.   r/   r0   r7   r   r   r'   r%   r#   r  r  	
  sw         4 "'/$&4+ + + + +:3V 3V 3V 3Vj     r%   r  Fr   rK   hypr   stretchr  c                   t          | ||j                  }t          |j        |j        |j        |j        |j        |s||fnd          }t          ||g          }|j	        dk    r1|
                    dt          | |j        |j	                             nT|                    t          | t          t          | ||j                  |g          |j        |j	                             | j                            dg           }t!          | d	d
          r| j                            dd          }t#          |          dk    r9|j        dk    s|j        dk    r#dx|_        |_        t)          j        d           n6|r4t#          |          |d         k    rt-          d| d|d                    t          |t/          | ||j                  t3          | ||j                  t7          dt!          |dd                    t9          |j        |j        |j                  tA          d|j        |          tA          d|j        |          g          S )a  Apply a series of image transformations for training.

    This function creates a composition of image augmentation techniques to prepare images for YOLO training. It
    includes operations such as mosaic, copy-paste, random perspective, mixup, and various color adjustments.

    Args:
        dataset (Dataset): The dataset object containing image data and annotations.
        imgsz (int): The target image size for resizing.
        hyp (IterableSimpleNamespace): A namespace of hyperparameters controlling various aspects of the
            transformations.
        stretch (bool): If True, applies stretching to the image. If False, uses LetterBox resizing.

    Returns:
        (Compose): A composition of image transformations to be applied to the dataset.

    Examples:
        >>> from ultralytics.data.dataset import YOLODataset
        >>> from ultralytics.utils import IterableSimpleNamespace
        >>> dataset = YOLODataset(img_path="path/to/images", imgsz=640)
        >>> hyp = IterableSimpleNamespace(mosaic=1.0, copy_paste=0.5, degrees=10.0, translate=0.2, scale=0.9)
        >>> transforms = v8_transforms(dataset, imgsz=640, hyp=hyp)
        >>> augmented_data = transforms(dataset[0])

        >>> # With custom albumentations
        >>> import albumentations as A
        >>> augmentations = [A.Blur(p=0.01), A.CLAHE(p=0.01)]
        >>> hyp.augmentations = augmentations
        >>> transforms = v8_transforms(dataset, imgsz=640, hyp=hyp)
    )r   rg   NrC  r  rj   )rg   r  )rf   rg   r  r  use_keypointsF	kpt_shaper   r   zXNo 'flip_idx' array defined in data.yaml, disabling 'fliplr' and 'flipud' augmentations.zdata.yaml flip_idx=z& length must be equal to kpt_shape[0]=)rf   rg   r   augmentations)rg   r6   r  r  )r  rg   r  r  )!r   mosaicr:  r;  r<  r=  r?  r@  r2   copy_paste_moder@   r  
copy_paster=   r:   r   getattrrS   r  r  r
   warningr  r  r  r  cutmixr  r  hsv_hhsv_shsv_vr  )	re   r   r  r  r  affinerf   r  r  s	            r#   v8_transformsr  
  sq   < G5CJ777F-iiO#*4eU^^  F VV,--M
f$$Q	'S^#J] ^ ^ ^____%vgUcj'Q'Q'QSY&Z[[.(	  	
 	
 	
 |
B//Hw// sL$$[$77	x==A3:#3#3szC7G7G&))CJNuvvvv 	s3x==IaL88q8qqclmncoqqrrr'#)DDD7-3:FFFSWS/4-P-PQQQCISYciHHHszHMMMhOOO	

 
 
r%      BILINEARrA  tuple[int, int] | intmeantuple[float, float, float]stdr  r  crop_fractionfloat | Nonec           	     D   ddl m} t          | t          t          f          rt          |           dk    r| n| | f}|rt          d          |d         |d         k    r2|                    |d         t          |j	        |                    g}n|                    |          g}||
                    |           |                                |                    t          j        |          t          j        |                    gz  }|                    |          S )a  Create a composition of image transforms for classification tasks.

    This function generates a sequence of torchvision transforms suitable for preprocessing images for classification
    models during evaluation or inference. The transforms include resizing, center cropping, conversion to tensor, and
    normalization.

    Args:
        size (tuple[int, int] | int): The target size for the transformed image. If an int, it defines the shortest
            edge. If a tuple, it defines (height, width).
        mean (tuple[float, float, float]): Mean values for each RGB channel used in normalization.
        std (tuple[float, float, float]): Standard deviation values for each RGB channel used in normalization.
        interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'.
        crop_fraction (float | None): Deprecated, will be removed in a future version.

    Returns:
        (torchvision.transforms.Compose): A composition of torchvision transforms.

    Examples:
        >>> transforms = classify_transforms(size=224)
        >>> img = Image.open("path/to/image.jpg")
        >>> transformed_img = transforms(img)
    r   Nr   z^'crop_fraction' arg of classify_transforms is deprecated, will be removed in a future version.rj   r  r  r  )torchvision.transformsr6   r4   r   r5   rS   DeprecationWarningr  r  InterpolationModer  ToTensor	NormalizerK  r  r2   )rA  r  r  r  r  rX  
scale_sizetfls           r#   classify_transformsr  
  s   : '&&&&&#D5$-88]SYY!^^RVX\Q]J 
 l
 
 	

 !}
1%%xx
1WQ=PR_5`5`xaab xx
##$ALL

akku|D?Q?QW\WcdgWhWhk.i.ijjC99S>>r%   r  r   gQ?g?r=  tuple[float, float] | Noner  hflipr   vflipauto_augment
str | Noner  r  r  force_color_jittererasingc                x   ddl m} t          | t                    st	          d|  d          t          |pd          }t          |pd          }t          |j        |          }|                    | |||          g}|dk    r)|	                    |
                    |	                     |dk    r)|	                    |                    |	                     g }d
}|r)t          |t                    sJ dt          |                       | }|dk    rFt          r*|	                    |                    |                     nt!          j        d           n|dk    rFt$          r*|	                    |                    |                     ntt!          j        d           n_|dk    rFt(          r*|	                    |                    |                     n(t!          j        d           nt-          d| d          |s,|	                    |                    |
|
|	|                     |                                |                    t5          j        |          t5          j        |                    |                    |d          g}|                    ||z   |z             S )a  Create a composition of image augmentation transforms for classification tasks.

    This function generates a set of image transformations suitable for training classification models. It includes
    options for resizing, flipping, color jittering, auto augmentation, and random erasing.

    Args:
        size (int): Target size for the image after transformations.
        mean (tuple[float, float, float]): Mean values for each RGB channel used in normalization.
        std (tuple[float, float, float]): Standard deviation values for each RGB channel used in normalization.
        scale (tuple[float, float] | None): Range of the proportion of the original image area to crop.
        ratio (tuple[float, float] | None): Range of aspect ratio for the cropped area.
        hflip (float): Probability of horizontal flip.
        vflip (float): Probability of vertical flip.
        auto_augment (str | None): Auto augmentation policy. Can be 'randaugment', 'augmix', 'autoaugment' or None.
        hsv_h (float): Image HSV-Hue augmentation factor.
        hsv_s (float): Image HSV-Saturation augmentation factor.
        hsv_v (float): Image HSV-Value augmentation factor.
        force_color_jitter (bool): Whether to apply color jitter even if auto augment is enabled.
        erasing (float): Probability of random erasing.
        interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'.

    Returns:
        (torchvision.transforms.Compose): A composition of image augmentation transforms.

    Examples:
        >>> transforms = classify_augmentations(size=224, auto_augment="randaugment")
        >>> augmented_image = transforms(original_image)
    r   Nzclassify_augmentations() size z# must be integer, not (list, tuple))g{Gz?r   )g      ?gUUUUUU?)r=  r  r  r   r0  Fz1Provided argument should be string, but got type randaugmentr  zH"auto_augment=randaugment" requires torchvision >= 0.11.0. Disabling it.augmixzC"auto_augment=augmix" requires torchvision >= 0.13.0. Disabling it.autoaugmentzH"auto_augment=autoaugment" requires torchvision >= 0.10.0. Disabling it.zInvalid auto_augment policy: zA. Should be one of "randaugment", "augmix", "autoaugment" or None)
brightnesscontrast
saturationr  r  T)rg   inplace)r  r6   r4   rK   	TypeErrorr   r  r  r+  r=   RandomHorizontalFlipRandomVerticalFlipr  rL   r   RandAugmentr
   r  r   AugMixr   AutoAugmentr  ColorJitterr  r  rK  r  RandomErasingr2   )rA  r  r  r=  r  r  r  r  r  r  r  r  r  r  rX  primary_tflsecondary_tfldisable_color_jitter	final_tfls                      r#   classify_augmentationsr    s   Z '&&&&&dC   dbbbbccc%&;''E%1122EA/??M&&t5Ub&ccdKs{{111E1::;;;s{{1//%/88999M  ,,,vv.vbfgsbtbt.v.vvv, $65=(( k$$Q]]]%O%OPPPPijjjjX%% f$$QXXMX%J%JKKKKdeeee]** k$$Q]]]%O%OPPPPijjjj 3 3 3 3  
   kQ]]eeX]ch]iijjj 	


	d++c1B1BCC	'400I 99[=09<===r%   c                  .     e Zd ZdZdd fdZddZ xZS )ClassifyLetterBoxaw  A class for resizing and padding images for classification tasks.

    This class is designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]). It
    resizes and pads images to a specified size while maintaining the original aspect ratio.

    Attributes:
        h (int): Target height of the image.
        w (int): Target width of the image.
        auto (bool): If True, automatically calculates the short side using stride.
        stride (int): The stride value, used when 'auto' is True.

    Methods:
        __call__: Apply the letterbox transformation to an input image.

    Examples:
        >>> transform = ClassifyLetterBox(size=(640, 640), auto=False, stride=32)
        >>> img = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
        >>> result = transform(img)
        >>> print(result.shape)
        (640, 640, 3)
    r  Fr  rA  int | tuple[int, int]r  r  r  rK   c                    t                                                       t          |t                    r||fn|\  | _        | _        || _        || _        dS )a  Initialize the ClassifyLetterBox object for image preprocessing.

        This class is designed to be part of a transformation pipeline for image classification tasks. It resizes and
        pads images to a specified size while maintaining the original aspect ratio.

        Args:
            size (int | tuple[int, int]): Target size for the letterboxed image. If an int, a square image of (size,
                size) is created. If a tuple, it should be (height, width).
            auto (bool): If True, automatically calculates the short side based on stride.
            stride (int): The stride value, used when 'auto' is True.
        N)r   r7   r4   rK   r   r   r  r  )r    rA  r  r  r^   s       r#   r7   zClassifyLetterBox.__init__  sQ     	)3D#)>)>H$D	r%   r  rD  rC   c                    |j         dd         \  }}t           j        |z   j        |z            }t	          ||z            t	          ||z            }} j        r fd||fD             n j         j        f\  }}t	          ||z
  dz  dz
            t	          ||z
  dz  dz
            }
}	t          j        ||dfd|j                  }t          j
        |||ft          j                  ||	|	|z   |
|
|z   f<   |S )	a'  Resize and pad an image using the letterbox method.

        This method resizes the input image to fit within the specified dimensions while maintaining its aspect ratio,
        then pads the resized image to match the target size.

        Args:
            im (np.ndarray): Input image as a numpy array with shape (H, W, C).

        Returns:
            (np.ndarray): Resized and padded image as a numpy array with shape (hs, ws, 3), where hs and ws are the
                target height and width respectively.

        Examples:
            >>> letterbox = ClassifyLetterBox(size=(640, 640))
            >>> image = np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8)
            >>> resized_image = letterbox(image)
            >>> print(resized_image.shape)
            (640, 640, 3)
        Nr   c              3  `   K   | ](}t          j        |j        z            j        z  V  )d S r,   )rP  ceilr  )rH   r|   r    s     r#   r~   z-ClassifyLetterBox.__call__.<locals>.<genexpr>  s:      KKq$)AO,,t{:KKKKKKr%   r&  r   r   r   r  )r   r   r   r   r  r  r   r   r   rN  r  r  )r    r  imhimwr  r   r   hswsr  r  im_outs   `           r#   r$   zClassifyLetterBox.__call__  s   ( 8BQB<Sdfsl++S1W~~uS1W~~1 PTynKKKKQFKKKK_c_egkgm^nB26Q,,--ub1f\C5G/H/HT "b!c:::14BAVYVf1g1g1gsS1W}dTAXo-.r%   )r  Fr  )rA  r  r  r  r  rK   )r  rD  rC   rD  r-   r.   r/   r0   r7   r$   r  r  s   @r#   r  r  h  s`         ,      "       r%   r  c                  .     e Zd ZdZdd fdZdd
Z xZS )r  a  Apply center cropping to images for classification tasks.

    This class performs center cropping on input images, resizing them to a specified size while maintaining the aspect
    ratio. It is designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]).

    Attributes:
        h (int): Target height of the cropped image.
        w (int): Target width of the cropped image.

    Methods:
        __call__: Apply the center crop transformation to an input image.

    Examples:
        >>> transform = CenterCrop(640)
        >>> image = np.random.randint(0, 255, (1080, 1920, 3), dtype=np.uint8)
        >>> cropped_image = transform(image)
        >>> print(cropped_image.shape)
        (640, 640, 3)
    r  rA  r  c                    t                                                       t          |t                    r||fn|\  | _        | _        dS )a  Initialize the CenterCrop object for image preprocessing.

        This class is designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]).
        It performs a center crop on input images to a specified size.

        Args:
            size (int | tuple[int, int]): The desired output size of the crop. If size is an int, a square crop (size,
                size) is made. If size is a sequence like (h, w), it is used as the output size.
        N)r   r7   r4   rK   r   r   )r    rA  r^   s     r#   r7   zCenterCrop.__init__  sC     	)3D#)>)>H$Dr%   r  Image.Image | np.ndarrayrC   rD  c                @   t          |t          j                  rt          j        |          }|j        dd         \  }}t          ||          }||z
  dz  ||z
  dz  }}t          j        ||||z   |||z   f         | j        | j	        ft          j
                  S )a  Apply center cropping to an input image.

        This method crops the largest centered square from the image and resizes it to the specified dimensions.

        Args:
            im (np.ndarray | PIL.Image.Image): The input image as a numpy array of shape (H, W, C) or a PIL Image
                object.

        Returns:
            (np.ndarray): The center-cropped and resized image as a numpy array of shape (self.h, self.w, C).

        Examples:
            >>> transform = CenterCrop(size=224)
            >>> image = np.random.randint(0, 255, (640, 480, 3), dtype=np.uint8)
            >>> cropped_image = transform(image)
            >>> assert cropped_image.shape == (224, 224, 3)
        Nr   r  )r4   r   r   r)  r   r   rN  r  r   r   r  )r    r  r  r  r   r  r  s          r#   r$   zCenterCrop.__call__  s    $ b%+&& 	 BB8BQB<SSMM1WNS1WNTz"S37]D4!8O;<tvtv>N^a^noooor%   )r  )rA  r  )r  r
  rC   rD  r  r  s   @r#   r  r    so         (I I I I I I Ip p p p p p p pr%   r  c                  .     e Zd ZdZdd fdZdd
Z xZS )r  a*  Convert an image from a numpy array to a PyTorch tensor.

    This class is designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]).

    Attributes:
        half (bool): If True, converts the image to half precision (float16).

    Methods:
        __call__: Apply the tensor conversion to an input image.

    Examples:
        >>> transform = ToTensor(half=True)
        >>> img = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
        >>> tensor_img = transform(img)
        >>> print(tensor_img.shape, tensor_img.dtype)
        torch.Size([3, 640, 640]) torch.float16

    Notes:
        The input image is expected to be in BGR format with shape (H, W, C).
        The output tensor will be in BGR format with shape (C, H, W), normalized to [0, 1].
    Fhalfr  c                V    t                                                       || _        dS )a  Initialize the ToTensor object for converting images to PyTorch tensors.

        This class is designed to be used as part of a transformation pipeline for image preprocessing in the
        Ultralytics YOLO framework. It converts numpy arrays or PIL Images to PyTorch tensors, with an option for
        half-precision (float16) conversion.

        Args:
            half (bool): If True, converts the tensor to half precision (float16).
        N)r   r7   r  )r    r  r^   s     r#   r7   zToTensor.__init__  s&     				r%   r  rD  rC   ru  c                    t          j        |                    d                    }t          j        |          }| j        r|                                n|                                }|dz  }|S )a_  Transform an image from a numpy array to a PyTorch tensor.

        This method converts the input image from a numpy array to a PyTorch tensor, applying optional half-precision
        conversion and normalization. The image is transposed from HWC to CHW format.

        Args:
            im (np.ndarray): Input image as a numpy array with shape (H, W, C) in BGR order.

        Returns:
            (torch.Tensor): The transformed image as a PyTorch tensor in float32 or float16, normalized to [0, 1] with
                shape (C, H, W) in BGR order.

        Examples:
            >>> transform = ToTensor(half=True)
            >>> img = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
            >>> tensor_img = transform(img)
            >>> print(tensor_img.shape, tensor_img.dtype)
            torch.Size([3, 640, 640]) torch.float16
        )r   r   rj   g     o@)r   r  rw  rK  rj  r  r   )r    r  s     r#   r$   zToTensor.__call__  s^    ( !",,y"9"9::b!!)3RWWYYY
e	r%   F)r  r  )r  rD  rC   ru  r  r  s   @r#   r  r    s`         ,             r%   r  r  )r   rK   r  r   r  r  )
rA  r  r  r  r  r  r  r  r  r  )rA  rK   r  r  r  r  r=  r  r  r  r  r   r  r   r  r  r  r   r  r   r  r   r  r  r  r   r  r  )>
__future__r   rP  rl   r  r   typingr   rN  numpyr   rK  PILr   torch.nnr   r  ultralytics.data.utilsr   r	   ultralytics.utilsr
   r   r   ultralytics.utils.checksr   ultralytics.utils.instancer   ultralytics.utils.metricsr   ultralytics.utils.opsr   r   r   ultralytics.utils.torch_utilsr   r   r   DEFAULT_MEANDEFAULT_STDr   r2   rb   r   r  r  r:  r  r  r  r  r  rX  r}  r  r  r  r  r  r  r  r  r'   r%   r#   <module>r     s   # " " " " "               



            $ $ $ $ $ $ I I I I I I I I G G G G G G G G G G 2 2 2 2 2 2 0 0 0 0 0 0 . . . . . . H H H H H H H H H H ^ ^ ^ ^ ^ ^ ^ ^ ^ ^O O O O O O O Od[\ [\ [\ [\ [\ [\ [\ [\|W W W W W} W W WtQ Q Q Q Q Q Q Qh
b b b b b b b bJj j j j j j j jZif if if if if if if ifXJ J J J J J J JZz z z z z z z zzx x x x x x x xvX X X X X  X X Xvp p p p p] p p pfe% e% e% e% e%] e% e% e%P% % % % %V % % %Pk k k k k} k k k\x x x x x] x x xvG G G G GX #&'3&1#"&. . . . .f '3&1(,(,#$#c> c> c> c> c>NG G G G G G G GV9p 9p 9p 9p 9p 9p 9p 9pz< < < < < < < < < <r%   