Ë
    ÃÓ^jÒ*  ã                  ó´   — d Z ddlmZ ddlmZmZmZ ddlZddlZ	ddl
mc mc mZ ddlmZmZmZ ddlmZ ddlmZ ddlmZmZ dd	lmZ d
gZ G d„ d
e«      Zy)aŸ  Implementation of mask-based dropout augmentation.

This module provides the MaskDropout transform, which identifies objects in a segmentation mask
and drops out random objects completely. This augmentation is particularly useful for instance
segmentation and object detection tasks, as it simulates occlusions or missing objects in a
semantically meaningful way, rather than dropping out random pixels or regions.
é    )Úannotations)ÚAnyÚLiteralÚcastN)ÚBboxProcessorÚdenormalize_bboxesÚnormalize_bboxes)ÚKeypointsProcessor)ÚOnePlusIntRangeType)ÚBaseTransformInitSchemaÚDualTransform)ÚALL_TARGETSÚMaskDropoutc                  ó�   ‡ — e Zd ZdZeZ G d„ de«      Z	 	 	 	 d	 	 	 	 	 	 	 dˆ fd„Ze	dd„«       Z
dd„Zdd„Zdd„Zdd	„Zdd
„Zˆ xZS )r   a£  Apply dropout to random objects in a mask, zeroing out the corresponding regions in both the image and mask.

    This transform identifies objects in the mask (where each unique non-zero value represents a distinct object),
    randomly selects a number of these objects, and sets their corresponding regions to zero in both the image and mask.
    It can also handle bounding boxes and keypoints, removing or adjusting them based on the dropout regions.

    Args:
        max_objects (int | tuple[int, int]): Maximum number of objects to dropout. If a single int is provided,
            it's treated as the upper bound. If a tuple of two ints is provided, it's treated as a range [min, max].
        fill (float | Literal["inpaint_telea", "inpaint_ns"]): Value to fill dropped out regions in the image.
            Can be one of:
            - float: Constant value to fill the regions (e.g., 0 for black, 255 for white)
            - "inpaint_telea": Use Telea inpainting algorithm (for 3-channel images only)
            - "inpaint_ns": Use Navier-Stokes inpainting algorithm (for 3-channel images only)
        fill_mask (float): Value to fill the dropped out regions in the mask.
        min_area (float): Minimum area (in pixels) of a bounding box that must remain visible after dropout to be kept.
            Only applicable if bounding box augmentation is enabled. Default: 0.0
        min_visibility (float): Minimum visibility ratio (visible area / total area) of a bounding box after dropout
            to be kept. Only applicable if bounding box augmentation is enabled. Default: 0.0
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image, mask, bboxes, keypoints, volume, mask3d

    Image types:
        uint8, float32

    Note:
        - The mask should be a single-channel image where 0 represents the background and non-zero values represent
          different object instances.
        - For bounding box and keypoint augmentation, make sure to set up the corresponding processors in the pipeline.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>>
        >>> # Prepare sample data
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> mask = np.zeros((100, 100), dtype=np.uint8)
        >>> mask[20:40, 20:40] = 1  # Object 1
        >>> mask[60:80, 60:80] = 2  # Object 2
        >>> bboxes = np.array([[20, 20, 40, 40], [60, 60, 80, 80]], dtype=np.float32)
        >>> bbox_labels = [1, 2]
        >>> keypoints = np.array([[30, 30], [70, 70]], dtype=np.float32)
        >>> keypoint_labels = [0, 1]
        >>>
        >>> # Define the transform with tuple for max_objects
        >>> transform = A.Compose(
        ...     transforms=[
        ...         A.MaskDropout(
        ...             max_objects=(1, 2),  # Using tuple to specify min and max objects to drop
        ...             fill=0,  # Fill value for dropped regions in image
        ...             fill_mask=0,  # Fill value for dropped regions in mask
        ...             p=1.0
        ...         ),
        ...     ],
        ...     bbox_params=A.BboxParams(
        ...         format='pascal_voc',
        ...         label_fields=['bbox_labels'],
        ...         min_area=1,
        ...         min_visibility=0.1
        ...     ),
        ...     keypoint_params=A.KeypointParams(
        ...         format='xy',
        ...         label_fields=['keypoint_labels'],
        ...         remove_invisible=True
        ...     )
        ... )
        >>>
        >>> # Apply the transform
        >>> transformed = transform(
        ...     image=image,
        ...     mask=mask,
        ...     bboxes=bboxes,
        ...     bbox_labels=bbox_labels,
        ...     keypoints=keypoints,
        ...     keypoint_labels=keypoint_labels
        ... )
        >>>
        >>> # Get the transformed data
        >>> transformed_image = transformed['image']  # Image with dropped out regions
        >>> transformed_mask = transformed['mask']    # Mask with dropped out regions
        >>> transformed_bboxes = transformed['bboxes']  # Remaining bboxes after dropout
        >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels for remaining bboxes
        >>> transformed_keypoints = transformed['keypoints']  # Remaining keypoints after dropout
        >>> transformed_keypoint_labels = transformed['keypoint_labels']  # Labels for remaining keypoints

    c                  ó,   — e Zd ZU ded<   ded<   ded<   y)úMaskDropout.InitSchemar   Úmax_objectsú.float | Literal['inpaint_telea', 'inpaint_ns']ÚfillÚfloatÚ	fill_maskN)Ú__name__Ú
