a
    yfn                    @   s  d dl Z d dlZd dlmZ d dlmZmZ d dlZd dlZ	d dl
Z
d dlmZ d dlmZmZ d dl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 d dlmZmZmZ dZ dZ!dZ"G dd dZ#G dd dZ$G dd dZ%G dd de%Z&G dd de%Z'G dd dZ(G dd dZ)G dd dZ*G dd  d Z+G d!d" d"e%Z,G d#d$ d$Z-G d%d& d&Z.G d'd( d(Z/d=d*d+Z0d,e e!d-e"fe1d.d/d0Z2d,e e!ddd1d2dd3d4d4d)d2d-fd5d6Z3G d7d8 d8Z4G d9d: d:Z5G d;d< d<Z6dS )>    N)deepcopy)TupleUnion)Image)polygons2maskspolygons2masks_overlap)LOGGERcolorstr)check_version)	Instances)bbox_ioa)segment2boxxyxyxyxy2xywhr)TORCHVISION_0_10TORCHVISION_0_11TORCHVISION_0_13)        r   r   )      ?r   r   r   c                   @   s>   e Zd ZdZddddZdd Zdd	 Zd
d Zdd ZdS )BaseTransforma  
    Base class for image transformations in the Ultralytics library.

    This class serves as a foundation for implementing various image processing operations, designed to be
    compatible with both classification and semantic segmentation tasks.

    Methods:
        apply_image: Applies image transformations to labels.
        apply_instances: Applies transformations to object instances in labels.
        apply_semantic: Applies semantic segmentation to an image.
        __call__: Applies all label transformations to an image, instances, and semantic masks.

    Examples:
        >>> transform = BaseTransform()
        >>> labels = {"image": np.array(...), "instances": [...], "semantic": np.array(...)}
        >>> transformed_labels = transform(labels)
    Nreturnc                 C   s   dS )aO  
        Initializes the BaseTransform object.

        This constructor sets up the base transformation object, which can be extended for specific image
        processing tasks. It is designed to be compatible with both classification and semantic segmentation.

        Examples:
            >>> transform = BaseTransform()
        N selfr   r   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/data/augment.py__init__-   s    
zBaseTransform.__init__c                 C   s   dS )a  
        Applies image transformations to labels.

        This method is intended to be overridden by subclasses to implement specific image transformation
        logic. In its base form, it returns the input labels unchanged.

        Args:
            labels (Any): The input labels to be transformed. The exact type and structure of labels may
                vary depending on the specific implementation.

        Returns:
            (Any): The transformed labels. In the base implementation, this is identical to the input.

        Examples:
            >>> transform = BaseTransform()
            >>> original_labels = [1, 2, 3]
            >>> transformed_labels = transform.apply_image(original_labels)
            >>> print(transformed_labels)
            [1, 2, 3]
        Nr   r   labelsr   r   r   apply_image9   s    zBaseTransform.apply_imagec                 C   s   dS )a  
        Applies transformations to object instances in labels.

        This method is responsible for applying various transformations to object instances within the given
        labels. It is designed to be overridden by subclasses to implement specific instance transformation
        logic.

        Args:
            labels (Dict): A dictionary containing label information, including object instances.

        Returns:
            (Dict): The modified labels dictionary with transformed object instances.

        Examples:
            >>> transform = BaseTransform()
            >>> labels = {"instances": Instances(xyxy=torch.rand(5, 4), cls=torch.randint(0, 80, (5,)))}
            >>> transformed_labels = transform.apply_instances(labels)
        Nr   r   r   r   r   apply_instancesP   s    zBaseTransform.apply_instancesc                 C   s   dS )a  
        Applies semantic segmentation transformations to an image.

        This method is intended to be overridden by subclasses to implement specific semantic segmentation
        transformations. In its base form, it does not perform any operations.

        Args:
            labels (Any): The input labels or semantic segmentation mask to be transformed.

        Returns:
            (Any): The transformed semantic segmentation mask or labels.

        Examples:
            >>> transform = BaseTransform()
            >>> semantic_mask = np.zeros((100, 100), dtype=np.uint8)
            >>> transformed_mask = transform.apply_semantic(semantic_mask)
        Nr   r   r   r   r   apply_semantice   s    zBaseTransform.apply_semanticc                 C   s"   |  | | | | | dS )a`  
        Applies all label transformations to an image, instances, and semantic masks.

        This method orchestrates the application of various transformations defined in the BaseTransform class
        to the input labels. It sequentially calls the apply_image and apply_instances methods to process the
        image and object instances, respectively.

        Args:
            labels (Dict): A dictionary containing image data and annotations. Expected keys include 'img' for
                the image data, and 'instances' for object instances.

        Returns:
            (Dict): The input labels dictionary with transformed image and instances.

        Examples:
            >>> transform = BaseTransform()
            >>> labels = {"img": np.random.rand(640, 640, 3), "instances": []}
            >>> transformed_labels = transform(labels)
        N)r   r   r    r   r   r   r   __call__y   s    

zBaseTransform.__call__)	__name__
__module____qualname____doc__r   r   r   r    r!   r   r   r   r   r      s   r   c                   @   sz   e Zd ZdZdd Zdd Zdd Zdd	 Zee	e
f d d
ddZee	e
f ee	e
f ddddZdd Zd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__: Applies a series of transformations to input data.
        append: Appends a new transform to the existing list of transforms.
        insert: Inserts a new transform at a specified index in the list of transforms.
        __getitem__: Retrieves a specific transform or a set of transforms using indexing.
        __setitem__: Sets a specific transform or a set of transforms using indexing.
        tolist: Converts 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                 C   s   t |tr|n|g| _dS )a  
        Initializes the Compose object with a list of transforms.

        Args:
            transforms (List[Callable]): A list of callable transform objects to be applied sequentially.

        Examples:
            >>> from ultralytics.data.augment import Compose, RandomHSV, RandomFlip
            >>> transforms = [RandomHSV(), RandomFlip()]
            >>> compose = Compose(transforms)
        N)
isinstancelist
transforms)r   r)   r   r   r   r      s    zCompose.__init__c                 C   s   | j D ]}||}q|S )a  
        Applies a series of transformations to input data. This method sequentially applies each transformation in the
        Compose object's list of 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)
        r)   )r   datatr   r   r   r!      s    

zCompose.__call__c                 C   s   | j | dS )a<  
        Appends 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)r)   append)r   	transformr   r   r   r-      s    zCompose.appendc                 C   s   | j || dS )a  
        Inserts 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)r)   insert)r   indexr.   r   r   r   r/      s    zCompose.insert)r0   r   c                    sJ   t |ttfs J dt| t |tr0|gn|}t fdd|D S )a  
        Retrieves 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): A new Compose object containing the selected transform(s).

        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 a Compose object with only RandomPerspective
            >>> multiple_transforms = compose[0:2]  # Returns a Compose object with RandomFlip and RandomPerspective
        6The indices should be either list or int type but got c                    s   g | ]} j | qS r   r*   .0ir   r   r   
<listcomp>       z'Compose.__getitem__.<locals>.<listcomp>)r'   intr(   typer&   )r   r0   r   r   r   __getitem__   s     zCompose.__getitem__N)r0   valuer   c                 C   s   t |ttfs J dt| t |trPt |tsPJ dt| dt| t |trh|g|g }}t||D ]<\}}|t| jk sJ d| dt| j d|| j|< qrdS )a  
        Sets 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:2] = [NewTransform1(), NewTransform2()]  # Replace first two transforms
        r1   z7The indices should be the same type as values, but got z and zlist index z out of range .N)r'   r7   r(   r8   ziplenr)   )r   r0   r:   r4   vr   r   r   __setitem__   s     

