o
    _{j^ ã                   @   s   d dl Z d dlmZ d dlZd dlZd dlmZ ddlm	Z	 dd„ Z
e	 ¡ G dd	„ d	ƒƒZe	 ¡ G d
d„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G dd„ dƒƒZe	 ¡ G d d!„ d!ƒƒZe	 ¡ G d"d#„ d#ƒƒZe	 ¡ G d$d%„ d%ƒƒZe	 ¡ G d&d'„ d'ƒƒZe	 ¡ G d(d)„ d)ƒƒZe	 ¡ G d*d+„ d+ƒƒZe	 ¡ G d,d-„ d-ƒƒZe	 ¡ G d.d/„ d/ƒƒZdS )0é    N)ÚSequence)Ú_pairé   )Ú	PIPELINESc                 C   s¤   d| vr| d d j dd… | d< |rHd| vrF| d \}}tƒ }| d |d< tjdd||gtjd�|d	< d
|d< d|d< d|d< || d< dS dS d| vsPJ dƒ‚dS )ag  Initialize lazy operation properly.

    Make sure that a lazy operation is properly initialized,
    and avoid a non-lazy operation accidentally getting mixed in.

    Required keys in results are "imgs" if "img_shape" not in results,
    otherwise, Required keys in results are "img_shape", add or modified keys
    are "img_shape", "lazy".
    Add or modified keys in "lazy" are "original_shape", "crop_bbox", "flip",
    "flip_direction", "interpolation".

    Args:
        results (dict): A dict stores data pipeline result.
        lazy (bool): Determine whether to apply lazy operation. Default: False.
    Ú	img_shapeÚimgsr   Nr   ÚlazyÚoriginal_shape©ÚdtypeÚ	crop_bboxFÚflipÚflip_directionÚinterpolationzUse Fuse after lazy operations)ÚshapeÚdictÚnpÚarrayÚfloat32)Úresultsr   Úimg_hÚimg_wÚlazyop© r   ú?/root/disk_3tb/HAC/mmaction/datasets/pipelines/augmentations.pyÚ_init_lazy_if_proper   s    
ÿ÷r   c                   @   s8   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ ZdS )ÚImgauga  Imgaug augmentation.

    Adds custom transformations from imgaug library.
    Please visit `https://imgaug.readthedocs.io/en/latest/index.html`
    to get more information. Two demo configs could be found in tsn and i3d
    config folder.

    It's better to use uint8 images as inputs since imgaug works best with
    numpy dtype uint8 and isn't well tested with other dtypes. It should be
    noted that not all of the augmenters have the same input and output dtype,
    which may cause unexpected results.

    Required keys are "imgs", "img_shape"(if "gt_bboxes" is not None) and
    "modality", added or modified keys are "imgs", "img_shape", "gt_bboxes"
    and "proposals".

    It is worth mentioning that `Imgaug` will NOT create custom keys like
    "interpolation", "crop_bbox", "flip_direction", etc. So when using
    `Imgaug` along with other mmaction2 pipelines, we should pay more attention
    to required keys.

    Two steps to use `Imgaug` pipeline:
    1. Create initialization parameter `transforms`. There are three ways
        to create `transforms`.
        1) string: only support `default` for now.
            e.g. `transforms='default'`
        2) list[dict]: create a list of augmenters by a list of dicts, each
            dict corresponds to one augmenter. Every dict MUST contain a key
            named `type`. `type` should be a string(iaa.Augmenter's name) or
            an iaa.Augmenter subclass.
            e.g. `transforms=[dict(type='Rotate', rotate=(-20, 20))]`
            e.g. `transforms=[dict(type=iaa.Rotate, rotate=(-20, 20))]`
        3) iaa.Augmenter: create an imgaug.Augmenter object.
            e.g. `transforms=iaa.Rotate(rotate=(-20, 20))`
    2. Add `Imgaug` in dataset pipeline. It is recommended to insert imgaug
        pipeline before `Normalize`. A demo pipeline is listed as follows.
        ```
        pipeline = [
            dict(
                type='SampleFrames',
                clip_len=1,
                frame_interval=1,
                num_clips=16,
            ),
            dict(type='RawFrameDecode'),
            dict(type='Resize', scale=(-1, 256)),
            dict(
                type='MultiScaleCrop',
                input_size=224,
                scales=(1, 0.875, 0.75, 0.66),
                random_crop=False,
                max_wh_scale_gap=1,
                num_fixed_crops=13),
            dict(type='Resize', scale=(224, 224), keep_ratio=False),
            dict(type='Flip', flip_ratio=0.5),
            dict(type='Imgaug', transforms='default'),
            # dict(type='Imgaug', transforms=[
            #     dict(type='Rotate', rotate=(-20, 20))
            # ]),
            dict(type='Normalize', **img_norm_cfg),
            dict(type='FormatShape', input_format='NCHW'),
            dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
            dict(type='ToTensor', keys=['imgs', 'label'])
        ]
        ```

    Args:
        transforms (str | list[dict] | :obj:`iaa.Augmenter`): Three different
            ways to create imgaug augmenter.
    c                    sš   dd l m} |dkrˆ  ¡ ˆ _n%t|tƒr$tdd„ |D ƒƒs J ‚|ˆ _nt||jƒr1| ˆ _ˆ _nt	dƒ‚t||jƒsK| 
‡ fdd„ˆ jD ƒ¡ˆ _d S d S )Nr   Údefaultc                 s   ó   � | ]}t |tƒV  qd S ©N)Ú
isinstancer   )Ú.0Útransr   r   r   Ú	<genexpr>|   s   € z"Imgaug.__init__.<locals>.<genexpr>zGtransforms must be `default` or a list of dicts or iaa.Augmenter objectc                    ó   g | ]}ˆ   |¡‘qS r   ©Úimgaug_builder)r!   Út©Úselfr   r   Ú
<listcomp>†   s    z#Imgaug.__init__.<locals>.<listcomp>)Úimgaug.augmentersÚ
augmentersÚdefault_transformsÚ
transformsr    ÚlistÚallÚ	AugmenterÚaugÚ
ValueErrorÚ
Sequential)r)   r.   Úiaar   r(   r   Ú__init__v   s   

ÿÿzImgaug.__init__c                 C   st   t ddd�t ddt dt ddd	�t d
dd�t ddd�gd�t dt dddd�t ddddd�gd�t ddddd�gd�gS )zDefault transforms for imgaug.ÚRotate)iâÿÿÿé   )ÚtypeÚrotateZSomeOf)r   é   ZOneOfÚGaussianBlur)r   ç      à?)r9   ÚsigmaZAverageBlur)r   é   )r9   ÚkZ
MedianBlur)r;   é   )r9   ÚchildrenÚDropout)g{®Gáz„?çš™™™™™¹?r=   )r9   ÚpÚper_channelZCoarseDropout)g¸…ëQ¸ž?g333333Ã?)g{®Gáz”?gš™™™™™©?gš™™™™™É?)r9   rE   Zsize_percentrF   ZAdditiveGaussianNoiser   )ç        g     €)@)r9   ÚlocÚscalerF   )r9   ÚnrB   )r   r(   r   r   r   r-   ˆ   sD   



ýþþüüþüìýþzImgaug.default_transformsc                    sž   ddl m} t|tƒrd|v sJ ‚| ¡ }| d¡}t |¡r%t||ƒ}nt	||j
ƒr.|}n	tdt|ƒ› �ƒ‚d|v rH‡ fdd„|d D ƒ|d< |di |¤ŽS )	aO  Import a module from imgaug.

        It follows the logic of :func:`build_from_cfg`. Use a dict object to
        create an iaa.Augmenter object.

        Args:
            cfg (dict): Config dict. It should at least contain the key "type".

        Returns:
            obj:`iaa.Augmenter`: The constructed imgaug augmenter.
        r   Nr9   z*type must be a str or valid type, but got rB   c                    r$   r   r%   )r!   Úchildr(   r   r   r*   Ç   ó    
ÿz)Imgaug.imgaug_builder.<locals>.<listcomp>r   )r+   r,   r    r   ÚcopyÚpopÚmmcvÚis_strÚgetattrÚ
issubclassr1   Ú	TypeErrorr9   )r)   Úcfgr5   ÚargsÚobj_typeÚobj_clsr   r(   r   r&   ¬   s    

ÿ

ÿzImgaug.imgaug_builderc                 C   s   | j jd| j› d� }|S )Nz(transforms=ú))Ú	__class__Ú__name__r2   ©r)   Úrepr_strr   r   r   Ú__repr__Í   ó   zImgaug.__repr__c                    s\  |d dks
J dƒ‚|d d j j}| j ¡ ‰‡fdd„|d D ƒ|d< |d d j\‰‰}|d d j j}||ksFJ dd	|› d
|› �fƒ‚d|v r¦ddlm‰  ‡ fdd„|d D ƒ}ˆ j||d d�}ˆ |g¡^}}‡‡fdd„|j	D ƒ|d< d|v r¦‡ fdd„|d D ƒ}ˆ j||d d�}ˆ |g¡^}}‡‡fdd„|j	D ƒ|d< ˆˆf|d< |S )NÚmodalityÚRGBzImgaug only support RGB images.r   r   c                    r$   r   )Zaugment_image)r!   Úframe)Úcur_augr   r   r*   ×   rL   z#Imgaug.__call__.<locals>.<listcomp>z6Imgaug input dtype and output dtype are not the same. zConvert from z to Ú	gt_bboxes©Úbbsc                    ó.   g | ]}ˆ j |d  |d |d |d d�‘qS ©r   é   r   r;   )Úx1Úy1Úx2Úy2©ZBoundingBox©r!   Úbboxrd   r   r   r*   ã   ó    þÿÿr   )r   c                    ó8   g | ]}t |jd ƒt |jd ƒt|jˆƒt|jˆ ƒg‘qS ©r   ©Úmaxri   rj   Úminrk   rl   rn   ©r   r   r   r   r*   ë   ó    
ü