__module__Ú__qualname__Ú__annotations__© ó    ú|/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/albumentations/augmentations/dropout/mask_dropout.pyÚ
InitSchemar   v   s   … Ø(Ó(à<Ó<ØÔr   r   c                ód   •— t         ‰| �  |¬«       t        d|«      | _        || _        || _        y )N)Úpztuple[int, int])ÚsuperÚ__init__r   r   r   r   )Úselfr   r   r   r!   Ú	__class__s        €r   r#   zMaskDropout.__init__|   s3   ø€ ô 	‰Ñ˜1ÐÔÜÐ 1°;Ó?ˆÔØˆŒ	Ø"ˆ�r   c                ó   — dgS )zlGet targets as parameters.

        Returns:
            list[str]: List of targets as parameters.

        Úmaskr   )r$   s    r   Útargets_as_paramszMaskDropout.targets_as_paramsˆ   s   € ð ˆxˆr   c                ó˜  — |d   }t        j                  |d¬«      \  }}|dk(  rd}d	|iS  | j                  j                  | j                  Ž }t        ||«      }||k(  r	|dkD  }d	|iS | j                  j                  t        d|dz   «      |«      }t        j                  |j                  dd t        ¬«      }|D ]
  }	|||	k(  z  }Œ d	|iS )
a!  Get parameters dependent on the data.

        Args:
            params (dict[str, Any]): Dictionary containing parameters.
            data (dict[str, Any]): Dictionary containing data.

        Returns:
            dict[str, Any]: Dictionary with parameters for transformation.

        r'   T)Ú
return_numr   Né   é   )ÚdtypeÚdropout_mask)ÚfdropoutÚlabelÚ	py_randomÚrandintr   ÚminÚsampleÚrangeÚnpÚzerosÚshapeÚbool)
r$   ÚparamsÚdatar'   Úlabel_imageÚ
num_labelsr.   Úobjects_to_dropÚlabels_indexÚlabel_indexs
             r   Úget_params_dependent_on_dataz(MaskDropout.get_params_dependent_on_data’   së   € ð �F‰|ˆä"*§.¡.°À$Ô"GÑˆ�Zà˜Š?ØˆLð  Ð-Ð-ð 5˜dŸn™n×4Ñ4°d×6FÑ6FÐGˆOÜ! *¨oÓ>ˆOà *Ò,Ø# a™x�ð  Ð-Ð-ð  $Ÿ~™~×4Ñ4´U¸1¸jÈ1¹nÓ5MÈÓ_�Ü!Ÿx™x¨¯
©
°2°A¨¼dÔC�Ø#/ò ?�KØ  K°;Ñ$>Ñ>‘Lð?ð  Ð-Ð-r   c           	     ód  — |€|S | j                   dv r~|j                  t        j                  «      }t	        j
                  |«      \  }}}}t        dt        ||«      dz  «      }t	        j                  |||t        d| j                   «      «      S |j                  «       }| j                   ||<   |S )aK  Apply dropout to the image.

        Args:
            img (np.ndarray): The image to apply the transform to.
            dropout_mask (np.ndarray | None): The dropout mask for the image.
            **params (Any): Additional parameters for the transform.

        Returns:
            np.ndarray: The transformed image.

        >   Ú