*zCompose.__setitem__c                 C   s   | j S )a  
        Converts 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
        r*   r   r   r   r   tolist  s    zCompose.tolistc                 C   s&   | j j dddd | jD  dS )a  
        Returns 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                 S   s   g | ]
}| qS r   r   )r3   r,   r   r   r   r5   ;  r6   z$Compose.__repr__.<locals>.<listcomp>))	__class__r"   joinr)   r   r   r   r   __repr__+  s    zCompose.__repr__)r"   r#   r$   r%   r   r!   r-   r/   r   r(   r7   r9   r?   r@   rF   r   r   r   r   r&      s   "r&   c                   @   s@   e Zd ZdZdddddZdd Zd	d
 Zdd Zdd ZdS )BaseMixTransforma6  
    Base class for mix transformations like 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__: Applies the mix transformation to the input labels.
        _mix_transform: Abstract method to be implemented by subclasses for specific mix operations.
        get_indexes: Abstract method to get indexes of images to be mixed.
        _update_label_text: Updates label text for mixed images.

    Examples:
        >>> class CustomMixTransform(BaseMixTransform):
        ...     def _mix_transform(self, labels):
        ...         # Implement custom mix logic 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   r   c                 C   s   || _ || _|| _dS )a  
        Initializes the BaseMixTransform object for mix transformations like 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].

        Examples:
            >>> dataset = YOLODataset("path/to/data")
            >>> pre_transform = Compose([RandomFlip(), RandomPerspective()])
            >>> mix_transform = BaseMixTransform(dataset, pre_transform, p=0.5)
        Ndatasetpre_transformpr   rI   rJ   rK   r   r   r   r   ]  s    zBaseMixTransform.__init__c                    s   t dd jkr|S   }t|tr.|g} fdd|D } jdurjt|D ]\}} |||< qR||d<  |} 	|}|
dd |S )a  
        Applies pre-processing transforms and 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): A dictionary containing label data for an image.

        Returns:
            (Dict): 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      c                    s   g | ]} j |qS r   rI   Zget_image_and_labelr2   r   r   r   r5     r6   z-BaseMixTransform.__call__.<locals>.<listcomp>N
mix_labels)randomuniformrK   get_indexesr'   r7   rJ   	enumerate_update_label_text_mix_transformpopr   r   indexesrO   r4   r+   r   r   r   r!   q  s    



zBaseMixTransform.__call__c                 C   s   t dS )aR  
        Applies MixUp or Mosaic augmentation to the label dictionary.

        This method should be implemented by subclasses to perform specific mix transformations like MixUp or
        Mosaic. It modifies the input label dictionary in-place with the augmented data.

        Args:
            labels (Dict): A dictionary containing image and label data. Expected to have a 'mix_labels' key
                with a list of additional image and label data for mixing.

        Returns:
            (Dict): The modified labels dictionary with augmented data after applying the mix transform.

        Examples:
            >>> transform = BaseMixTransform(dataset)
            >>> labels = {"image": img, "bboxes": boxes, "mix_labels": [{"image": img2, "bboxes": boxes2}]}
            >>> augmented_labels = transform._mix_transform(labels)
        NNotImplementedErrorr   r   r   r   rU     s    zBaseMixTransform._mix_transformc                 C   s   t dS )aM  
        Gets a list of shuffled indexes for mosaic augmentation.

        Returns:
            (List[int]): A list of shuffled indexes from the dataset.

        Examples:
            >>> transform = BaseMixTransform(dataset)
            >>> indexes = transform.get_indexes()
            >>> print(indexes)  # [3, 18, 7, 2]
        NrY   r   r   r   r   rR     s    zBaseMixTransform.get_indexesc                 C   s   d|vr|S t |d gdd |d D  g }tdd |D }dd t|D }|g|d  D ]P}t|d	 d
 D ],\}}|d t| }|t| |d	 |< qz||d< q`|S )a  
        Updates 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): A dictionary containing label information, including 'texts' and 'cls' fields,
                and optionally a 'mix_labels' field with additional label dictionaries.

        Returns:
            (Dict): 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 = self._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                 S   s   g | ]}|d  qS )r[   r   r3   xr   r   r   r5     r6   z7BaseMixTransform._update_label_text.<locals>.<listcomp>rO   c                 S   s   h | ]}t |qS r   )tupler\   r   r   r   	<setcomp>  r6   z6BaseMixTransform._update_label_text.<locals>.<setcomp>c                 S   s   i | ]\}}||qS r   r   )r3   r4   textr   r   r   
<dictcomp>  r6   z7BaseMixTransform._update_label_text.<locals>.<dictcomp>cls)sumr(   rS   squeezer@   r7   r^   )r   r   Z	mix_textsZtext2idlabelr4   rb   r`   r   r   r   rT     s    "
z#BaseMixTransform._update_label_text)Nr   )	r"   r#   r$   r%   r   r!   rU   rR   rT   r   r   r   r   rG   >  s   (rG   c                       s`   e Zd ZdZd 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d Z  ZS )Mosaica7  
    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 width and height.

    Methods:
        get_indexes: Returns a list of random indexes from the dataset.
        _mix_transform: Applies mixup transformation to the input image and labels.
        _mosaic3: Creates a 1x3 image mosaic.
        _mosaic4: Creates a 2x2 image mosaic.
        _mosaic9: Creates a 3x3 image mosaic.
        _update_labels: Updates labels with padding.
        _cat_labels: Concatenates 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      c                    sl   d|  krdks&n J d| d|dv s6J dt  j||d || _| d | d f| _|| _d	S )
a%  
        Initializes 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).

        Examples:
            >>> from ultralytics.data.augment import Mosaic
            >>> dataset = YourDataset(...)
            >>> mosaic_aug = Mosaic(dataset, imgsz=640, p=0.5, n=4)
        r   r   3The probability should be in range [0, 1], but got r;   >   	   ri   zgrid must be equal to 4 or 9.)rI   rK      N)superr   imgszbordern)r   rI   rn   rK   rp   rD   r   r   r     s    &zMosaic.__init__Tc                    s@   |r t jt jj jd dS  fddt jd D S dS )aT  
        Returns 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' parameter. It is used to choose images for creating mosaic augmentations.

        Args:
            buffer (bool): If True, selects images from the dataset buffer. If False, selects from the entire
                dataset.

        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
        rM   kc                    s"   g | ]}t d t jd qS r   rM   rP   randintr=   rI   )r3   _r   r   r   r5   7  r6   z&Mosaic.get_indexes.<locals>.<listcomp>N)rP   choicesr(   rI   bufferrp   range)r   ry   r   r   r   rR      s    zMosaic.get_indexesc                 C   sb   | dddu sJ dt| dg s0J d| jdkrD| |S | jdkrX| |S | |S )a  
        Applies mosaic augmentation to the input image and labels.

        This method combines multiple images (3, 4, or 9) into a single mosaic image based on the 'n' attribute.
        It ensures that rectangular annotations are not present and that there are other images available for
        mosaic augmentation.

        Args:
            labels (Dict): A dictionary containing image data and annotations. Expected keys include:
                - 'rect_shape': Should be None as rect and mosaic are mutually exclusive.
                - 'mix_labels': A list of dictionaries containing data for other images to be used in the mosaic.

        Returns:
            (Dict): A dictionary containing the mosaic-augmented image and updated annotations.

        Raises:
            AssertionError: If 'rect_shape' is not None or if 'mix_labels' is empty.

        Examples:
            >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
            >>> augmented_data = mosaic._mix_transform(labels)
        
rect_shapeNz'rect and mosaic are mutually exclusive.rO   z-There are no other images for mosaic augment.   ri   )getr=   rp   _mosaic3_mosaic4_mosaic9r   r   r   r   rU   9  s    0zMosaic._mix_transformc                 C   s  g }| j }tdD ]L}|dkr$|n|d |d  }|d }|d\}}|dkrtj|d |d |jd fdtjd	}	|| }
}|||| || f}nJ|dkr|| ||| | || f}n$|dkr|| ||
 | |||
 f}|d