üÚ	proposalsc                    rf   rg   rm   rn   rd   r   r   r*   ò   rp   c                    rq   rr   rs   rn   rv   r   r   r*   ú   rw   )
r   r9   r2   Zto_deterministicr   Zimgaug.augmentablesre   ZBoundingBoxesOnImageZaugment_bounding_boxesÚitems)r)   r   Zin_typeÚ_Úout_typeZ	bbox_listÚbboxesZbbox_augr   )re   rb   r   r   r   Ú__call__Ñ   sL   


ÿ
ÿÿ
ýÿ
û
ýÿ
ûzImgaug.__call__N)	rZ   Ú
__module__Ú__qualname__Ú__doc__r6   r-   r&   r]   r}   r   r   r   r   r   -   s    G$!r   c                   @   s   e Zd ZdZdd„ ZdS )ÚFusea  Fuse lazy operations.

    Fusion order:
        crop -> resize -> flip

    Required keys are "imgs", "img_shape" and "lazy", added or modified keys
    are "imgs", "lazy".
    Required keys in "lazy" are "crop_bbox", "interpolation", "flip_direction".
    c                    sÂ   d|vrt dƒ‚|d }|d }|d  ¡  t¡\‰‰‰‰ ‡ ‡‡‡fdd„|D ƒ}|d \‰‰|d d u r8d	‰n|d ‰‡‡‡fd
d„|D ƒ}|d rX|D ]
}t ||d ¡ qM||d< |d= |S )Nr   zNo lazy operation detectedr   r   c                    ó    g | ]}|ˆˆ …ˆˆ…f ‘qS r   r   ©r!   Úimg©ÚbottomÚleftÚrightÚtopr   r   r*     s     z!Fuse.__call__.<locals>.<listcomp>r   r   Úbilinearc                    s    g | ]}t j|ˆˆ fˆd �‘qS ©)r   )rO   Úimresizerƒ   )r   r   r   r   r   r*   "  s    ÿÿr   r   )r3   ÚroundÚastypeÚintrO   Úimflip_)r)   r   r   r   r„   r   )r†   r   r   r   r‡   rˆ   r‰   r   r}     s&   þzFuse.__call__N)rZ   r~   r   r€   r}   r   r   r   r   r�     s    
r�   c                   @   s2   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ ZdS )ÚRandomScalea  Resize images by a random scale.

    Required keys are "imgs", "img_shape", "modality", added or modified
    keys are "imgs", "img_shape", "keep_ratio", "scale_factor", "lazy",
    "scale", "resize_size". Required keys in "lazy" is None, added or
    modified key is "interpolation".

    Args:
        scales (tuple[int]): Tuple of scales to be chosen for resize.
        mode (str): Selection mode for choosing the scale. Options are "range"
            and "value". If set to "range", The short edge will be randomly
            chosen from the range of minimum and maximum on the shorter one
            in all tuples. Otherwise, the longer edge will be randomly chosen
            from the range of minimum and maximum on the longer one in all
            tuples. Default: 'range'.
    Úrangec                 K   s0   || _ | j dvrtd| j › �ƒ‚|| _|| _d S )N)r’   Úvaluez+mode should be 'range' or 'value', but got )Úmoder3   ÚscalesÚkwargs)r)   r•   r”   r–   r   r   r   r6   E  s   
ÿ
zRandomScale.__init__c                 C   sÂ   t |ƒ}|dkr|d }|S |dkrQ| jdkrEdd„ |D ƒ}dd„ |D ƒ}tj t|ƒt|ƒd ¡}tj t|ƒt|ƒd ¡}||f}|S | jdkrOt |¡}|S | jdkrZtd	ƒ‚t |¡}|S )
Nrh   r   r   r’   c                 S   ó   g | ]}t |ƒ‘qS r   )rt   ©r!   Úsr   r   r   r*   T  ó    z,RandomScale.select_scale.<locals>.<listcomp>c                 S   r—   r   )ru   r˜   r   r   r   r*   U  rš   r“   z3Only 'value' mode supports more than 2 image scales)	Úlenr”   r   ÚrandomÚrandintru   rt   Úchoicer3   )r)   r•   Z
num_scalesrI   Z
scale_longZscale_shortZ	long_edgeÚ
short_edger   r   r   Úselect_scaleM  s2   í

þ
þ	
ø

û
zRandomScale.select_scalec                 C   s2   |   | j¡}||d< t|fi | j¤Ž}||ƒ}|S )NrI   )r    r•   ÚResizer–   )r)   r   rI   Úresizer   r   r   r}   g  s
   zRandomScale.__call__c                 C   ó"   | j j› d| j› d| j› d�}|S )Nz(scales=z, mode=rX   )rY   rZ   r•   r”   r[   r   r   r   r]   n  s   
ÿÿzRandomScale.__repr__N)r’   )rZ   r~   r   r€   r6   r    r}   r]   r   r   r   r   r‘   2  s    
r‘   c                   @   ó(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	ÚEntityBoxRescaleaR  Rescale the entity box and proposals according to the image shape.

    Required keys are "proposals", "gt_bboxes", added or modified keys are
    "gt_bboxes". If original "proposals" is not None, "proposals" and
    will be added or modified.

    Args:
        scale_factor (np.ndarray): The scale factor used entity_box rescaling.
    c                 C   ó
   || _ d S r   )Úscale_factor)r)   r§   r   r   r   r6   ‚  ó   
