U
    h                     @  s   d dl mZ d dlZd dlmZmZmZ d dlZd dlZ	d dl
mZ d dlmZ d dlm  m  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m Z m!Z! dgZ"G dd deZ#dS )    )annotationsN)AnyTuplecast)label)Literal)BboxProcessordenormalize_bboxesnormalize_bboxes)KeypointsProcessor)OnePlusIntRangeType)BaseTransformInitSchemaDualTransform)
ScalarTypeScaleIntTypeTargetsMaskDropoutc                      s   e Zd ZdZejejejejfZ	G dd de
Zd*dd	d
ddd fddZeddddZddddddZdddddddZddddddd Zddddd!d"d#Zddddd$d%d&Zd'dd(d)Z  ZS )+r   as  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].
        image_fill_value (float | str): Value to fill the dropped out regions in the image.
            If set to 'inpaint', it applies inpainting to the dropped out regions (works only for 3-channel images).
        mask_fill_value (float | int): 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

    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.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>>
        >>> # Define a sample image, mask, and bounding boxes
        >>> 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]])
        >>>
        >>> # Define the transform
        >>> transform = A.Compose([
        ...     A.MaskDropout(max_objects=1, mask_fill_value=0, min_area=100, min_visibility=0.5, p=1.0),
        ... ], bbox_params=A.BboxParams(format='pascal_voc', min_area=1, min_visibility=0.1))
        >>>
        >>> # Apply the transform
        >>> transformed = transform(image=image, mask=mask, bboxes=bboxes)
        >>>
        >>> # The result will have one of the objects dropped out in both image and mask,
        >>> # and the corresponding bounding box removed if it doesn't meet the area and visibility criteria
    c                   @  s&   e Zd ZU ded< ded< ded< dS )zMaskDropout.InitSchemar   max_objectsfloat | Literal['inpaint']image_fill_valuer   mask_fill_valueN)__name__
__module____qualname____annotations__ r   r   U/tmp/pip-unpacked-wheel-e8onvpoz/albumentations/augmentations/dropout/mask_dropout.py
InitSchemaL   s   
r      r   r   N      ?r   r   r   zbool | Nonefloat)r   r   r   always_applypc                   s4   t  j||d ttttf || _|| _|| _d S )N)r#   r"   )super__init__r   r   intr   r   r   )selfr   r   r   r"   r#   	__class__r   r   r%   R   s    zMaskDropout.__init__z	list[str])returnc                 C  s   dgS )Nmaskr   r'   r   r   r   targets_as_params_   s    zMaskDropout.targets_as_paramszdict[str, Any])paramsdatar*   c           
      C  s   |d }t |dd\}}|dkr&d }nrtj| j }t||}||krN|dk}nJttd|d |}tj|j	d |j	d ft
d}|D ]}	|||	kO }qd|iS )Nr+   T)Z
return_numr   r   )Zdtypedropout_mask)r   randomrandintr   minsamplerangenpzerosshapebool)
r'   r.   r/   r+   Zlabel_imageZ
num_labelsr0   Zobjects_to_dropZlabels_indexZlabel_indexr   r   r   get_params_dependent_on_datac   s    

z(MaskDropout.get_params_dependent_on_dataz
np.ndarrayznp.ndarray | Noner   )imgr0   r.   r*   c                 K  sp   |d kr|S | j dkrZ|tj}t|\}}}}tdt||d }t|||tj	S |
 }| j ||< |S )Ninpaint      )r   Zastyper6   Zuint8cv2ZboundingRectr3   maxr<   Z
INPAINT_NScopy)r'   r;   r0   r.   _widthheightZradiusr   r   r   applyx   s    

zMaskDropout.apply)r+   r0   r.   r*   c                 K  s"   |d kr|S |  }| j||< |S )N)rA   r   )r'   r+   r0   r.   r   r   r   apply_to_mask   s
    
zMaskDropout.apply_to_mask)bboxesr0   r.   r*   c                 K  sf   |d kr|S t t| d}|d kr(|S |d d d }t||}t||||jj|jj}t	||S )NrG   r8   r>   )
r   r   get_processorr	   fdropoutZmask_dropout_bboxesr.   Zmin_areaZmin_visibilityr
   )r'   rG   r0   r.   	processorZimage_shapeZdenormalized_bboxesresultr   r   r   apply_to_bboxes   s    
zMaskDropout.apply_to_bboxes)	keypointsr0   r.   r*   c                 K  s<   |d kr|S t t| d}|d ks,|jjs0|S t||S )NrM   )r   r   rH   r.   Zremove_invisiblerI   Zmask_dropout_keypoints)r'   rM   r0   r.   rJ   r   r   r   apply_to_keypoints   s    zMaskDropout.apply_to_keypointsztuple[str, ...]c                 C  s   dS )N)r   r   r   r   r,   r   r   r   get_transform_init_args_names   s    z)MaskDropout.get_transform_init_args_names)r   r   r   Nr    )r   r   r   __doc__r   ZIMAGEMASKZBBOXESZ	KEYPOINTSZ_targetsr   r   r%   propertyr-   r:   rE   rF   rL   rN   rO   __classcell__r   r   r(   r   r      s"   4     )$
__future__r   r1   typingr   r   r   r?   Znumpyr6   Zskimage.measurer   Ztyping_extensionsr   Z/albumentations.augmentations.dropout.functionalZaugmentationsZdropoutZ
functionalrI   Zalbumentations.core.bbox_utilsr   r	   r
   Z#albumentations.core.keypoints_utilsr   Zalbumentations.core.pydanticr   Z(albumentations.core.transforms_interfacer   r   Zalbumentations.core.typesr   r   r   __all__r   r   r   r   r   <module>   s   