d \}}dd |D \}}}}||| d
|| d
f |	||||f< | ||| jd  || jd  }|	| q| 
|}|	| jd  | jd | jd  | jd f |d< |S )a  
        Creates a 1x3 image mosaic by combining three images.

        This method arranges three images in a horizontal layout, with the main image in the center and two
        additional images on either side. It's part of the Mosaic augmentation technique used in object detection.

        Args:
            labels (Dict): A dictionary containing image and label information for the main (center) image.
                Must include 'img' key with the image array, and 'mix_labels' key with a list of two
                dictionaries containing information for the side images.

        Returns:
            (Dict): A dictionary with the mosaic image and updated labels. Keys include:
                - 'img' (np.ndarray): The mosaic image array with shape (H, W, C).
                - Other keys from the input labels, updated to reflect the new image dimensions.

        Examples:
            >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=3)
            >>> labels = {
            ...     "img": np.random.rand(480, 640, 3),
            ...     "mix_labels": [{"img": np.random.rand(480, 640, 3)} for _ in range(2)],
            ... }
            >>> result = mosaic._mosaic3(labels)
            >>> print(result["img"].shape)
            (640, 640, 3)
        r|   r   rO   rM   imgresized_shaperl   r   dtypeNc                 s   s   | ]}t |d V  qdS r   Nmaxr\   r   r   r   	<genexpr>  r6   z"Mosaic._mosaic3.<locals>.<genexpr>rn   rz   rV   npfullshapeuint8_update_labelsro   r-   _cat_labels)r   r   mosaic_labelssr4   labels_patchr   hwZimg3h0w0cpadwpadhx1y1x2y2final_labelsr   r   r   r~   V  s,    &
,"
4zMosaic._mosaic3c                    sb  g }| j   fdd| jD \}}tdD ]}|dkr<|n|d |d  }|d }|d\}}	|dkrtj d	  d	 |jd	 fd
tjd}
t||	 dt|| d||f\}}}}|	||  |||  |	|f\}}}}n|dkr>|t|| dt	||	  d	 |f\}}}}d|||  t	|	|| |f\}}}}n|d	krt||	 d||t	 d	 || f\}}}}|	||  d|	t	|| |f\}}}}nb|dkr||t	||	  d	 t	 d	 || f\}}}}ddt	|	|| t	|| |f\}}}}|||||f |
||||f< || }|| }| 
|||}|| q*| |}|
|d< |S )a<  
        Creates a 2x2 image mosaic from four input images.

        This method combines four images into a single mosaic image by placing them in a 2x2 grid. It also
        updates the corresponding labels for each image in the mosaic.

        Args:
            labels (Dict): A dictionary containing image data and labels for the base image (index 0) and three
                additional images (indices 1-3) in the 'mix_labels' key.

        Returns:
            (Dict): A dictionary containing the mosaic image and updated labels. The 'img' key contains the mosaic
                image as a numpy array, and other keys contain the combined and adjusted labels for all four images.

        Examples:
            >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
            >>> labels = {
            ...     "img": np.random.rand(480, 640, 3),
            ...     "mix_labels": [{"img": np.random.rand(480, 640, 3)} for _ in range(3)],
            ... }
            >>> result = mosaic._mosaic4(labels)
            >>> assert result["img"].shape == (1280, 1280, 3)
        c                 3   s(   | ] }t t| d   | V  qdS )rl   N)r7   rP   rQ   r\   r   r   r   r     r6   z"Mosaic._mosaic4.<locals>.<genexpr>ri   r   rO   rM   r   r   rl   r   r   r|   )rn   ro   rz   rV   r   r   r   r   r   minr   r-   r   )r   r   r   ZycZxcr4   r   r   r   r   Zimg4Zx1aZy1aZx2aZy2aZx1bZy1bZx2bZy2br   r   r   r   r   r   r     s8    &((
,(
,(
0($
zMosaic._mosaic4c                 C   s  g }| j }d\}}tdD ]l}|dkr,|n|d |d  }|d }|d\}	}
|dkrtj|d |d |jd	 fd
tjd}|	|
 }}||||
 ||	 f}n^|dkr|||	 ||
 |f}n>|d	kr|| ||	 || |
 |f}n|dkr|| ||| |
 ||	 f}n|dkrB|| || || |
 || |	 f}n|dkrr|| |
 || || || |	 f}n|dkr|| | |
 || || | || |	 f}nV|dkr||
 || |	 ||| f}n.|dkr ||
 || | |	 ||| | f}|dd	 \}}dd |D \}}}}||| d|| df |||||f< |	|
 }}| ||| jd  || jd  }|	| q| 
|}|| jd  | jd | jd  | jd f |d< |S )aC  
        Creates a 3x3 image mosaic from the input image and eight additional images.

        This method combines nine images into a single mosaic image. The input image is placed at the center,
        and eight additional images from the dataset are placed around it in a 3x3 grid pattern.

        Args:
            labels (Dict): A dictionary containing the input image and its associated labels. It should have
                the following keys:
                - 'img' (numpy.ndarray): The input image.
                - 'resized_shape' (Tuple[int, int]): The shape of the resized image (height, width).
                - 'mix_labels' (List[Dict]): A list of dictionaries containing information for the additional
                  eight images, each with the same structure as the input labels.

        Returns:
            (Dict): A dictionary containing the mosaic image and updated labels. It includes the following keys:
                - 'img' (numpy.ndarray): The final mosaic image.
                - Other keys from the input labels, updated to reflect the new mosaic arrangement.

        Examples:
            >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=9)
            >>> input_labels = dataset[0]
            >>> mosaic_result = mosaic._mosaic9(input_labels)
            >>> mosaic_image = mosaic_result["img"]
        )rc   rc   rk   r   rO   rM   r   r   r|   rl   r   r   ri               Nc                 s   s   | ]}t |d V  qdS r   r   r\   r   r   r   r     r6   z"Mosaic._mosaic9.<locals>.<genexpr>r   )r   r   r   r   hpZwpr4   r   r   r   r   Zimg9r   r   r   r   r   r   r   r   r   r   r   r   r   r     sH    &
 

&
&
.

$,
"
4zMosaic._mosaic9c                 C   sJ   | d j dd \}}| d jdd | d || | d || | S )a7  
        Updates 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): 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.

        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)
        r   Nrl   	instancesxyxyformat)r   convert_bboxdenormalizeadd_padding)r   r   r   Znhnwr   r   r   r     s
    zMosaic._update_labelsc                 C   s   t |dkri S g }g }| jd }|D ] }||d  ||d  q&|d d |d d ||ft|dtj|dd| jd}|d || |d  }|d | |d< d	|d v r|d d	 |d	< |S )
a  
        Concatenates and processes 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]): A list of label dictionaries for each image in the mosaic.

        Returns:
            (Dict): 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.
                - mosaic_border (Tuple[int, int]): Mosaic border size.
                - 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', 'mosaic_border'])
        r   rl   rb   r   im_file	ori_shapeZaxis)r   r   r   rb   r   mosaic_borderr[   )	r=   rn   r-   r   concatenater   ro   clipZremove_zero_area_boxes)r   r   rb   r   rn   r   r   Zgoodr   r   r   r   .  s*    



zMosaic._cat_labels)rh   r   ri   )T)r"   r#   r$   r%   r   rR   rU   r~   r   r   staticmethodr   r   __classcell__r   r   rq   r   rg     s   
;:H
rg   c                       s8   e Zd ZdZddd fddZdd Zd	d
 Z  ZS )MixUpa  
    Applies 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_indexes: Returns a random index from the dataset.
        _mix_transform: Applies MixUp augmentation to the input labels.

    Examples:
        >>> from ultralytics.data.augment import MixUp
        >>> dataset = YourDataset(...)  # Your image dataset
        >>> mixup = MixUp(dataset, p=0.5)
        >>> augmented_labels = mixup(original_labels)
    Nr   r   c                    s   t  j|||d dS )a  
        Initializes 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].

        Examples:
            >>> from ultralytics.data.dataset import YOLODataset
            >>> dataset = YOLODataset("path/to/data.yaml")
            >>> mixup = MixUp(dataset, pre_transform=None, p=0.5)
        rH   N)rm   r   rL   rq   r   r   r   y  s    zMixUp.__init__c                 C   s   t dt| jd S )a  
        Get a random index from the dataset.

        This method returns a single random index from the dataset, which is used to select an image for MixUp
        augmentation.

        Returns:
            (int): A random integer index within the range of the dataset length.

        Examples:
            >>> mixup = MixUp(dataset)
            >>> index = mixup.get_indexes()
            >>> print(index)
            42
        r   rM   ru   r   r   r   r   rR     s    zMixUp.get_indexesc                 C   s   t jdd}|d d }|d | |d d|   t j|d< tj|d |d gdd|d< t |d |d gd|d< |S )	aG  
        Applies MixUp augmentation to the input labels.

        This method implements the MixUp augmentation technique as described in the paper
        "mixup: Beyond Empirical Risk Minimization" (https://arxiv.org/abs/1710.09412).

        Args:
            labels (Dict): A dictionary containing the original image and label information.

        Returns:
            (Dict): A dictionary containing the mixed-up image and combined label information.

        Examples:
            >>> mixer = MixUp(dataset)
            >>> mixed_labels = mixer._mix_transform(labels)
        g      @@rO   r   r   rM   r   r   rb   )r   rP   betaastyper   r   r   )r   r   rlabels2r   r   r   rU     s    (zMixUp._mix_transform)Nr   )r"   r#   r$   r%   r   rR   rU   r   r   r   rq   r   r   b  s   r   c                   @   sL   e Zd ZdZdddZd	d
 Zdd Zdd Zdd Zdd Z	dddZ