zEntityBoxRescale.__init__c                 C   sd   t  | j| jg¡}|d }|d }|| |d< |d ur0|jd dks*J d|j› �ƒ‚|| |d< |S )Nrx   rc   rh   é   z-proposals shape should be in (n, 4), but got )r   Úconcatenater§   r   )r)   r   r§   rx   rc   r   r   r   r}   …  s   ÿÿzEntityBoxRescale.__call__c                 C   ó   | j j› d| j› d�S )Nz(scale_factor=rX   )rY   rZ   r§   r(   r   r   r   r]   ”  ó   zEntityBoxRescale.__repr__N©rZ   r~   r   r€   r6   r}   r]   r   r   r   r   r¥   v  s
    
r¥   c                   @   r¤   )	ÚEntityBoxCropaH  Crop the entity boxes and proposals according to the cropped images.

    Required keys are "proposals", "gt_bboxes", added or modified keys are
    "gt_bboxes". If original "proposals" is not None, "proposals" will be
    modified.

    Args:
        crop_bbox(np.ndarray | None): The bbox used to crop the original image.
    c                 C   r¦   r   )r   )r)   r   r   r   r   r6   ¤  r¨   zEntityBoxCrop.__init__c                 C   sV  |d }|d }| j d u r|S | j \}}}}|| || }}	|jd dks(J ‚| ¡ }
t |ddd d…f | d|d ¡|
ddd d…f< t |ddd d…f | d|	d ¡|
ddd d…f< |
|d< |d ur©|jd dksoJ ‚| ¡ }t |ddd d…f | d|d ¡|ddd d…f< t |ddd d…f | d|	d ¡|ddd d…f< ||d< |S )	Nrx   rc   éÿÿÿÿr©   .r   r   rh   )r   r   rM   r   Úclip)r)   r   rx   rc   ri   rj   rk   rl   r   r   Ú
gt_bboxes_Ú
proposals_r   r   r   r}   §  s4   
ÿÿÿÿzEntityBoxCrop.__call__c                 C   r«   )Nz(crop_bbox=rX   )rY   rZ   r   r(   r   r   r   r]   Ã  r¬   zEntityBoxCrop.__repr__Nr­   r   r   r   r   r®   ˜  s
    
r®   c                   @   r¤   )	ÚEntityBoxFlipa  Flip the entity boxes and proposals with a probability.

    Reverse the order of elements in the given bounding boxes and proposals
    with a specific direction. The shape of them are preserved, but the
    elements are reordered. Only the horizontal flip is supported (seems
    vertical flipping makes no sense). Required keys are "proposals",
    "gt_bboxes", added or modified keys are "gt_bboxes". If "proposals"
    is not None, it will also be modified.

    Args:
        img_shape (tuple[int]): The img shape.
    c                 C   s   || _ t |t¡sJ ‚d S r   )r   rO   Úis_tuple_ofr�   )r)   r   r   r   r   r6   Ö  s   zEntityBoxFlip.__init__c                 C   s  |d }|d }| j \}}|jd dksJ ‚| ¡ }||ddd d…f  d |ddd d…f< ||ddd d…f  d |ddd d…f< |d ur||jd dksOJ ‚| ¡ }||ddd d…f  d |ddd d…f< ||ddd d…f  d |ddd d…f< nd }||d< ||d< |S )	Nrx   rc   r¯   r©   .r   rh   r   )r   r   rM   )r)   r   rx   rc   r   r   r±   r²   r   r   r   r}   Ú  s    
(((*zEntityBoxFlip.__call__c                 C   ó   | j j› d| j› d�}|S )Nz(img_shape=rX   )rY   rZ   r   r[   r   r   r   r]   ï  r^   zEntityBoxFlip.__repr__Nr­   r   r   r   r   r³   Ç  s
    r³   c                   @   ó*   e Zd ZdZd
dd„Zdd„ Zdd„ Zd	S )Ú
RandomCropa‘  Vanilla square random crop that specifics the output size.

    Required keys in results are "imgs" and "img_shape", added or
    modified keys are "imgs", "lazy"; Required keys in "lazy" are "flip",
    "crop_bbox", added or modified key is "crop_bbox".

    Args:
        size (int): The output size of the images.
        lazy (bool): Determine whether to apply lazy operation. Default: False.
    Fc                 C   s,   t |tƒstdt|ƒ› �ƒ‚|| _|| _d S )NzSize must be an int, but got )r    r�   rS   r9   Úsizer   )r)   r¸   r   r   r   r   r6     s   

zRandomCrop.__init__c                    sR  t || jƒ |d \}}| j|kr| j|ksJ ‚d‰d‰|| jkr-ttj d|| j ¡ƒ‰|| jkr>ttj d|| j ¡ƒ‰d|vrNtjg d¢tjd�|d< ˆ| ˆ| }}| j| | j| }}|d }|d |d }	}
|d |d }}|	||  |
||  || ||	 g}tj|tjd�|d< | j| j‰ ‰t ˆˆˆˆ ˆˆ  g¡|d	< ˆ ˆf|d< | jsÄ‡ ‡‡‡fd
d„|d D ƒ|d< nN|d }|d rÐt	dƒ‚|d	 \}}}}ˆ||  | }ˆˆ ||  | }ˆ||  | }ˆˆ  ||  | }tj|| || || || gtjd�|d	< d|v �r'| j�rJ ‚t
|d	 ƒ}||ƒ}|S )z¹Performs the RandomCrop augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r   r   Úcrop_quadruple©r   r   rh   rh   r
   rh   r   r;   r   c                    ó(   g | ]}|ˆˆˆ  …ˆˆˆ …f ‘qS r   r   rƒ   ©Únew_hÚnew_wÚx_offsetÚy_offsetr   r   r*   5  ó    ÿÿz'RandomCrop.__call__.<locals>.<listcomp>r   r   r   úPut Flip at last for nowrc   )r   r   r¸   r�   r   rœ   r�   r   r   ÚNotImplementedErrorr®   )r)   r   r   r   Úx_ratioÚy_ratioÚw_ratioÚh_ratioÚold_crop_quadrupleÚold_x_ratioÚold_y_ratioÚold_w_ratioÚold_h_ratioÚnew_crop_quadrupler   Ú	lazy_leftÚlazy_topÚ
lazy_rightÚlazy_bottomr‡   rˆ   r‰   r†   Úentity_box_cropr   r¼   r   r}     sn   


þ
ý
ÿÿþ
ý
ü
zRandomCrop.__call__c                 C   r£   )Nz(size=ú, lazy=rX   )rY   rZ   r¸   r   r[   r   r   r   r]   R  ó   ÿzRandomCrop.__repr__N©Fr­   r   r   r   r   r·   ô  s
    
Kr·   c                   @   s@   e Zd ZdZ			ddd„Ze	ddd	„ƒZd
d„ Zdd„ ZdS )ÚRandomResizedCropa•  Random crop that specifics the area and height-weight ratio range.

    Required keys in results are "imgs", "img_shape", "crop_bbox" and "lazy",
    added or modified keys are "imgs", "crop_bbox" and "lazy"; Required keys
    in "lazy" are "flip", "crop_bbox", added or modified key is "crop_bbox".

    Args:
        area_range (Tuple[float]): The candidate area scales range of
            output cropped images. Default: (0.08, 1.0).
        aspect_ratio_range (Tuple[float]): The candidate aspect ratio range of
            output cropped images. Default: (3 / 4, 4 / 3).
        lazy (bool): Determine whether to apply lazy operation. Default: False.
    ©g{®Gáz´?ç      ð?©g      è?gUUUUUUõ?Fc                 C   sV   || _ || _|| _t | j t¡stdt|ƒ› �ƒ‚t | jt¡s)tdt|ƒ› �ƒ‚d S )Nz-Area_range must be a tuple of float, but got z5Aspect_ratio_range must be a tuple of float, but got )Ú