inpaint_nsÚinpaint_teleaé   r,   z&Literal['inpaint_telea', 'inpaint_ns'])r   Úastyper6   Úuint8Úcv2ÚboundingRectr3   ÚmaxÚinpaintr   Úcopy)r$   Úimgr.   r:   Ú_ÚwidthÚheightÚradiuss           r   ÚapplyzMaskDropout.apply±   s£   € ð ÐØˆJà�9‰9Ð7Ñ7Ø'×.Ñ.¬r¯x©xÓ8ˆLÜ"%×"2Ñ"2°<Ó"@ÑˆAˆq�%˜Ü˜œC  vÓ.°!Ñ3Ó4ˆFÜ—;‘;˜s L°&¼$Ð?gÐim×irÑirÓ:sÓtÐtà�h‰h‹jˆØ ŸI™IˆˆLÑàˆ
r   c                ód   — |�| j                   €|S |j                  «       }| j                   ||<   |S )aH  Apply dropout to the mask.

        Args:
            mask (np.ndarray): The mask to apply the transform to.
            dropout_mask (np.ndarray | None): The dropout mask for the mask.
            **params (Any): Additional parameters for the transform.

        Returns:
            np.ndarray: The transformed mask.

        )r   rL   )r$   r'   r.   r:   s       r   Úapply_to_maskzMaskDropout.apply_to_maskË   s6   € ð Ð 4§>¡>Ð#9ØˆKà�y‰y‹{ˆØ!Ÿ^™^ˆˆ\ÑØˆr   c                ó
  — |€|S t        d| j                  d«      «      }|€|S |d   dd }t        ||«      }t        j                  ||||j
                  j                  |j
                  j                  «      }t        ||«      S )an  Apply dropout to bounding boxes.

        Args:
            bboxes (np.ndarray): The bounding boxes to apply the transform to.
            dropout_mask (np.ndarray | None): The dropout mask for the bounding boxes.
            **params (Any): Additional parameters for the transform.

        Returns:
            np.ndarray: The transformed bounding boxes.

        Nr   Úbboxesr8   r,   )	r   Úget_processorr   r/   Úmask_dropout_bboxesr:   Úmin_areaÚmin_visibilityr	   )r$   rV   r.   r:   Ú	processorÚimage_shapeÚdenormalized_bboxesÚresults           r   Úapply_to_bboxeszMaskDropout.apply_to_bboxesÞ   s”   € ð ÐØˆMä˜¨$×*<Ñ*<¸XÓ*FÓGˆ	ØÐØˆMà˜W‘o b qÐ)ˆä0°¸ÓEÐä×-Ñ-ØØØØ×Ñ×%Ñ%Ø×Ñ×+Ñ+ó
ˆô   ¨Ó4Ð4r   c                ó    — |€|S t        d| j                  d«      «      }|�|j                  j                  s|S t	        j
                  ||«      S )a]  Apply dropout to keypoints.

        Args:
            keypoints (np.ndarray): The keypoints to apply the transform to.
            dropout_mask (np.ndarray | None): The dropout mask for the keypoints.
            **params (Any): Additional parameters for the transform.

        Returns:
            np.ndarray: The transformed keypoints.

        r
   Ú	keypoints)r   rW   r:   Úremove_invisibler/   Úmask_dropout_keypoints)r$   ra   r.   r:   r[   s        r   Úapply_to_keypointszMaskDropout.apply_to_keypointsÿ   sU   € ð ÐØÐÜÐ-¨t×/AÑ/AÀ+Ó/NÓOˆ	àÐ I×$4Ñ$4×$EÒ$EØÐä×.Ñ.¨y¸,ÓGÐGr   ))r+   r+   r   r   g      à?)r   ztuple[int, int] | intr   r   r   r   r!   r   )Úreturnz	list[str])r:   údict[str, Any]r;   rf   re   rf   )rM   ú
np.ndarrayr.   únp.ndarray | Noner:   r   re   rg   )r'   rg   r.   rh   r:   r   re   rg   )rV   rg   r.   rh   r:   r   re   rg   )ra   rg   r.   rh   r:   r   re   rg   )r   r   r   Ú__doc__r   Ú_targetsr   r   r#   Úpropertyr(   rA   rR   rT   r_   rd   Ú__classcell__)r%   s   @r   r   r      s†   ø„ ñWðr €HôÐ,ô ð .4Ø?@ØØð
#à*ð
#ð =ð
#ð ð	
#ð
 õ
#ð òó ðó.ó>ó4ó&5÷BHr   )ri   Ú
__future__r   Útypingr   r   r   rH   Únumpyr6   Ú/albumentations.augmentations.dropout.functionalÚaugmentationsÚdropoutÚ
functionalr/   Úalbumentations.core.bbox_utilsr   r   r	   Ú#albumentations.core.keypoints_utilsr
   Úalbumentations.core.pydanticr   Ú(albumentations.core.transforms_interfacer   r   Ú$albumentations.core.type_definitionsr   Ú__all__r   r   r   r   ú<module>rz      sJ   ðñõ #ç %Ñ %ã 
Û ç BÓ Bß ^Ñ ^Ý BÝ <ß [Ý <àˆ/€ôxH�-õ xHr   