dS )RandomPerspectivea,  
    Implements 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.
        border (Tuple[int, int]): Mosaic border size as (x, y).
        pre_transform (Callable | None): Optional transform to apply before the random perspective.

    Methods:
        affine_transform: Applies affine transformations to the input image.
        apply_bboxes: Transforms bounding boxes using the affine matrix.
        apply_segments: Transforms segments and generates new bounding boxes.
        apply_keypoints: Transforms keypoints using the affine matrix.
        __call__: Applies the random perspective transformation to images and annotations.
        box_candidates: Filters 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   Nc                 C   s.   || _ || _|| _|| _|| _|| _|| _dS )a  
        Initializes 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): Scaling factor interval, e.g., a scale factor of 0.5 allows a resize between 50%-150%.
            shear (float): Shear intensity (angle in degrees).
            perspective (float): Perspective distortion factor.
            border (Tuple[int, int]): Tuple specifying mosaic border (top/bottom, left/right).
            pre_transform (Callable | None): Function/transform to apply to the image before starting the random
                transformation.

        Examples:
            >>> transform = RandomPerspective(degrees=10.0, translate=0.1, scale=0.5, shear=5.0)
            >>> result = transform(labels)  # Apply random perspective to labels
        N)degrees	translatescaleshearperspectivero   rJ   )r   r   r   r   r   r   ro   rJ   r   r   r   r     s    zRandomPerspective.__init__c                 C   s  t jdt jd}|jd  d |d< |jd  d |d< t jdt jd}t| j | j|d< t| j | j|d	< t jdt jd}t| j | j}td| j d| j }t	j
|d
|d|dd< t jdt jd}tt| j | jtj d |d< tt| j | jtj d |d< t jdt jd}	td| j d| j | jd  |	d< td| j d| j | jd  |	d< |	| | | | }
|d dks|d dks|
t dk r| jrt	j||
| jdd}nt	j||
dd | jdd}||
|fS )a  
        Applies a sequence of affine transformations centered around the image center.

        This function performs a series of geometric transformations on the input image, including
        translation, perspective change, rotation, scaling, and shearing. The transformations are
        applied in a specific order to maintain consistency.

        Args:
            img (np.ndarray): Input image to be transformed.
            border (Tuple[int, int]): Border dimensions for the transformed image.

        Returns:
            (Tuple[np.ndarray, np.ndarray, float]): A tuple containing:
                - np.ndarray: Transformed image.
                - np.ndarray: 3x3 transformation matrix.
                - float: Scale factor applied during the transformation.

        Examples:
            >>> import numpy as np
            >>> img = np.random.rand(100, 100, 3)
            >>> border = (10, 10)
            >>> transformed_img, matrix, scale = affine_transform(img, border)
        r|   r   rM   rl   )r   rl   r   )rM   rl   )rl   r   )rl   rM   r   )Zanglecenterr   N   rt   )rM   r   r   r   r   r   )ZdsizeZborderValue)r   eyefloat32r   rP   rQ   r   r   r   cv2ZgetRotationMatrix2Dmathtanr   pir   sizeanyZwarpPerspectiveZ
warpAffine)r   r   ro   CPRar   STMr   r   r   affine_transform  s,    &&&&0z"RandomPerspective.affine_transformc                 C   s  t |}|dkr|S tj|d df|jd}|ddg df |d d|ddddf< ||j }| jr|ddddf |ddddf  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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 (torch.Tensor): Bounding boxes in xyxy format with shape (N, 4), where N is the number
                of bounding boxes.
            M (torch.Tensor): Affine transformation matrix with shape (3, 3).

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

        Examples:
            >>> bboxes = torch.tensor([[10, 10, 20, 20], [30, 30, 40, 40]])
            >>> M = torch.eye(3)
            >>> transformed_bboxes = apply_bboxes(bboxes, M)
        r   ri   r|   r   N)r   rM   rl   r|   r   r|   rl   rM   rl   r   )r   rl   ri   r   )rM   r|   r   r   rM   )
r=   r   onesr   reshaper   r   r   r   r   )r   bboxesr   rp   xyr]   yr   r   r   apply_bboxes7  s    0
JzRandomPerspective.apply_bboxesc                    s$  |j dd \}}|dkr"g |fS tj|| df|jd}|dd}||ddddf< ||j }|ddddf |ddddf  }||dd}t fd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).

        Returns:
            (Tuple[np.ndarray, np.ndarray]): A tuple containing:
                - New bounding boxes with shape (N, 4) in xyxy format.
                - Transformed and clipped segments with shape (N, M, 2).

        Examples:
            >>> segments = np.random.rand(10, 500, 2)  # 10 segments with 500 points each
            >>> M = np.eye(3)  # Identity transformation matrix
            >>> new_bboxes, new_segments = apply_segments(segments, M)
        Nrl   r   r|   r   rc   c                    s$   g | ]}t | jd   jd qS rt   )r   r   )r3   r   r   r   r   r5   y  r6   z4RandomPerspective.apply_segments.<locals>.<listcomp>.r   rM   .rM   ri   )r   r   r   r   r   r   stackr   )r   segmentsr   rp   numr   r   r   r   r   apply_segmentsY  s    
(44z RandomPerspective.apply_segmentsc                 C   s(  |j dd \}}|dkr|S tj|| df|jd}|d || d}|dddf || d|ddddf< ||j }|ddddf |ddddf  }|dddf dk |dddf dk B |dddf | jd kB |dddf | jd kB }d||< tj||gd	d
||dS )a  
        Applies 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, 17, 3), where N is the number of instances,
                17 is the number of keypoints per instance, and 3 represents (x, y, visibility).
            M (np.ndarray): 3x3 affine transformation matrix.

        Returns:
            (np.ndarray): Transformed keypoints array with the same shape as input (N, 17, 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)
        Nrl   r   r|   r   ).rl   rM   .rc   r   )r   r   r   r   r   r   r   r   )r   	keypointsr   rp   Znkptr   visibleZout_maskr   r   r   apply_keypoints~  s    ,