area_rangeÚaspect_ratio_ranger   rO   r´   ÚfloatrS   r9   )r)   rÚ   rÛ   r   r   r   r   r6   h  s   ÿÿÿzRandomResizedCrop.__init__é
   c                 C   sx  d|d   k r|d   krdksJ ‚ J ‚d|d   k r&|d ks)J ‚ J ‚| \}}|| }|\}}t  t jjt  |¡t  |¡|d�¡}	t jj|d|iŽ| }
t  t  |
|	 ¡¡ t j¡}t  t  |
|	 ¡¡ t j¡}t	|ƒD ].}|| }|| }||kr ||kr t 
d|| ¡}t 
d|| ¡}|||| || f  S qrt||ƒ}|| d }|| d }|||| || fS )a  Get a crop bbox given the area range and aspect ratio range.

        Args:
            img_shape (Tuple[int]): Image shape
            area_range (Tuple[float]): The candidate area scales range of
                output cropped images. Default: (0.08, 1.0).
            aspect_ratio_range (Tuple[float]): The candidate aspect
                ratio range of output cropped images. Default: (3 / 4, 4 / 3).
                max_attempts (int): The maximum of attempts. Default: 10.
            max_attempts (int): Max attempts times to generate random candidate
                bounding box. If it doesn't qualified one, the center bounding
                box will be used.
        Returns:
            (list[int]) A random crop bbox within the area range and aspect
            ratio range.
        r   rh   ©r¸   r¸   r   )r   Úexprœ   ÚuniformÚlogr�   ÚsqrtrŽ   Úint32r’   r�   ru   )r   rÚ   rÛ   Zmax_attemptsr   r   ÚareaZmin_arZmax_arÚaspect_ratiosZtarget_areasZcandidate_crop_wZcandidate_crop_hÚiÚcrop_wÚcrop_hr¿   rÀ   Ú	crop_sizer   r   r   Úget_crop_bboxv  sB   .$ÿÿ
ÿÿ
ÿÿ€
zRandomResizedCrop.get_crop_bboxc                    sø  t || jƒ |d \}}|  ||f| j| j¡\‰‰‰‰ ˆ ˆ ˆˆ }}d|vr4tjg d¢tjd�|d< ˆ| ˆ| }}|| || }}	|d }
|
d |
d }}|
d |
d }}|||  |||  || |	| g}tj|tjd�|d< t ˆˆˆˆ g¡|d	< ||f|d< | js�‡ ‡‡‡fd
d„|d D ƒ|d< nJ|d }|d r©tdƒ‚|d	 \}}}}ˆ||  | ‰ˆ||  | ‰ˆ||  | ‰ˆ ||  | ‰ tj|ˆ |ˆ |ˆ |ˆ  gtjd�|d	< d|v rú| jrðJ ‚t	|d	 ƒ}||ƒ}|S )z¿Performs the RandomResizeCrop augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r   r¹   rº   r
   r   rh   r   r;   r   c                    r‚   r   r   rƒ   r…   r   r   r*   Ï  ó    ÿz.RandomResizedCrop.__call__.<locals>.<listcomp>r   r   r   rÂ   rc   )
r   r   rê   rÚ   rÛ   r   r   r   rÃ   r®   )r)   r   r   r   r½   r¾   rÄ   rÅ   rÆ   rÇ   rÈ   rÉ   rÊ   rË   rÌ   rÍ   r   rÎ   rÏ   rÐ   rÑ   rÒ   r   r…   r   r}   ©  sb   ÿ
þ
ý
ÿÿ
ý
ü
zRandomResizedCrop.__call__c                 C   s*   | j j› d| j› d| j› d| j› d�}|S )Nz(area_range=z, aspect_ratio_range=rÓ   rX   )rY   rZ   rÚ   rÛ   r   r[   r   r   r   r]   é  s   
ÿþýzRandomResizedCrop.__repr__N)r×   rÙ   F)rÝ   )	rZ   r~   r   r€   r6   Ústaticmethodrê   r}   r]   r   r   r   r   rÖ   X  s    
ýý2@rÖ   c                   @   s4   e Zd ZdZ					ddd„Zdd	„ Zd
d„ ZdS )ÚMultiScaleCropaå  Crop images with a list of randomly selected scales.

    Randomly select the w and h scales from a list of scales. Scale of 1 means
    the base size, which is the minimal of image weight and height. The scale
    level of w and h is controlled to be smaller than a certain value to
    prevent too large or small aspect ratio.
    Required keys are "imgs", "img_shape", added or modified keys are "imgs",
    "crop_bbox", "img_shape", "lazy" and "scales". Required keys in "lazy" are
    "crop_bbox", added or modified key is "crop_bbox".

    Args:
        input_size (int | tuple[int]): (w, h) of network input.
        scales (tuple[float]): Weight and height scales to be selected.
        max_wh_scale_gap (int): Maximum gap of w and h scale levels.
            Default: 1.
        random_crop (bool): If set to True, the cropping bbox will be randomly
            sampled, otherwise it will be sampler from fixed regions.
            Default: False.
        num_fixed_crops (int): If set to 5, the cropping bbox will keep 5
            basic fixed regions: "upper left", "upper right", "lower left",
            "lower right", "center". If set to 13, the cropping bbox will
            append another 8 fix regions: "center left", "center right",
            "lower center", "upper center", "upper left quarter",
            "upper right quarter", "lower left quarter", "lower right quarter".
            Default: 5.
        lazy (bool): Determine whether to apply lazy operation. Default: False.
    ©rh   rh   Fé   c                 C   sˆ   t |ƒ| _t | jt¡stdt|ƒ› �ƒ‚t|tƒs#tdt|ƒ› �ƒ‚|dvr3t	dddg› d|› �ƒ‚|| _
|| _|| _|| _|| _d S )Nz0Input_size must be int or tuple of int, but got zScales must be tuple, but got )rï   é   zNum_fix_crops must be in rï   rð   z
, but got )r   Ú
input_sizerO   r´   r�   rS   r9   r    Útupler3   r•   Úmax_wh_scale_gapÚrandom_cropÚnum_fixed_cropsr   )r)   rñ   r•   ró   rô   rõ   r   r   r   r   r6     s    
ÿ
ÿ
zMultiScaleCrop.__init__c           %   
      s¬  t || jƒ |d \}}t||ƒ‰ ‡ fdd„| jD ƒ}g }t|ƒD ]\}}t|ƒD ]\}}	t|| ƒ| jkr=| |	|g¡ q)q!t 	|¡}
t
dƒD ]}t|
| | j|  ƒdk r^| j| |
|< qH|
\}}| jrwt d|| ¡‰t d|| ¡‰np|| d }|| d }dd| dfdd| fd| d| fd| d| fg}| jd	kràdd| fd| d| fd| d| fd| d| fd
| d
| fd| d
| fd
| d| fd| d| fg}| |¡ t 	|¡\‰‰||‰‰t ˆˆˆˆ ˆˆ g¡|d< ˆˆf|d< | j|d< d|v�rtjg d¢tjd�|d< ˆ| ˆ| }}ˆ| ˆ| }}|d }|d |d
 }}|d |d }}|||  |||  || || g}tj|tjd�|d< | j�sp‡‡‡‡fdd„|d D ƒ|d< nO|d }|d �r}tdƒ‚|d \}}}}ˆ||  | } ˆˆ ||  | }!ˆ||  | }"ˆˆ ||  | }#tj||  ||" ||! ||# gtjd�|d< d|v �rÔ| j�rÊJ ‚t|d ƒ}$|$|ƒ}|S )z½Performs the MultiScaleCrop augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r   c                    s   g | ]}t ˆ | ƒ‘qS r   )r�   r˜   )Ú	base_sizer   r   r*   3  s    z+MultiScaleCrop.__call__.<locals>.<listcomp>r   r;   r   r©   ©r   r   rð   rh   r   r•   r¹   rº   r
   c                    r»   r   r   rƒ   r¼   r   r   r*   x  rÁ   r   r   r   rÂ   rc   )r   r   ru   r•   Ú	enumerateÚabsró   Úappendrœ   rž   r’   rñ   rô   r�   rõ   Úextendr   r   r   rÃ   r®   )%r)   r   r   r   Z
crop_sizesZcandidate_sizesræ   ÚhÚjÚwré   rç   rè   Úw_stepÚh_stepZcandidate_offsetsZextra_candidate_offsetsrÄ   rÅ   rÆ   rÇ   rÈ   rÉ   rÊ   rË   rÌ   rÍ   r   rÎ   rÏ   rÐ   rÑ   r‡   rˆ   r‰   r†   rÒ   r   )rö   r½   r¾   r¿   rÀ   r   r}   (  s®   
€þ
€

û

ø


ÿ


þ
ý
ÿþ

ý
ü
zMultiScaleCrop.__call__c                 C   sB   | j j› d| j› d| j› d| j› d| j› d| j› d| j› d�}|S )Nz(input_size=z	, scales=z, max_wh_scale_gap=z, random_crop=z, num_fixed_crops=rÓ   rX   )rY   rZ   rñ   r•   ró   rô   rõ   r   r[   r   r   r   r]   ”  s   
ÿÿþýüûzMultiScaleCrop.__repr__N)rî   rh   Frï   Fr­   r   r   r   r   rí   ñ  s    
úlrí   c                   @   s0   e Zd ZdZ			ddd„Zdd„ Zd	d
„ ZdS )r¡   a)  Resize images to a specific size.

    Required keys are "imgs", "img_shape", "modality", added or modified
    keys are "imgs", "img_shape", "keep_ratio", "scale_factor", "lazy",
    "resize_size". Required keys in "lazy" is None, added or modified key is
    "interpolation".

    Args:
        scale (float | Tuple[int]): If keep_ratio is True, it serves as scaling
            factor or maximum size:
            If it is a float number, the image will be rescaled by this
            factor, else if it is a tuple of 2 integers, the image will
            be rescaled as large as possible within the scale.
            Otherwise, it serves as (w, h) of output size.
        keep_ratio (bool): If set to True, Images will be resized without
            changing the aspect ratio. Otherwise, it will resize images to a
            given size. Default: True.
        interpolation (str): Algorithm used for interpolation:
            "nearest" | "bilinear". Default: "bilinear".
        lazy (bool): Determine whether to apply lazy operation. Default: False.
    TrŠ   Fc                 C   s€   t |tƒr|dkrtd|› d�ƒ‚n t |tƒr)t|ƒ}t|ƒ}|dkr(tj|f}n	tdt	|ƒ› �ƒ‚|| _
|| _|| _|| _d S )Nr   zInvalid scale z, must be positive.r¯   z-Scale must be float or tuple of int, but got )r    rÜ   r3   rò   rt   ru   r   ÚinfrS   r9   rI   Ú
keep_ratior   r   )r)   rI   r  r   r   Úmax_long_edgeÚmax_short_edger   r   r   r6   ¶  s"   
ÿ

€ÿ
zResize.__init__c                    s  t |ˆjƒ d|vrtjddgtjd�|d< |d \}}ˆjr+t ||fˆj¡\‰‰ nˆj\‰‰ tjˆ| ˆ | gtjd�ˆ_	ˆ ˆf|d< ˆj|d< |d ˆj	 |d< ˆjsf‡ ‡‡fdd„|d D ƒ|d< n|d	 }|d
 rrt
dƒ‚ˆj|d< d|v r‰ˆjr€J ‚tˆj	ƒ}||ƒ}|S )úµPerforms the Resize augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r§   rh   r
   r   r  c                    s"   g | ]}t j|ˆˆ fˆjd �‘qS r‹   )rO   rŒ   r   rƒ   ©r½   r¾   r)   r   r   r*   ç  s    þÿÿz#Resize.__call__.<locals>.<listcomp>r   r   r   rÂ   r   rc   )r   r   r   r   r   r  rO   Úrescale_sizerI   r§   rÃ   r   r¥   )r)   r   r   r   r   Zentity_box_rescaler   r  r   r}   Ì  s4   
ÿ
ý


zResize.__call__c              
   C   ó2   | j j› d| j› d| j› d| j› d| j› d�
}|S )Nz(scale=z, keep_ratio=z, interpolation=rÓ   rX   )rY   rZ   rI   r  r   r   r[   r   r   r   r]   ù  s   
ÿÿþýzResize.__repr__N)TrŠ   Fr­   r   r   r   r   r¡   ž  s    
ü-r¡   c                   @   r¶   )ÚRandomRescalea"  Randomly resize images so that the short_edge is resized to a specific
    size in a given range. The scale ratio is unchanged after resizing.

    Required keys are "imgs", "img_shape", "modality", added or modified
    keys are "imgs", "img_shape", "keep_ratio", "scale_factor", "resize_size",
    "short_edge".

    Args:
        scale_range (tuple[int]): The range of short edge length. A closed
            interval.
        interpolation (str): Algorithm used for interpolation:
            "nearest" | "bilinear". Default: "bilinear".
    rŠ   c                 C   sb   || _ t |t¡sJ ‚t|ƒdksJ ‚|d |d k sJ ‚t dd„ |D ƒ¡s)J ‚d| _|| _d S )Nr   r   rh   c                 S   s   g | ]}|d k‘qS rr   r   ©r!   Úxr   r   r   r*     rš   z*RandomRescale.__init__.<locals>.<listcomp>T)	Úscale_rangerO   r´   r�   r›   r   r0   r  r   )r)   r  r   r   r   r   r6     s   
zRandomRescale.__init__c                 C   sH   t j | jd | jd d ¡}td|fd| jdd�}||ƒ}||d< |S )r  r   rh   r¯   TF)r  r   r   rŸ   )r   rœ   r�   r  r¡   r   )r)   r   rŸ   r¢   r   r   r   r}     s   ÿýzRandomRescale.__call__c                 C   s4   | j }| jj› d|d › d|d › d| j› d�}|S )Nz(scale_range=(r   z, rh   z), interpolation=rX   )r  rY   rZ   r   )r)   r  r\   r   r   r   r]   .  s   
ÿÿþzRandomRescale.__repr__N)rŠ   r­   r   r   r   r   r	    s
    
r	  c                   @   s:   e Zd ZdZddgZ				ddd„Zd	d
„ Zdd„ ZdS )ÚFlipaë  Flip the input images with a probability.

    Reverse the order of elements in the given imgs with a specific direction.
    The shape of the imgs is preserved, but the elements are reordered.
    Required keys are "imgs", "img_shape", "modality", added or modified
    keys are "imgs", "lazy" and "flip_direction". Required keys in "lazy" is
    None, added or modified key are "flip" and "flip_direction". The Flip
    augmentation should be placed after any cropping / reshaping augmentations,
    to make sure crop_quadruple is calculated properly.

    Args:
        flip_ratio (float): Probability of implementing flip. Default: 0.5.
        direction (str): Flip imgs horizontally or vertically. Options are
            "horizontal" | "vertical". Default: "horizontal".
        flip_label_map (Dict[int, int] | None): Transform the label of the
            flipped image with the specific label. Default: None.
        lazy (bool): Determine whether to apply lazy operation. Default: False.
    Ú
horizontalÚverticalr=   NFc                 C   s<   || j vrtd|› d| j › �ƒ‚|| _|| _|| _|| _d S )Nz
Direction z. is not supported. Currently support ones are )Ú_directionsr3   Ú
flip_ratioÚ	directionÚflip_label_mapr   )r)   r  r  r  r   r   r   r   r6   L  s   