(\z!RandomPerspective.apply_keypointsc                 C   s  | j rd|vr|  |}|dd |d }|d }|d}|jdd |j|jdd	 ddd
   |d| j}|jd |d d	  |jd |d d	  f| _| ||\}}}| |j	|}|j
}	|j}
t|	r| |	|\}}	|
dur| |
|}
t||	|
ddd}|j| j  |j||dd | j|j	j|j	jt|	rHdndd}|| |d< || |d< ||d< |jdd	 |d< |S )a  
        Applies random perspective and affine transformations to an image and its associated labels.

        This method performs a series of transformations including rotation, translation, scaling, shearing,
        and perspective distortion on the input image and adjusts the corresponding bounding boxes, segments,
        and keypoints accordingly.

        Args:
            labels (Dict): A dictionary containing image data and annotations.
                Must include:
                    'img' (ndarray): The input image.
                    'cls' (ndarray): Class labels.
                    'instances' (Instances): Object instances with bounding boxes, segments, and keypoints.
                May include:
                    'mosaic_border' (Tuple[int, int]): Border size for mosaic augmentation.

        Returns:
            (Dict): Transformed labels dictionary containing:
                - 'img' (np.ndarray): The transformed image.
                - 'cls' (np.ndarray): Updated class labels.
                - 'instances' (Instances): Updated object instances.
                - 'resized_shape' (Tuple[int, int]): New image shape after transformation.

        Examples:
            >>> transform = RandomPerspective()
            >>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
            >>> labels = {
            ...     "img": image,
            ...     "cls": np.array([0, 1, 2]),
            ...     "instances": Instances(bboxes=np.array([[10, 10, 50, 50], [100, 100, 150, 150]])),
            ... }
            >>> result = transform(labels)
            >>> assert result["img"].shape[:2] == result["resized_shape"]
        r   	ratio_padNr   rb   r   r   r   rl   rc   rM   r   F)bbox_format
normalizedT)Zscale_wZscale_hZ	bbox_only{Gz?r   )box1box2area_thrr   )rJ   rV   r   r   r   ro   r   r   r   r   r   r   r=   r   r   r   r   r   box_candidatesr   )r   r   r   rb   r   ro   r   r   r   r   r   Znew_instancesr4   r   r   r   r!     s:    #

.zRandomPerspective.__call__rl   d   缉ؗҜ<c                 C   s   |d |d  |d |d   }}|d |d  |d |d   }	}
t |	|
|  |
|	|  }|	|k|
|k@ |	|
 || |  |k@ ||k @ 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 (numpy.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 (numpy.ndarray): Augmented boxes after transformation, shape (4, N). Format is
                [x1, y1, x2, y2] in absolute coordinates.
            wh_thr (float): Width and height threshold in pixels. Boxes smaller than this in either
                dimension are rejected.
            ar_thr (float): 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:
            (numpy.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]
        rl   r   r|   rM   )r   maximum)r   r   r   Zwh_thrZar_thrr   ZepsZw1Zh1Zw2Zh2arr   r   r   r     s    !""z RandomPerspective.box_candidates)r   r   r   r   r   r   N)rl   r   r   r   )r"   r#   r$   r%   r   r   r   r   r   r!   r   r   r   r   r   r     s   " 
?"%"Nr   c                   @   s(   e Zd ZdZd	ddddZdd ZdS )
	RandomHSVa  
    Randomly adjusts 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:
        __call__: Applies 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}
        >>> augmented_labels = augmenter(labels)
        >>> augmented_image = augmented_labels["img"]
    r   Nr   c                 C   s   || _ || _|| _dS )ap  
        Initializes 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].

        Examples:
            >>> hsv_aug = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
            >>> augmented_image = hsv_aug(image)
        Nhgainsgainvgain)r   r   r   r   r   r   r   r   -  s    zRandomHSV.__init__c                 C   s   |d }| j s| js| jrtjddd| j | j| jg d }tt|tj	\}}}|j
}tjdd|j
d}||d  d |}	t||d  dd	|}
t||d
  dd	|}tt||	t||
t||f}tj|tj|d |S )a  
        Applies 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): A dictionary containing image data and metadata. Must include an 'img' key with
                the image as a numpy array.

        Returns:
            (None): The function modifies the input 'labels' dictionary in-place, updating the 'img' key
                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)}
            >>> hsv_augmenter(labels)
            >>> augmented_img = labels["img"]
        r   rc   rM   r|   r      r   r      rl   )dst)r   r   r   r   rP   rQ   r   splitZcvtColorZCOLOR_BGR2HSVr   Zaranger   r   mergeZLUTZCOLOR_HSV2BGR)r   r   r   r   huesatvalr   r]   Zlut_hueZlut_satZlut_valZim_hsvr   r   r   r!   @  s    $(zRandomHSV.__call__)r   r   r   r"   r#   r$   r%   r   r!   r   r   r   r   r     s   r   c                   @   s(   e Zd ZdZd
ddddZdd	 ZdS )
RandomFlipaD  
    Applies 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__: Applies 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   
horizontalNr   c                 C   sR   |dv sJ d| d|  kr*dks<n J d| d|| _ || _|| _dS )aY  
        Initializes 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.

        Examples:
            >>> flip = RandomFlip(p=0.5, direction="horizontal")
            >>> flip = RandomFlip(p=0.7, direction="vertical", flip_idx=[1, 0, 3, 2, 5, 4])
        >   r  verticalz2Support direction `horizontal` or `vertical`, got r   r   rj   r;   N)rK   	directionflip_idx)r   rK   r  r  r   r   r   r   {  s
    &zRandomFlip.__init__c                 C   s   |d }| d}|jdd |jdd \}}|jr:dn|}|jrHdn|}| jdkrxt | jk rxt|}|| | jd	krt | jk rt	|}|	| | j
dur|jdurt|jdd| j
ddf |_t||d< ||d< |S )
a  
        Applies random flip to an image and updates any instances like bounding boxes or keypoints accordingly.

        This method randomly flips the input image either horizontally or vertically based on the initialized
        probability and direction. It also updates the corresponding instances (bounding boxes, keypoints) to
        match the flipped image.

        Args:
            labels (Dict): A dictionary containing the following keys:
                'img' (numpy.ndarray): The image to be flipped.
                'instances' (ultralytics.utils.instance.Instances): An object containing bounding boxes and
                    optionally keypoints.

        Returns:
            (Dict): The same dictionary with the flipped image and updated instances:
                'img' (numpy.ndarray): The flipped image.
                'instances' (ultralytics.utils.instance.Instances): Updated instances matching the flipped image.

        Examples:
            >>> labels = {"img": np.random.rand(640, 640, 3), "instances": Instances(...)}
            >>> random_flip = RandomFlip(p=0.5, direction="horizontal")
            >>> flipped_labels = random_flip(labels)
        r   r   xywhr   Nrl   rM   r  r  )rV   r   r   r   r  rP   rK   r   flipudfliplrr  r   ascontiguousarray)r   r   r   r   r   r   r   r   r   r!     s"    




"zRandomFlip.__call__)r   r  Nr   r   r   r   r   r  e  s   r  c                   @   s,   e Zd ZdZdddZdd	d
Z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.
        scaleFill (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"]
    rh   rh   FT    c                 C   s(   || _ || _|| _|| _|| _|| _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.
            scaleFill (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).

        Attributes:
            new_shape (Tuple[int, int]): Target size for the resized image.
            auto (bool): Flag for using minimum rectangle resizing.
            scaleFill (bool): Flag for stretching image without padding.
            scaleup (bool): Flag for allowing upscaling.
            stride (int): Stride value for ensuring image size is divisible by stride.

        Examples:
            >>> letterbox = LetterBox(new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, stride=32)
            >>> resized_img = letterbox(original_img)
        N)	new_shapeauto	scaleFillscaleupstrider   )r   r  r  r  r  r   r  r   r   r   r     s    zLetterBox.__init__Nc              	   C   sD  |du ri }|du r| dn|}|jdd }|d| j}t|trP||f}t|d |d  |d |d  }| jst|d}||f}tt|d | tt|d | f}|d |d  |d |d   }	}
| j	rt
|	| jt
|
| j }	}
n@| jr:d\}	}
|d |d f}|d |d  |d |d  f}| jrR|	d }	|
d }
|ddd	 |krxtj||tjd
}| jrtt|
d ndtt|
d  }}| jrtt|	d ndtt|	d  }}tj|||||tjdd}| dr|d ||ff|d< t|r<| |||	|
}||d< ||d< |S |S dS )a  
        Resizes and pads 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 | 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 | Tuple): If 'labels' is provided, returns an updated dictionary with the resized and padded image,
                updated labels, and additional metadata. If 'labels' is empty, returns a tuple containing the resized
                and padded image, and a tuple of (ratio, (left_pad, top_pad)).

        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   rl   r{   r   rM   r   )r   r   rc   interpolationr   r   )r:   r   r   )r}   r   rV   r  r'   r7   r   r  roundr  r   modr  r  r   r   resizeINTER_LINEARZcopyMakeBorderZBORDER_CONSTANTr=   r   )r   r   imager   r   r  r   ratioZ	new_unpadZdwZdhtopbottomleftrightr   r   r   r!     sJ    