ÿ
zFlip.__init__c           	      C   sX  t || jƒ |d }|dkr| jdksJ ‚tj ¡ | jk }||d< | j|d< | jdur:|r:| j |d |d ¡|d< | js{|rrt	|d ƒD ]\}}t
 || j¡ qEt|d ƒ}td	|d
ƒD ]}|dkrpt
 |d | ¡|d |< q]nt|d ƒ|d< n|d }|d r‡tdƒ‚||d< | j|d< d|v rª|rª| jsž| jdks J ‚t|d ƒ}||ƒ}|S )z³Performs the Flip augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r_   ÚFlowr  r   r   NÚlabelr   r   r   r   zUse one Flip pleaserc   r   )r   r   r  r   rœ   Úrandr  r  Úgetrø   rO   r�   r›   r’   Úiminvertr/   rÃ   r³   )	r)   r   r_   r   ræ   r„   Últr   Zentity_box_flipr   r   r   r}   Y  s@   
ÿ€ü
zFlip.__call__c              
   C   r  )Nz(flip_ratio=z, direction=z, flip_label_map=rÓ   rX   )rY   rZ   r  r  r  r   r[   r   r   r   r]   ‰  s   
ÿÿþþÿzFlip.__repr__)r=   r  NF)rZ   r~   r   r€   r  r6   r}   r]   r   r   r   r   r  6  s    
ü0r  c                   @   r¶   )Ú	Normalizeau  Normalize images with the given mean and std value.

    Required keys are "imgs", "img_shape", "modality", added or modified
    keys are "imgs" and "img_norm_cfg". If modality is 'Flow', additional
    keys "scale_factor" is required

    Args:
        mean (Sequence[float]): Mean values of different channels.
        std (Sequence[float]): Std values of different channels.
        to_bgr (bool): Whether to convert channels from RGB to BGR.
            Default: False.
        adjust_magnitude (bool): Indicate whether to adjust the flow magnitude
            on 'scale_factor' when modality is 'Flow'. Default: False.
    Fc                 C   sl   t |tƒstdt|ƒ› �ƒ‚t |tƒstdt|ƒ› �ƒ‚tj|tjd�| _tj|tjd�| _|| _	|| _
d S )Nz0Mean must be list, tuple or np.ndarray, but got z/Std must be list, tuple or np.ndarray, but got r
   )r    r   rS   r9   r   r   r   ÚmeanÚstdÚto_bgrÚadjust_magnitude)r)   r  r  r  r  r   r   r   r6   ¢  s   
ÿ
ÿ
zNormalize.__init__c                 C   s  |d }|dkrUt |d ƒ}|d d j\}}}tj||||ftjd�}t|d ƒD ]\}}	|	||< q*|D ]}	t |	| j| j	| j
¡ q5||d< t| j| j	| j
d�|d< |S |dk�rt |d ƒ}
|
d	 dkshJ ‚| jjd d	ksrJ ‚| j	jd d	ks|J ‚|
d	 }|d d j\}}tj|||ftjd�}tj|||ftjd�}t|ƒD ]}|d d	|  ||< |d d	| d
  ||< q£|| jd  | j	d  }|| jd
  | j	d
  }| jrç||d d  }||d d
  }tj||gdd�}||d< t| j| j	| j
| jd�}||d< |S t‚)Nr_   r`   r   r   r
   )r  r  r  Úimg_norm_cfgr  r   rh   r§   r¯   ©Úaxis)r  r  r  r  )r›   r   r   Úemptyr   rø   rO   Úimnormalize_r  r  r  r   r’   r  ÚstackrÃ   )r)   r   r_   rJ   rü   rþ   Úcr   ræ   r„   Únum_imgsZx_flowZy_flowrU   r   r   r   r}   ±  sT   

ÿ
üzNormalize.__call__c              
   C   r  )Nz(mean=z, std=z	, to_bgr=z, adjust_magnitude=rX   )rY   rZ   r  r  r  r  r[   r   r   r   r]   Þ  ó   
ÿþýüzNormalize.__repr__N)FFr­   r   r   r   r   r  ‘  s
    
-r  c                   @   sb   e Zd ZdZ				ddd„Zedd„ ƒZed	d
„ ƒZedd„ ƒZedd„ ƒZ	dd„ Z
dd„ ZdS )ÚColorJittera8  Randomly distort the brightness, contrast, saturation and hue of images,
    and add PCA based noise into images.

    Note: The input images should be in RGB channel order.

    Code Reference:
    https://gluon-cv.mxnet.io/_modules/gluoncv/data/transforms/experimental/image.html
    https://mxnet.apache.org/api/python/docs/_modules/mxnet/image/image.html#LightingAug

    If specified to apply color space augmentation, it will distort the image
    color space by changing brightness, contrast and saturation. Then, it will
    add some random distort to the images in different color channels.
    Note that the input images should be in original range [0, 255] and in RGB
    channel sequence.

    Required keys are "imgs", added or modified keys are "imgs", "eig_val",
    "eig_vec", "alpha_std" and "color_space_aug".

    Args:
        color_space_aug (bool): Whether to apply color space augmentations. If
            specified, it will change the brightness, contrast, saturation and
            hue of images, then add PCA based noise to images. Otherwise, it
            will directly add PCA based noise to images. Default: False.
        alpha_std (float): Std in the normal Gaussian distribution of alpha.
        eig_val (np.ndarray | None): Eigenvalues of [1 x 3] size for RGB
            channel jitter. If set to None, it will use the default
            eigenvalues. Default: None.
        eig_vec (np.ndarray | None): Eigenvectors of [3 x 3] size for RGB
            channel jitter. If set to None, it will use the default
            eigenvectors. Default: None.
    FrD   Nc                 C   sj   |d u rt jg d¢t jd�| _n|| _|d u r*t jg d¢g d¢g d¢gt jd�| _n|| _|| _|| _d S )N)g{®GáºK@g“V-@g‘í|?5^ò?r
   )g)\�Âõ(â¿gùé·¯ç?gÙ=yX¨Ù?)g ‰°áé•â¿g;ßO�—nr¿g?5^ºIê¿)g[B>èÙ¬â¿gyX¨5Í;æ¿g.� ø1æÚ?)r   r   r   Úeig_valÚeig_vecÚ	alpha_stdÚcolor_space_aug)r)   r,  r+  r)  r*  r   r   r   r6   	  s   
þ
ý
zColorJitter.__init__c                 C   s    t j ¡ dkr| t  |¡ } | S )a  Brightness distortion.

        Args:
            img (np.ndarray): An input image.
            delta (float): Delta value to distort brightness.
                It ranges from [-32, 32).

        Returns:
            np.ndarray: A brightness distorted image.
        r=   ©r   rœ   r  r   )r„   Údeltar   r   r   Ú
brightness  ó   zColorJitter.brightnessc                 C   s    t j ¡ dkr| t  |¡ } | S )a  Contrast distortion.

        Args:
            img (np.ndarray): An input image.
            alpha (float): Alpha value to distort contrast.
                It ranges from [0.6, 1.4).

        Returns:
            np.ndarray: A contrast distorted image.
        r=   r-  )r„   Úalphar   r   r   Úcontrast/  r0  zColorJitter.contrastc                 C   sV   t j ¡ dkr)| t jg d¢t jd� }t j|ddd�}|d| 9 }| | } | | } | S )a  Saturation distortion.

        Args:
            img (np.ndarray): An input image.
            alpha (float): Alpha value to distort the saturation.
                It ranges from [0.6, 1.4).

        Returns:
            np.ndarray: A saturation distorted image.
        r=   ©g‰A`åÐ"Ó?gbX9´Èâ?gÉv¾Ÿ/½?r
   r   T)ÚkeepdimsrØ   )r   rœ   r  r   r   Úsum)r„   r1  Úgrayr   r   r   Ú
saturation?  s   zColorJitter.saturationc                 C   sÐ   t j ¡ dkrft  |t j ¡}t  |t j ¡}t jg d¢d|| gd||ggt jd�}t jg d¢g d¢g d¢gt jd�}t jg d¢g d	¢g d
¢gt jd�}t  t  ||¡|¡j	}t j|t jd�}t  | |¡} | S )a  Hue distortion.

        Args:
            img (np.ndarray): An input image.
            alpha (float): Alpha value to control the degree of rotation
                for hue. It ranges from [-18, 18).

        Returns:
            np.ndarray: A hue distorted image.
        r=   )rØ   rG   rG   rG   r
   r3  )gßO�—nã?gð§ÆK7‰Ñ¿g%�•C‹Ô¿)g5^ºIË?g#Ûù~j¼à¿g�•C‹lçÓ?)rØ   gd;ßO�—î?g¬Zd;ßã?)rØ   gœÄ °rhÑ¿gNbX9´ä¿)rØ   gƒÀÊ¡E¶ñ¿gHáz®Gû?)
r   rœ   r  ÚcosÚpiÚsinr   r   ÚdotÚT)r„   r1  Úurþ   ÚbtZtyiqZityiqr'   r   r   r   ÚhueS  s(   ÿÿþÿþzColorJitter.huec                    sX  |d }g }| j rktj dd¡}tj dd¡}tj dd¡}tj dd¡}tj ¡ }|D ]=}	| j|	|d�}	|d	krO| j|	|d
�}	| j|	|d
�}	| j|	|d
�}	n| j|	|d
�}	| j|	|d
�}	| j|	|d
�}	| 	|	¡ q,n|}tjj
d| jdd�}
tjt | j|
 | j¡tjd�‰ ˆ d ‰ ‡ fdd„|D ƒ|d< | j|d< | j|d< | j|d< | j |d< |S )Nr   iàÿÿÿé    g333333ã?gffffffö?iîÿÿÿé   )r.  r=   )r1  r   )r;   rÞ   r
   )NN.c                    s   g | ]}|ˆ  ‘qS r   r   rƒ   ©Úrgbr   r   r*   Œ  rš   z(ColorJitter.__call__.<locals>.<listcomp>r)  r*  r+  r,  )r,  r   rœ   rà   r  r/  r2  r7  r?  rú   Únormalr+  r   r;  r*  r)  r   )r)   r   r   ÚoutZbright_deltaZcontrast_alphaZsaturation_alphaZ	hue_alphaZjitter_coinr„   r1  r   rB  r   r}   o  s>   
öÿ



zColorJitter.__call__c              
   C   r  )Nz(color_space_aug=z, alpha_std=z
, eig_val=z
, eig_vec=rX   )rY   rZ   r,  r+  r)  r*  r[   r   r   r   r]   ”  r'  zColorJitter.__repr__)FrD   NN)rZ   r~   r   r€   r6   rì   r/  r2  r7  r?  r}   r]   r   r   r   r   r(  ç  s"    !
ü



%r(  c                   @   r¶   )Ú
CenterCropa†  Crop the center area from images.

    Required keys are "imgs", "img_shape", added or modified keys are "imgs",
    "crop_bbox", "lazy" and "img_shape". Required keys in "lazy" is
    "crop_bbox", added or modified key is "crop_bbox".

    Args:
        crop_size (int | tuple[int]): (w, h) of crop size.
        lazy (bool): Determine whether to apply lazy operation. Default: False.
    Fc                 C   s4   t |ƒ| _|| _t | jt¡stdt|ƒ› �ƒ‚d S ©Nz/Crop_size must be int or tuple of int, but got )r   ré   r   rO   r´   r�   rS   r9   )r)   ré   r   r   r   r   r6   ª  s   
ÿÿzCenterCrop.__init__c                    s  t || jƒ |d \}}| j\}}|| d ‰|| d ‰ˆ| ‰ˆ| ‰ ˆ ˆ ˆˆ }}t ˆˆˆˆ g¡|d< ||f|d< d|vrOtjg d¢tjd�|d< ˆ| ˆ| }}	|| || }
}|d }|d |d }}|d |d	 }}|||  ||	|  |
| || g}tj|tjd�|d< | js§‡ ‡‡‡fd
d„|d D ƒ|d< nJ|d }|d r³tdƒ‚|d \}}}}ˆ||  | ‰ˆ||  | ‰ˆ||  | ‰ˆ ||  | ‰ tj|ˆ |ˆ |ˆ |ˆ  gtjd�|d< d|v �r| jrûJ ‚t|d ƒ}||ƒ}|S )z¹Performs the CenterCrop augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r   r   r   r¹   rº   r
   r   rh   r;   c                    r‚   r   r   rƒ   r…   r   r   r*   Ú  rë   z'CenterCrop.__call__.<locals>.<listcomp>r   r   r   rÂ   rc   )r   r   ré   r   r   r   rÃ   r®   )r)   r   r   r   rç   rè   r½   r¾   rÄ   rÅ   rÆ   rÇ   rÈ   rÉ   rÊ   rË   rÌ   rÍ   r   rÎ   rÏ   rÐ   rÑ   rÒ   r   r…   r   r}   ±  sf   

þ
ý
ÿÿ
ý
ü

zCenterCrop.__call__c                 C   r£   )Nú(crop_size=rÓ   rX   )rY   rZ   ré   r   r[   r   r   r   r]   õ  rÔ   zCenterCrop.__repr__NrÕ   r­   r   r   r   r   rF  �  s
    
DrF  c                   @   r¤   )	Ú	ThreeCropa5  Crop images into three crops.

    Crop the images equally into three crops with equal intervals along the
    shorter side.
    Required keys are "imgs", "img_shape", added or modified keys are "imgs",
    "crop_bbox" and "img_shape".

    Args:
        crop_size(int | tuple[int]): (w, h) of crop size.
    c                 C   ó.   t |ƒ| _t | jt¡stdt|ƒ› �ƒ‚d S rG  ©r   ré   rO   r´   r�   rS   r9   ©r)   ré   r   r   r   r6     ó   
ÿÿzThreeCrop.__init__c                    sD  t |dƒ |d }|d d jdd… \}}| j\‰‰ˆ|ks%ˆ|ks%J ‚ˆ|kr;|ˆ d }dd| df|dfg}nˆ|krP|ˆ d }ddd| fd|fg}g }g }	|D ]/\‰‰ˆˆˆˆ ˆˆ g‰ ‡‡‡‡fdd„|D ƒ}
| |
¡ |	 ‡ fd	d„tt|ƒƒD ƒ¡ qVt |	¡}	||d< |	|d
< |d d jdd… |d< |S )z¸Performs the ThreeCrop augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        Fr   r   Nr   r÷   c                    r»   r   r   rƒ   ©rè   rç   r¿   rÀ   r   r   r*   /  rÁ   z&ThreeCrop.__call__.<locals>.<listcomp>c                    ó   g | ]}ˆ ‘qS r   r   ©r!   rz   ©ro   r   r   r*   4  ó    r   r   )r   r   ré   rû   r’   r›   r   r   )r)   r   r   r   r   rÿ   Úoffsetsr   ZcroppedÚcrop_bboxesÚcropr   ©ro   rè   rç   r¿   rÀ   r   r}     s>   