"
("  ..
zLetterBox.__call__c                 C   sX   |d j dd |d j|d jdd ddd   |d j|  |d || |S )a  
        Updates 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): 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.

        Returns:
            (Dict): 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)
        r   r   r   r   Nrl   rc   )r   r   r   r   r   )r   r   r  r   r   r   r   r   r   A  s
    &zLetterBox._update_labels)r  FFTTr  )NN)r"   r#   r$   r%   r   r!   r   r   r   r   r   r
    s   
!
Dr
  c                       sL   e Zd ZdZddd fddZdd	 Zd
d Zdd Zi fddZ  Z	S )	CopyPasteaV  
    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_indexes: Returns a random index from the dataset.
        _mix_transform: Applies Copy-Paste augmentation to the input labels.
        __call__: Applies the Copy-Paste transformation to images and annotations.

    Examples:
        >>> from ultralytics.data.augment import CopyPaste
        >>> dataset = YourDataset(...)  # Your image dataset
        >>> copypaste = CopyPaste(dataset, p=0.5)
        >>> augmented_labels = copypaste(original_labels)
    Nr   flipr   c                    s4   t  j|||d |dv s*J d| d|| _dS )z\Initializes CopyPaste object with dataset, pre_transform, and probability of applying MixUp.rH   >   mixupr  z1Expected `mode` to be `flip` or `mixup`, but got r;   N)rm   r   mode)r   rI   rJ   rK   r!  rq   r   r   r   x  s    zCopyPaste.__init__c                 C   s   t dt| jd S )zMReturns a list of random indexes from the dataset for CopyPaste augmentation.r   rM   ru   r   r   r   r   rR   ~  s    zCopyPaste.get_indexesc                 C   s   |d d }|  ||S )]Applies Copy-Paste augmentation to combine objects from another image into the current image.rO   r   )
_transform)r   r   r   r   r   r   rU     s    zCopyPaste._mix_transformc                    s   t |d jdks jdkr |S  jdkr4 |S   }t|trL|g} fdd|D } jdurt	|D ]\}} |||< qp||d<  
|} |}|dd |S )z;Applies Copy-Paste augmentation to an image and its labels.r   r   r  c                    s   g | ]} j |qS r   rN   r2   r   r   r   r5     r6   z&CopyPaste.__call__.<locals>.<listcomp>NrO   )r=   r   rK   r!  r#  rR   r'   r7   rJ   rS   rT   rU   rV   rW   r   r   r   r!     s     





zCopyPaste.__call__c                 C   s  |d }|d }|j dd \}}|d}|jdd ||| t|j tj}|dd}	|	du rzt|}	|	| t	|	j
|j
}
t|
dk d	d
 }t|}t|
d	| }|| }|dt| j|  D ]`}tj||d||g fd
d}tj||	|g fd
d}t||	j|g tjddtj q|dt|d	}|t}|| ||< ||d< ||d< ||d< |S )r"  r   rb   Nrl   r   r   r   g333333?rM   r   r   rc   )rM   rM   rM   )r   rV   r   r   r   zerosr   r   r  r   r   Znonzeroallr=   Zargsortr   r  rK   r   r}   r   r   ZdrawContoursr   r   Zint32ZFILLEDr  bool)r   Zlabels1r   imrb   r   r   r   Zim_newZ
instances2ZioarX   rp   
sorted_idxjresultr4   r   r   r   r#    s6    

 &
zCopyPaste._transform)NNr   r  )
r"   r#   r$   r%   r   rR   rU   r!   r#  r   r   r   rq   r   r  _  s   r  c                   @   s"   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__: Applies the Albumentations transformations to the input labels.

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

    Notes:
        - The Albumentations package must be installed to use this class.
        - If the package is not installed or an error occurs during initialization, the transform will be set to None.
        - Spatial transforms are handled differently and require special processing for bounding boxes.
    r   c              
      s4  || _ d| _td}zddl}t|jddd h d |jdd	|jdd	|jdd	|j	dd	|j
d
d	|jd
d	|jdd
dg}t fdd|D | _| jr|j||jddgddn||| _t|ddd |D   W nH ty   Y n8 ty. } zt| |  W Y d}~n
d}~0 0 dS )a  
        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.

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

        Raises:
            ImportError: If the Albumentations package is not installed.
            Exception: For any other errors during initialization.

        Examples:
            >>> transform = Albumentations(p=0.5)
            >>> augmented = transform(image=image, bboxes=bboxes, class_labels=classes)
            >>> augmented_image = augmented["image"]
            >>> augmented_bboxes = augmented["bboxes"]

        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.
        Nzalbumentations: r   z1.0.3T)hard>(   ZCropLambdaZShiftScaleRotateZPerspectiver   ZOpticalDistortionZ	XYMaskingZLongestMaxSizeZRandomSizedCropZPiecewiseAffineZD4ZRandomCropFromBordersZCoarseDropoutZPixelDropoutZCropNonEmptyMaskIfExistsZSmallestMaxSizeZVerticalFlipZGridDropoutZFlipZHorizontalFlipZRotateZNoOpResizeZMaskDropoutZElasticTransform
CenterCropZ
RandomCropZPadIfNeededZ
SafeRotateZRandomGridShuffleZBBoxSafeRandomCropZAffineZRandomRotate90ZRandomSizedBBoxSafeCropZ
CropAndPadZ	TransposeZGridDistortionRandomResizedCropZRandomScaleZMorphologicalr   rK   r   K   )Zquality_lowerrK   c                 3   s   | ]}|j j v V  qd S N)rD   r"   )r3   r.   Zspatial_transformsr   r   r   >  r6   z*Albumentations.__init__.<locals>.<genexpr>Zyoloclass_labels)r   Zlabel_fields)Zbbox_paramsrB   c                 s   s"   | ]}|j r| d dV  qdS )zalways_apply=False,  N)rK   replacer\   r   r   r   r   D  r6   )rK   r.   r	   Zalbumentationsr
   __version__ZBlurZ
MedianBlurZToGrayZCLAHEZRandomBrightnessContrastZRandomGammaZImageCompressionr   contains_spatialr&   Z
BboxParamsr   inforE   ImportError	Exception)r   rK   prefixAr   er   r4  r   r     s2    -





"zAlbumentations.__init__c                 C   s   | j du st | jkr|S | jr|d }t|r|d }|d d |d j|jdd ddd   |d j}| j |||d}t|d	 d
kr|d |d< t	
|d	 |d< t	j
|d t	jd}|d j|d n| j |d dd |d< |S )a{  
        Applies 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): A dictionary containing image data and annotations. Expected keys are:
                - 'img': numpy.ndarray representing the image
                - 'cls': numpy.ndarray of class labels
                - 'instances': object containing bounding boxes and other instance information

        Returns:
            (Dict): 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.
        Nrb   r   r   r  rl   rc   )r  r   r5  r5  r   r  r   r   )r   )r  )r.   rP   rK   r9  r=   r   	normalizer   r   r   arrayr   update)r   r   rb   r'  r   newr   r   r   r!   J  s"    "
zAlbumentations.__call__N)r   r   r   r   r   r   r+    s   
lr+  c                	   @   s2   e Zd ZdZdddZd	d
 Zdd Zdd ZdS )Formata  
    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__: Formats labels dictionary with image, classes, bounding boxes, and optionally masks and keypoints.
        _format_img: Converts image from Numpy array to PyTorch tensor.
        _format_segments: Converts 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  TFri   r   c
           
      C   s:   || _ || _|| _|| _|| _|| _|| _|| _|	| _dS )a  
        Initializes 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.

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

        Examples:
            >>> format = Format(bbox_format="xyxy", return_mask=True, return_keypoint=False)
            >>> print(format.bbox_format)
            xyxy
        N)	r   r@  return_maskreturn_keypoint
return_obb
mask_ratiomask_overlap	batch_idxbgr)
r   r   r@  rE  rF  rG  rH  rI  rJ  rK  r   r   r   r     s    -zFormat.__init__c           	      C   s  | d}|jdd \}}| d}| d}|j| jd ||| t|}| jr|r~| ||||\}}}t	|}n0t
| jrdn||jd | j |jd | j }||d	< | ||d< |rt	|nt
||d< |rt	|jnt
|d
f|d< | jrJt	|j|d< | jrJ|d d  |  < |d d  |  < | jr|t|jrntt	|jnt
d|d< | jr|d ddddgf  |  < |d ddddgf  |  < | jrt
||d< |S )a  
        Formats image annotations for object detection, instance segmentation, and pose estimation tasks.

        This method standardizes the image and instance annotations to be used by the `collate_fn` in PyTorch
        DataLoader. It processes the input labels dictionary, converting annotations to the specified format and
        applying normalization if required.

        Args:
            labels (Dict): A dictionary containing image and annotation data with the following keys:
                - 'img': The input image as a numpy array.
                - 'cls': Class labels for instances.
                - 'instances': An Instances object containing bounding boxes, segments, and keypoints.

        Returns:
            (Dict): A dictionary with formatted data, including:
                - 'img': Formatted image tensor.
                - 'cls': Class labels tensor.
                - 'bboxes': Bounding boxes tensor in the specified format.
                - 'masks': Instance masks tensor (if return_mask is True).
                - 'keypoints': Keypoints tensor (if return_keypoint is True).
                - 'batch_idx': Batch index tensor (if batch_idx is True).

        Examples:
            >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True)
            >>> labels = {"img": np.random.rand(640, 640, 3), "cls": np.array([0, 1]), "instances": Instances(...)}
            >>> formatted_labels = formatter(labels)
            >>> print(formatted_labels.keys())
        r   Nrl   rb   r   r   rM   r   masksri   r   r   r   r   )r   r   r|   rJ  )rV   r   r   r   r   r=   rE  _format_segmentstorch
from_numpyr$  rI  rH  _format_imgr   rF  r   r@  rG  r   r   rJ  )	r   r   r   r   r   rb   r   nlrL  r   r   r   r!     s@    


("$  zFormat.__call__c                 C   s`   t |jdk rt|d}|ddd}ttdd| jkrL|ddd n|}t	
|}|S )a  
        Formats 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 flips the color channels from RGB to BGR.
        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|   rc   rl   r   rM   N)r=   r   r   Zexpand_dims	transposer	  rP   rQ   rK  rN  rO  )r   r   r   r   r   rP    s    *