ý
ýþ
"
zThreeCrop.__call__c                 C   rµ   ©NrH  rX   ©rY   rZ   ré   r[   r   r   r   r]   =  r^   zThreeCrop.__repr__Nr­   r   r   r   r   rI  û  s
    /rI  c                   @   r¤   )	ÚTenCropai  Crop the images into 10 crops (corner + center + flip).

    Crop the four corners and the center part of the image with the same
    given crop_size, and flip it horizontally.
    Required keys are "imgs", "img_shape", added or modified keys are "imgs",
    "crop_bbox" and "img_shape".

    Args:
        crop_size(int | tuple[int]): (w, h) of crop size.
    c                 C   rJ  rG  rK  rL  r   r   r   r6   O  rM  zTenCrop.__init__c                    sH  t |dƒ |d }|d d jdd… \}}| j\‰‰|ˆ d }|ˆ d }dd| dfdd| fd| d| fd| d| fg}tƒ }tƒ }	|D ]=\‰‰‡‡‡‡fdd	„|D ƒ}
d
d	„ |
D ƒ}ˆˆˆˆ ˆˆ g‰ | |
¡ | |¡ |	 ‡ fdd	„tt|ƒd ƒD ƒ¡ qJt |	¡}	||d< |	|d< |d d jdd… |d< |S )z¶Performs the TenCrop augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        Fr   r   Nr   r©   r÷   c                    r»   r   r   rƒ   )rè   rç   r¿   Ú	y_offsetsr   r   r*   q  rÁ   z$TenCrop.__call__.<locals>.<listcomp>c                 S   s   g | ]}t j|d d� ¡ ‘qS )rh   r   )r   r   rM   )r!   r%  r   r   r   r*   u  s    c                    rO  r   r   rP  rQ  r   r   r*   y  rR  r   r   )	r   r   ré   r/   rû   r’   r›   r   r   )r)   r   r   r   r   rÿ   r   rS  Ú	img_cropsrT  rU  Z	flip_cropr   )ro   rè   rç   r¿   rZ  r   r}   U  s8   



ûþ

&
zTenCrop.__call__c                 C   rµ   rW  rX  r[   r   r   r   r]   ‚  r^   zTenCrop.__repr__Nr­   r   r   r   r   rY  B  s
    -rY  c                   @   r¤   )	ÚMultiGroupCropad  Randomly crop the images into several groups.

    Crop the random region with the same given crop_size and bounding box
    into several groups.
    Required keys are "imgs", added or modified keys are "imgs", "crop_bbox"
    and "img_shape".

    Args:
        crop_size(int | tuple[int]): (w, h) of crop size.
        groups(int): Number of groups.
    c                 C   sb   t |ƒ| _|| _t | jt¡stdt|ƒ› �ƒ‚t|tƒs'tdt|ƒ› d�ƒ‚|dkr/t	dƒ‚d S )Nz/Crop size must be int or tuple of int, but got zGroups must be int, but got Ú.r   zGroups must be positive.)
r   ré   ÚgroupsrO   r´   r�   rS   r9   r    r3   )r)   ré   r^  r   r   r   r6   •  s   
ÿ
ÿzMultiGroupCrop.__init__c           	         sî   |d }|d j dd… \}}| j\‰‰g }g }t| jƒD ]=}t d|ˆ ¡‰t d|ˆ ¡‰ˆˆˆˆ ˆˆ g‰ ‡‡‡‡fdd„|D ƒ}| |¡ | ‡ fdd„tt|ƒƒD ƒ¡ qt 	|¡}||d< ||d< |d d j dd… |d	< |S )
z½Performs the MultiGroupCrop augmentation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r   r   Nr   c                    r»   r   r   rƒ   rN  r   r   r*   ´  rÁ   z+MultiGroupCrop.__call__.<locals>.<listcomp>c                    rO  r   r   rP  rQ  r   r   r*   ¹  rR  r   r   )
r   ré   r’   r^  rœ   r�   rû   r›   r   r   )	r)   r   r   r   r   r[  rT  rz   rU  r   rV  r   r}   ¢  s&   
þ
"
zMultiGroupCrop.__call__c                 C   r£   )NrH  z	, groups=rX   )rY   rZ   ré   r^  r[   r   r   r   r]   Â  s   
ÿþzMultiGroupCrop.__repr__Nr­   r   r   r   r   r\  ‡  s
     r\  c                   @   r¤   )	ÚAudioAmplifyzÅAmplify the waveform.

    Required keys are "audios", added or modified keys are "audios",
    "amplify_ratio".

    Args:
        ratio (float): The ratio used to amplify the audio waveform.
    c                 C   s   t |tƒr
|| _d S tdƒ‚)Nz$Amplification ratio should be float.)r    rÜ   ÚratiorS   )r)   r`  r   r   r   r6   Ô  s   

zAudioAmplify.__init__c                 C   s,   d|v sJ ‚|d  | j 9  < | j |d< |S )z´Perfrom the audio amplification.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        ÚaudiosZamplify_ratio)r`  )r)   r   r   r   r   r}   Ú  s   
zAudioAmplify.__call__c                 C   rµ   )Nz(ratio=rX   )rY   rZ   r`  r[   r   r   r   r]   è  r^   zAudioAmplify.__repr__Nr­   r   r   r   r   r_  É  s
    	r_  c                   @   s2   e Zd ZdZ				ddd„Zdd	„ Zd
d„ ZdS )ÚMelSpectrogramaK  MelSpectrogram. Transfer an audio wave into a melspectogram figure.

    Required keys are "audios", "sample_rate", "num_clips", added or modified
    keys are "audios".

    Args:
        window_size (int): The window size in milisecond. Default: 32.
        step_size (int): The step size in milisecond. Default: 16.
        n_mels (int): Number of mels. Default: 80.
        fixed_length (int): The sample length of melspectrogram maybe not
            exactly as wished due to different fps, fix the length for batch
            collation by truncating or padding. Default: 128.
    r@  é   éP   é€   c                 C   s>   t dd„ ||||fD ƒƒr|| _|| _|| _|| _d S tdƒ‚)Nc                 s   r   r   )r    r�   r
  r   r   r   r#     s
   € ÿ
ÿz*MelSpectrogram.__init__.<locals>.<genexpr>zAll arguments should be int.)r0   Úwindow_sizeÚ	step_sizeÚn_melsÚfixed_lengthrS   )r)   rf  rg  rh  ri  r   r   r   r6   ý  s   
þ
zMelSpectrogram.__init__c                 C   s   zddl }W n ty   tdƒ‚w |d }|d }tt|| j d ƒƒ}tt|| j d ƒƒ}tƒ }t|d ƒD ]=}|| }	|jj	|	|||| j
d�}
|
jd | jkr_|
d| j…dd…f }
ntj|
d|
jd	 | j fd
fdd�}
| |
¡ q9t |¡|d< |S )zºPerform MelSpectrogram transformation.

        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        r   NzInstall librosa first.ra  Úsample_rateiè  Ú	num_clips)ÚyÚsrÚn_fftÚ
hop_lengthrh  r¯   r÷   Úedge)r”   )ÚlibrosaÚImportErrorr�   r�   rf  rg  r/   r’   ÚfeatureZmelspectrogramrh  r   ri  r   Úpadrú   r   )r)   r   rq  Úsignalsrj  rn  ro  ZmelspectrogramsÚclip_idxZclip_signalZmelr   r   r   r}     s8   ÿûþzMelSpectrogram.__call__c              
   C   r  )Nz(window_size=z), step_size=z	, n_mels=z, fixed_length=rX   )rY   rZ   rf  rg  rh  ri  r[   r   r   r   r]   /  r'  zMelSpectrogram.__repr__N)r@  rc  rd  re  r­   r   r   r   r   rb  í  s    
ü#rb  ) rœ   Úcollections.abcr   rO   Únumpyr   Ztorch.nn.modules.utilsr   Úregistryr   r   Úregister_moduler   r�   r‘   r¥   r®   r³   r·   rÖ   rí   r¡   r	  r  r  r(  rF  rI  rY  r\  r_  rb  r   r   r   r   Ú<module>   sf    " Y+C!.,c  -b4ZU 6]FDA#