zFormat._format_imgc                 C   s^   |j }| jr>t||f|| jd\}}|d }|| }|| }nt||f|d| jd}|||fS )a  
        Converts polygon segments to bitmap masks.

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

        Returns:
            (tuple): Tuple containing:
                masks (numpy.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 (numpy.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_ratioNrM   )colorrS  )r   rI  r   rH  r   )r   r   rb   r   r   r   rL  r(  r   r   r   rM  7  s    
zFormat._format_segmentsN)	r  TFFFri   TTr   )r"   r#   r$   r%   r   r!   rP  rM  r   r   r   r   rD    s            
7CrD  c                   @   sB   e Zd ZdZdeeeef eeeddd	d
Ze	e	dddZ
dS )RandomLoadTexta  
    Randomly samples positive and negative texts and updates 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 (str): The text used for padding when padding is True.

    Methods:
        __call__: Processes the input labels and returns 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']
    {}P   rX  rX  Fr6  N)prompt_formatneg_samplesmax_samplespaddingpadding_valuer   c                 C   s"   || _ || _|| _|| _|| _dS )a;  
        Initializes 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. Default is '{}'. 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. Default is (80, 80).
            max_samples (int): The maximum number of different text samples in one image. Default is 80.
            padding (bool): Whether to pad texts to max_samples. If True, the number of texts will always
                be equal to max_samples. Default is False.
            padding_value (str): The padding text to use when padding is True. Default is an empty string.

        Attributes:
            prompt_format (str): The format string for the prompt.
            neg_samples (Tuple[int, int]): The range for sampling negative texts.
            max_samples (int): The maximum number of text samples.
            padding (bool): Whether padding is enabled.
            padding_value (str): The value used for padding.

        Examples:
            >>> random_load_text = RandomLoadText(prompt_format="Object: {}", neg_samples=(50, 100), max_samples=120)
            >>> random_load_text.prompt_format
            'Object: {}'
            >>> random_load_text.neg_samples
            (50, 100)
            >>> random_load_text.max_samples
            120
        N)rY  rZ  r[  r\  r]  )r   rY  rZ  r[  r\  r]  r   r   r   r   r  s
    )zRandomLoadText.__init__)r   r   c                    s  d|v sJ d|d }t |}tj|dtd}t|  t  | jkr`tj	 | jd t
t
|| jt   tj| j } fddt|D }tj	||d} | }t| dd	 t|D }tjt |d
 td}	g }
t|d D ],\}}||vr
qd|	|< |
|| g q|d
 |	 |d
< t|
|d< g }|D ]D}|| }t |dkshJ | j|tt | }|| qJ| jrt  t | }| j| }|dkr|| jg| 7 }||d< |S )aQ  
        Randomly samples positive and negative texts and updates class indices accordingly.

        This method samples positive texts based on the existing class labels in the image, and randomly
        selects negative texts from the remaining classes. It then updates the class indices to match the
        new sampled text order.

        Args:
            labels (Dict): A dictionary containing image labels and metadata. Must include 'texts' and 'cls' keys.

        Returns:
            (Dict): Updated labels dictionary with new 'cls' and 'texts' entries.

        Examples:
            >>> loader = RandomLoadText(prompt_format="A photo of {}", neg_samples=(5, 10), max_samples=20)
            >>> labels = {"cls": np.array([[0], [1], [2]]), "texts": [["dog"], ["cat"], ["bird"]]}
            >>> updated_labels = loader(labels)
        r[   zNo texts found in labels.rb   r   rr   c                    s   g | ]}| vr|qS r   r   r2   Z
pos_labelsr   r   r5     r6   z+RandomLoadText.__call__.<locals>.<listcomp>c                 S   s   i | ]\}}||qS r   r   )r3   r4   rf   r   r   r   ra     r6   z+RandomLoadText.__call__.<locals>.<dictcomp>r   rc   Tr   )r=   r   asarrayrV   r7   uniquer@   r[  rP   sampler   rv   rZ  rz   shufflerS   r$  r&  re   r-   rA  rY  r   	randranger\  r]  )r   r   Zclass_textsZnum_classesrb   rZ  Z
neg_labelsZsampled_labelsZ	label2idsZ	valid_idxZnew_clsr4   rf   r[   ZpromptspromptZvalid_labelsZnum_paddingr   r^  r   r!     sF    "



zRandomLoadText.__call__)rV  rW  rX  Fr6  )r"   r#   r$   r%   strr   r7   r&  r   dictr!   r   r   r   r   rU  X  s        
/rU  Fc           	      C   sf  t | ||jd}t|j|j|j|j|j|r.dnt||fdd}t	||g}|j
dkrp|dt|j|j
d n.|t| t	t | ||jd|g|j|j
d | jd	g }| jr| jd
d}t|dkr|jdkrd|_td n0|rt||d krtd| d|d  t	|t| ||jdtddt|j|j|jdtd|jdtd|j|dgS )a_  
    Applies 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 (Dict): A dictionary 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
        >>> dataset = YOLODataset(img_path="path/to/images", imgsz=640)
        >>> hyp = {"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])
    )rn   rK   N)r  )r   r   r   r   r   rJ   r  rM   )rK   r!  )rJ   rK   r!  r  	kpt_shaper   r   uZ   WARNING ⚠️ No 'flip_idx' array defined in data.yaml, setting augmentation 'fliplr=0.0'zdata.yaml flip_idx=z& length must be equal to kpt_shape[0]=)rJ   rK   r   r1  r   r  )r  rK   r  )r  rK   r  ) rg   mosaicr   r   r   r   r   r   r
  r&   Zcopy_paste_moder/   r  Z
copy_paster-   r+   r}   Zuse_keypointsr=   r  r   warning
ValueErrorr   r   r+  r   hsv_hhsv_shsv_vr  r  )	rI   rn   ZhypZstretchrh  ZaffinerJ   r  rg  r   r   r   v8_transforms  sJ    	
rn     ZBILINEARcrop_fractionc              	      s   ddl m} t| ttfrPt| dks8J dt|  t fdd| D }nt|   }||f}|d |d kr|j|d t	|j
|dg}n||g}||| | |jt|t|d	g ||S )
aQ  
    Creates 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 (int | tuple): The target size for the transformed image. If an int, it defines the shortest edge. If a
            tuple, it defines (height, width).
        mean (tuple): Mean values for each RGB channel used in normalization.
        std (tuple): Standard deviation values for each RGB channel used in normalization.
        interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'.
        crop_fraction (float): Fraction of the image to be cropped.

    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   Nrl   z+'size' tuples must be length 2, not length c                 3   s   | ]}t |  V  qd S r3  )r   floorr\   rp  r   r   r   F	  r6   z&classify_transforms.<locals>.<genexpr>rM   r  meanstd)torchvision.transformsr)   r'   r^   r(   r=   r   rr  r.  getattrInterpolationModeextendr/  ToTensor	NormalizerN  tensorr&   )r   rt  ru  r  rq  r   Z
scale_sizeZtflr   rp  r   classify_transforms$	  s     r}  r   r   gQ?g?c                 C   s  ddl m} t| ts&td|  dt|p.d}t|p:d}t|j|}|j| |||dg}|dkrx|	|j
|d	 |dkr|	|j|d	 g }d
}|r^t|tsJ dt| | }|dkrtr|	|j|d n
td np|dkrtr|	|j|d n
td n@|dkrNtrB|	|j|d n
td ntd| d|s||	|j|
|
|	|d | |jt|t|d|j|ddg}||| | S )aK  
    Creates 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): Mean values for normalization, one per channel.
        std (tuple): Standard deviation values for normalization, one per channel.
        scale (tuple | None): Range of size of the origin size cropped.
        ratio (tuple | None): Range of aspect ratio of the origin aspect ratio cropped.
        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_transforms() size z# must be integer, not (list, tuple))g{Gz?r   )g      ?gUUUUUU?)r   r  r  r   r1  Fz1Provided argument should be string, but got type Zrandaugmentr  zH"auto_augment=randaugment" requires torchvision >= 0.11.0. Disabling it.ZaugmixzC"auto_augment=augmix" requires torchvision >= 0.13.0. Disabling it.Z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)Z
brightnessZcontrastZ
saturationr   rs  T)rK   Zinplace)rv  r)   r'   r7   	TypeErrorr^   rw  rx  r0  r-   ZRandomHorizontalFlipZRandomVerticalFlipre  r8   r   ZRandAugmentr   ri  r   ZAugMixr   ZAutoAugmentrj  ZColorJitterrz  r{  rN  r|  ZRandomErasingr&   )r   rt  ru  r   r  ZhflipZvflipZauto_augmentrk  rl  rm  Zforce_color_jitterZerasingr  r   Zprimary_tflZsecondary_tflZdisable_color_jitterZ	final_tflr   r   r   classify_augmentations]	  sL    .



r  c                       s*   e Zd ZdZd	 fdd	Zdd Z  ZS )
ClassifyLetterBoxa~  
    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__: Applies 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  c                    s8   t    t|tr||fn|\| _| _|| _|| _dS )a  
        Initializes 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. Default is False.
            stride (int): The stride value, used when 'auto' is True. Default is 32.

        Attributes:
            h (int): Target height of the letterboxed image.
            w (int): Target width of the letterboxed image.
            auto (bool): Flag indicating whether to automatically calculate short side.
            stride (int): Stride value for automatic short side calculation.

        Examples:
            >>> transform = ClassifyLetterBox(size=224)
            >>> img = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
            >>> result = transform(img)
            >>> print(result.shape)
            (224, 224, 3)
        N)rm   r   r'   r7   r   r   r  r  )r   r   r  r  rq   r   r   r   	  s    
zClassifyLetterBox.__init__c                    s   |j dd \}}t j|  j| }t|| t||  }} jr^ fdd||fD n
 j jf\}}t|| d d t|| d d  }	}
tj||dfd|jd}t	j
|||ft	jd	||	|	| |
|
| f< |S )
a8  
        Resizes and pads 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 (numpy.ndarray): Input image as a numpy array with shape (H, W, C).

        Returns:
            (numpy.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)
        Nrl   c                 3   s$   | ]}t | j  j V  qd S r3  )r   ceilr  r\   r   r   r   r   
  r6   z-ClassifyLetterBox.__call__.<locals>.<genexpr>r   r|   r   r   r  )r   r   r   r   r  r  r   r   r   r   r  r  )r   r'  imhimwr   r   r   hswsr  r  Zim_outr   r   r   r!   	  s    ,*.zClassifyLetterBox.__call__)r  Fr  r"   r#   r$   r%   r   r!   r   r   r   rq   r   r  	  s   r  c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )r/  a  
    Applies 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__: Applies 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)
    rh   c                    s,   t    t|tr||fn|\| _| _dS )a<  
        Initializes 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.

        Returns:
            (None): This method initializes the object and does not return anything.

        Examples:
            >>> transform = CenterCrop(224)
            >>> img = np.random.rand(300, 300, 3)
            >>> cropped_img = transform(img)
            >>> print(cropped_img.shape)
            (224, 224, 3)
        N)rm   r   r'   r7   r   r   )r   r   rq   r   r   r   6
  s    
zCenterCrop.__init__c                 C   s~   t |tjrt|}|jdd \}}t||}|| d || d  }}tj|||| ||| f | j| j	ftj
dS )a"  
        Applies center cropping to an input image.

        This method resizes and crops the center of the image using a letterbox method. It maintains the aspect
        ratio of the original image while fitting it into the specified dimensions.

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

        Returns:
            (numpy.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)
        Nrl   r  )r'   r   r   r_  r   r   r   r  r   r   r  )r   r'  r  r  mr  r  r   r   r   r!   N
  s    

zCenterCrop.__call__)rh   r  r   r   rq   r   r/   
  s   r/  c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )rz  a2  
    Converts 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__: Applies 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 RGB format with shape (C, H, W), normalized to [0, 1].
    Fc                    s   t    || _dS )a  
        Initializes 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). Default is False.

        Examples:
            >>> transform = ToTensor(half=True)
            >>> img = np.random.rand(640, 640, 3)
            >>> tensor_img = transform(img)
            >>> print(tensor_img.dtype)
            torch.float16
        N)rm   r   half)r   r  rq   r   r   r   
  s    
zToTensor.__init__c                 C   sF   t |dddd }t|}| jr2| n| }|d }|S )a  
        Transforms 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 and
        the color channels are reversed from BGR to RGB.

        Args:
            im (numpy.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 RGB 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
        )rl   r   rM   Nrc   g     o@)r   r	  rR  rN  rO  r  float)r   r'  r   r   r   r!   
  s
    
zToTensor.__call__)Fr  r   r   rq   r   rz  k
  s   rz  )F)7r   rP   copyr   typingr   r   r   numpyr   rN  ZPILr   Zultralytics.data.utilsr   r   Zultralytics.utilsr   r	   Zultralytics.utils.checksr
   Zultralytics.utils.instancer   Zultralytics.utils.metricsr   Zultralytics.utils.opsr   r   Zultralytics.utils.torch_utilsr   r   r   ZDEFAULT_MEANZDEFAULT_STDZDEFAULT_CROP_FRACTIONr   r&   rG   rg   r   r   r   r  r
  r  r+  rD  rU  rn  r  r}  r  r  r/  rz  r   r   r   r   <module>   s   x - ,  {U  `P^ e = Y 

D:
h[K