Ë
    ÃÓ^jaG  ã                  óî   — d Z ddlmZ ddlmZmZmZ ddlZddl	m
Z
 ddlmZ ddlmZ ddlmZmZmZmZmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZm Z  ddl!m"Z"m#Z# dgZ$ G d„ de «      Z% G d„ de «      Z&y)a�  Transform classes for dropout-based augmentations.

This module contains transform classes for various dropout techniques used in image
augmentation. It provides the base dropout class and specialized implementations like
PixelDropout. These transforms randomly remove or modify pixels, channels, or regions
in images, which can help models become more robust to occlusions and missing information.
é    )Úannotations)ÚAnyÚLiteralÚcastN)Úget_num_channels)ÚField)Ú
functional)ÚcutoutÚcutout_on_volumeÚcutout_on_volumesÚfilter_bboxes_by_holesÚfilter_keypoints_in_holes)ÚBboxProcessorÚdenormalize_bboxesÚnormalize_bboxes)ÚKeypointsProcessor)ÚBaseTransformInitSchemaÚDualTransform)ÚALL_TARGETSÚTargetsÚPixelDropoutc                  óÆ   ‡ — e Zd ZU dZeZded<    G d„ de«      Z	 	 	 	 	 	 dˆ fd„Z	dd„Z
dd„Zdd	„Zdd
„Zdd„Zdd„Zdd„Z	 	 	 	 	 	 	 	 dd„Z	 	 	 	 	 	 	 	 dd„Zdd„Zˆ xZS )ÚBaseDropoutaT  Base class for dropout-style transformations.

    This class provides common functionality for various dropout techniques,
    including applying cutouts to images and masks.

    Args:
        fill (tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
            Value to fill dropped regions.
        fill_mask (tuple[float, ...] | float | None): Value to fill
            dropped regions in the mask. If None, the mask is not modified.
        p (float): Probability of applying the transform.

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

    Image types:
        uint8, float32

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>>
        >>> # Example of a custom dropout transform inheriting from BaseDropout
        >>> class CustomDropout(A.BaseDropout):
        ...     def __init__(self, num_holes_range=(4, 8), hole_size_range=(10, 20), *args, **kwargs):
        ...         super().__init__(*args, **kwargs)
        ...         self.num_holes_range = num_holes_range
        ...         self.hole_size_range = hole_size_range
        ...
        ...     def get_params_dependent_on_data(self, params, data):
        ...         img = data["image"]
        ...         height, width = img.shape[:2]
        ...
        ...         # Generate random holes
        ...         num_holes = self.py_random.randint(*self.num_holes_range)
        ...         hole_sizes = self.py_random.randint(*self.hole_size_range, size=num_holes)
        ...
        ...         holes = []
        ...         for i in range(num_holes):
        ...             # Random position for each hole
        ...             x1 = self.py_random.randint(0, max(1, width - hole_sizes[i]))
        ...             y1 = self.py_random.randint(0, max(1, height - hole_sizes[i]))
        ...             x2 = min(width, x1 + hole_sizes[i])
        ...             y2 = min(height, y1 + hole_sizes[i])
        ...             holes.append([x1, y1, x2, y2])
        ...
        ...         # Return holes and random seed
        ...         return {
        ...             "holes": np.array(holes) if holes else np.empty((0, 4), dtype=np.int32),
        ...             "seed": self.py_random.integers(0, 100000)
        ...         }
        >>>
        >>> # Prepare sample data
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
        >>> bboxes = np.array([[0.1, 0.1, 0.4, 0.4], [0.6, 0.6, 0.9, 0.9]])
        >>>
        >>> # Create a transform with custom dropout
        >>> transform = A.Compose([
        ...     CustomDropout(
        ...         num_holes_range=(3, 6),       # Generate 3-6 random holes
        ...         hole_size_range=(5, 15),      # Holes of size 5-15 pixels
        ...         fill=0,                       # Fill holes with black
        ...         fill_mask=1,                  # Fill mask holes with 1
        ...         p=1.0                         # Always apply for this example
        ...     )
        ... ], bbox_params=A.BboxParams(format='yolo', min_visibility=0.3))
        >>>
        >>> # Apply the transform
        >>> transformed = transform(image=image, mask=mask, bboxes=bboxes)
        >>>
        >>> # Get the transformed data
        >>> dropout_image = transformed["image"]      # Image with random holes filled with 0
        >>> dropout_mask = transformed["mask"]        # Mask with same holes filled with 1
        >>> dropout_bboxes = transformed["bboxes"]    # Bboxes filtered by visibility threshold

    ztuple[Targets, ...] | TargetsÚ_targetsc                  ó"   — e Zd ZU ded<   ded<   y)úBaseDropout.InitSchemaú^tuple[float, ...] | float | Literal['random', 'random_uniform', 'inpaint_telea', 'inpaint_ns']Úfillú tuple[float, ...] | float | NoneÚ	fill_maskN)Ú__name__Ú
__module__Ú__qualname__Ú__annotations__© ó    úz/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/albumentations/augmentations/dropout/transforms.pyÚ
InitSchemar   s   s   … ØlÓlØ3Ô3r&   r(   c                óB   •— t         ‰| �  |¬«       || _        || _        y ©N)Úp)ÚsuperÚ__init__r   r    )Úselfr   r    r+   Ú	__class__s       €r'   r-   zBaseDropout.__init__w   s#   ø€ ô 	‰Ñ˜1ÐÔØˆŒ	Ø"ˆ�r&   c                óÞ   — |j                   dk(  r|S | j                  dv rt        |«      }|dvrt        d«      ‚t	        ||| j                  t
        j                  j                  |«      «      S )Nr   >   Ú
inpaint_nsÚinpaint_telea¾   é   é   ú/Inpainting works only for 1 or 3 channel images)Úsizer   r   Ú
ValueErrorr
   ÚnpÚrandomÚdefault_rng)r.   ÚimgÚholesÚseedÚparamsÚnum_channelss         r'   ÚapplyzBaseDropout.apply�   sa   € Ø�:‰:˜Š?ØˆJØ�9‰9Ð7Ñ7Ü+¨CÓ0ˆLØ 6Ñ)Ü Ð!RÓSÐSÜ�c˜5 $§)¡)¬R¯Y©Y×-BÑ-BÀ4Ó-HÓIÐIr&   c                ó  — |j                   dk(  r|S | j                  dv r/|j                  dk(  r|j                  d   nd}|dvrt	        d«      ‚t        ||| j                  t        j                  j                  |«      «      S )Nr   >   r1   r2   é   r5   r4   r3   r6   )	r7   r   ÚndimÚshaper8   r   r9   r:   r;   )r.   Úimagesr=   r>   r?   r@   s         r'   Úapply_to_imageszBaseDropout.apply_to_imagesŠ   sr   € Ø�:‰:˜Š?ØˆMØ�9‰9Ð7Ñ7Ø.4¯k©k¸QÒ.>˜6Ÿ<™<¨š?ÀAˆLØ 6Ñ)Ü Ð!RÓSÐSä ¨¨t¯y©y¼"¿)¹)×:OÑ:OÐPTÓ:UÓVÐVr&   c                ó,   —  | j                   |||fi |¤ŽS )N)rG   )r.   Úvolumer=   r>   r?   s        r'   Úapply_to_volumezBaseDropout.apply_to_volume”   s    € ð $ˆt×#Ñ# F¨E°4ÑB¸6ÑBÐBr&   c                ó  — |j                   dk(  r|S | j                  dv r/|j                  dk(  r|j                  d   nd}|dvrt	        d«      ‚t        ||| j                  t        j                  j                  |«      «      S )Nr   >   r1   r2   é   rC   r4   r3   r6   )	r7   r   rD   rE   r8   r   r9   r:   r;   )r.   Úvolumesr=   r>   r?   r@   s         r'   Úapply_to_volumeszBaseDropout.apply_to_volumes™   ss   € Ø�:‰:˜Š?ØˆNØ�9‰9Ð7Ñ7Ø/6¯|©|¸qÒ/@˜7Ÿ=™=¨Ò+ÀaˆLØ 6Ñ)Ü Ð!RÓSÐSÜ  ¨%°·±¼B¿I¹I×<QÑ<QÐRVÓ<WÓXÐXr&   c                ó¦   — | j                   �|j                  dk(  r|S t        ||| j                   t        j                  j                  |«      «      S ©Nr   )r    r7   r   r9   r:   r;   ©r.   Úmaskr=   r>   r?   s        r'   Úapply_to_mask3dzBaseDropout.apply_to_mask3d¢   s@   € Ø�>‰>Ð! U§Z¡Z°1¢_ØˆKÜ  e¨T¯^©^¼R¿Y¹Y×=RÑ=RÐSWÓ=XÓYÐYr&   c                ó¦   — | j                   �|j                  dk(  r|S t        ||| j                   t        j                  j                  |«      «      S rP   )r    r7   r   r9   r:   r;   rQ   s        r'   Úapply_to_masks3dzBaseDropout.apply_to_masks3d§   s@   € Ø�>‰>Ð! U§Z¡Z°1¢_ØˆKÜ   u¨d¯n©n¼b¿i¹i×>SÑ>SÐTXÓ>YÓZÐZr&   c                ó¦   — | j                   �|j                  dk(  r|S t        ||| j                   t        j                  j                  |«      «      S rP   )r    r7   r
   r9   r:   r;   rQ   s        r'   Úapply_to_maskzBaseDropout.apply_to_mask¬   s?   € Ø�>‰>Ð! U§Z¡Z°1¢_ØˆKÜ�d˜E 4§>¡>´2·9±9×3HÑ3HÈÓ3NÓOÐOr&   c           	     ó  — |j                   dk(  r|S t        d| j                  d«      «      }|€|S |d   d d }t        ||«      }t	        t        ||||j                  j                  |j                  j                  ¬«      |«      S )Nr   r   ÚbboxesrE   é   )Úmin_areaÚmin_visibility)	r7   r   Úget_processorr   r   r   r?   r[   r\   )r.   rY   r=   r?   Ú	processorÚimage_shapeÚdenormalized_bboxess          r'   Úapply_to_bboxeszBaseDropout.apply_to_bboxes±   s”   € ð �:‰:˜Š?ØˆMÜ˜¨$×*<Ñ*<¸XÓ*FÓGˆ	ØÐØˆMà˜W‘o b qÐ)ˆÜ0°¸ÓEÐäÜ"Ø#ØØØ"×)Ñ)×2Ñ2Ø(×/Ñ/×>Ñ>ôð ó	
ð 		
r&   c                ó¦   — |j                   dk(  r|S t        d| j                  d«      «      }|�|j                  j                  s|S t        ||«      S )Nr   r   Ú	keypoints)r7   r   r]   r?   Úremove_invisibler   )r.   rc   r=   r?   r^   s        r'   Úapply_to_keypointszBaseDropout.apply_to_keypointsË   sT   € ð �:‰:˜Š?ØÐÜÐ-¨t×/AÑ/AÀ+Ó/NÓOˆ	àÐ I×$4Ñ$4×$EÒ$EØÐä(¨°EÓ:Ð:r&   c                ó   — t        d«      ‚)Nz&Subclasses must implement this method.)ÚNotImplementedError)r.   r?   Údatas      r'   Úget_params_dependent_on_dataz(BaseDropout.get_params_dependent_on_dataÚ   s   € Ü!Ð"JÓKÐKr&   )r   r   r    r   r+   Úfloat)
r<   ú
np.ndarrayr=   rk   r>   Úintr?   r   Úreturnrk   )
rF   rk   r=   rk   r>   rl   r?   r   rm   rk   )
rI   rk   r=   rk   r>   rl   r?   r   rm   rk   )
rM   rk   r=   rk   r>   rl   r?   r   rm   rk   )
rR   rk   r=   rk   r>   rl   r?   r   rm   rk   )rY   rk   r=   rk   r?   r   rm   rk   )rc   rk   r=   rk   r?   r   rm   rk   ©r?   údict[str, Any]rh   ro   rm   ro   )r!   r"   r#   Ú__doc__r   r   r$   r   r(   r-   rA   rG   rJ   rN   rS   rU   rW   ra   re   ri   Ú__classcell__©r/   s   @r'   r   r   "   sË   ø… ñLð\ /:€HÐ+Ó9ô4Ð,ô 4ð#àlð#ð 4ð#ð õ	#óJóWóCó
YóZó
[ó
Pð

àð
ð ð
ð ð	
ð
 
ó
ð4;àð;ð ð;ð ð	;ð
 
ó;÷Lr&   r   c                  óÔ   ‡ — e Zd ZdZ G d„ de«      ZeZ	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 dˆ fd„Z	 	 	 	 	 	 	 	 	 	 dd„Z		 	 	 	 	 	 	 	 	 	 dd„Z
	 	 	 	 	 	 	 	 dd„Z	 	 	 	 	 	 dd„Z	 	 	 	 	 	 dd	„Zˆ xZS )r   ap	  Drops random pixels from the image.

    This transform randomly sets pixels in the image to a specified value, effectively "dropping out" those pixels.
    It can be applied to both the image and its corresponding mask.

    Args:
        dropout_prob (float): Probability of dropping out each pixel. Should be in the range [0, 1].
            Default: 0.01

        per_channel (bool): If True, the dropout mask will be generated independently for each channel.
            If False, the same dropout mask will be applied to all channels.
            Default: False

        drop_value (float | tuple[float, ...] | None): Value to assign to the dropped pixels.
            If None, the value will be randomly sampled for each application:
                - For uint8 images: Random integer in [0, 255]
                - For float32 images: Random float in [0, 1]
            If a single number, that value will be used for all dropped pixels.
            If a sequence, it should contain one value per channel.
            Default: 0

        mask_drop_value (float | tuple[float, ...] | None): Value to assign to dropped pixels in the mask.
            If None, the mask will remain unchanged.
            If a single number, that value will be used for all dropped pixels in the mask.
            If a sequence, it should contain one value per channel.
            Default: None

        p (float): Probability of applying the transform. Should be in the range [0, 1].
            Default: 0.5

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

    Image types:
        uint8, float32

    Note:
        - When applied to bounding boxes, this transform may cause some boxes to have zero area
          if all pixels within the box are dropped. Such boxes will be removed.
        - When applied to keypoints, keypoints that fall on dropped pixels will be removed if
          the keypoint processor is configured to remove invisible keypoints.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
        >>> transform = A.PixelDropout(dropout_prob=0.1, per_channel=True, p=1.0)
        >>> result = transform(image=image, mask=mask)
        >>> dropped_image, dropped_mask = result['image'], result['mask']

    c                  óJ   — e Zd ZU  edd¬«      Zded<   ded<   ded	<   ded
<   y)úPixelDropout.InitSchemar   r4   )ÚgeÚlerj   Údropout_probÚboolÚper_channelr   Ú
drop_valueÚmask_drop_valueN)r!   r"   r#   r   rx   r$   r%   r&   r'   r(   ru     s%   … Ù# q¨QÔ/ˆ�eÓ/ØÓØ4Ó4Ø9Ô9r&   r(   c                ó^   •— t         ‰| �  |¬«       || _        || _        || _        || _        y r*   )r,   r-   rx   rz   r{   r|   )r.   rx   rz   r{   r|   r+   r/   s         €r'   r-   zPixelDropout.__init__  s4   ø€ ô 	‰Ñ˜1ÐÔØ(ˆÔØ&ˆÔØ$ˆŒØ.ˆÕr&   c                ó0   — t        j                  |||«      S )a‹  Apply pixel dropout to the image.

        Args:
            img (np.ndarray): The image to apply the transform to.
            drop_mask (np.ndarray): The dropout mask.
            drop_values (np.ndarray): The values to assign to the dropped pixels.
            **params (Any): Additional parameters for the transform.

        Returns:
            np.ndarray: The transformed image.

        )ÚfpixelÚpixel_dropout)r.   r<   Ú	drop_maskÚdrop_valuesr?   s        r'   rA   zPixelDropout.apply*  s   € ô& ×#Ñ# C¨°KÓ@Ð@r&   c                óL   — | j                   €|S t        j                  |||«      S )a´  Apply pixel dropout to the mask.

        Args:
            mask (np.ndarray): The mask to apply the transform to.
            mask_drop_mask (np.ndarray): The dropout mask for the mask.
            mask_drop_values (float | np.ndarray): The values to assign to the dropped pixels in the mask.
            **params (Any): Additional parameters for the transform.

        Returns:
            np.ndarray: The transformed mask.

        )r|   r   r€   )r.   rR   Úmask_drop_maskÚmask_drop_valuesr?   s        r'   rW   zPixelDropout.apply_to_mask?  s+   € ð& ×ÑÐ'ØˆKä×#Ñ# D¨.Ð:JÓKÐKr&   c                ó  — |�| j                   r|S t        d| j                  d«      «      }|€|S |d   dd }t        ||«      }| j                   rjt	        |j
                  «      dkD  rRt        j                  ||j
                  d   dk  rdnd¬	«      }|j                  d
k(  r|j
                  d   dk(  r|d   }n|}t        j                  ||||j                  j                  |j                  j                  «      }t        ||«      S )au  Apply pixel dropout to the bounding boxes.

        Args:
            bboxes (np.ndarray): The bounding boxes to apply the transform to.
            drop_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   rY   rE   rZ   éÿÿÿÿrC   r   )Úaxisr5   r4   )rz   r   r]   r   ÚlenrE   r9   ÚanyrD   ÚfdropoutÚmask_dropout_bboxesr?   r[   r\   r   )	r.   rY   r�   r?   r^   r_   r`   Úcombined_maskÚresults	            r'   ra   zPixelDropout.apply_to_bboxesW  s
  € ð" Ð × 0Ò 0ØˆMä˜¨$×*<Ñ*<¸XÓ*FÓGˆ	ØÐØˆMà˜W‘o b qÐ)ˆä0°¸ÓEÐð ×Ò¤ I§O¡OÓ 4°qÒ 8äŸF™F 9¸¿¹ÈÑ9LÐPQÒ9Q±2ÐWXÔYˆMà×!Ñ! QÒ&¨=×+>Ñ+>¸qÑ+AÀQÒ+FØ -¨aÑ 0‘à%ˆMä×-Ñ-ØØØØ×Ñ×%Ñ%Ø×Ñ×+Ñ+ó
ˆô   ¨Ó4Ð4r&   c                ó   — |S )a  Apply pixel dropout to the keypoints.

        Args:
            keypoints (np.ndarray): The keypoints to apply the transform to.
            **params (Any): Additional parameters for the transform.

        Returns:
            np.ndarray: The transformed keypoints.

        r%   )r.   rc   r?   s      r'   re   zPixelDropout.apply_to_keypointsˆ  s
   € ð Ðr&   c                ó@  — d|v r|d   n|d   d   }t        j                  |j                  | j                  | j                  | j
                  «      }t        j                  || j                  | j
                  «      }d}d}t        j                  |«      }| j                  �m|�kt        j                  |j                  | j                  | j                  | j
                  «      }t        j                  || j                  | j
                  «      }|||�|nd|�|dœS ddœS )a(  Generate parameters for pixel dropout based on input data.

        Args:
            params (dict[str, Any]): Transform parameters
            data (dict[str, Any]): Input data dictionary

        Returns:
            dict[str, Any]: Dictionary of parameters for applying the transform

        ÚimagerF   r   N)r�   r‚   r„   r…   )
r   Úget_drop_maskrE   rz   rx   Úrandom_generatorÚprepare_drop_valuesr{   Úget_mask_arrayr|   )	r.   r?   rh   Úreference_arrayr�   r‚   r„   r…   rR   s	            r'   ri   z)PixelDropout.get_params_dependent_on_data™  s8  € ð ,3°d©?˜$˜wš-ÀÀXÁÈqÑ@Qˆô ×(Ñ(Ø×!Ñ!Ø×ÑØ×ÑØ×!Ñ!ó	
ˆ	ô ×0Ñ0ØØ�O‰OØ×!Ñ!ó
ˆð ˆØÐÜ×$Ñ$ TÓ*ˆØ×ÑÐ+°Ð0@Ü#×1Ñ1Ø—
‘
Ø× Ñ Ø×!Ñ!Ø×%Ñ%ó	ˆNô  &×9Ñ9ØØ×$Ñ$Ø×%Ñ%ó Ðð #Ø&Ø0>Ð0J™nÐPTØ4DÐ4PÐ 0ñ	
ð 	
ð W[ñ	
ð 	
r&   )g{®Gáz„?Fr   Ng      à?)
rx   rj   rz   ry   r{   r   r|   r   r+   rj   )
r<   rk   r�   rk   r‚   rk   r?   r   rm   rk   )
rR   rk   r„   rk   r…   zfloat | np.ndarrayr?   r   rm   rk   )rY   rk   r�   znp.ndarray | Noner?   r   rm   rk   )rc   rk   r?   r   rm   rk   rn   )r!   r"   r#   rp   r   r(   r   r   r-   rA   rW   ra   re   ri   rq   rr   s   @r'   r   r   Þ   sG  ø„ ñ3ôj:Ð,ô :ð €Hð #Ø!Ø78Ø<@Øð/àð/ð ð/ð 5ð	/ð
 :ð/ð õ/ðAàðAð ðAð  ð	Að
 ðAð 
óAð*LàðLð #ðLð -ð	Lð
 ðLð 
óLð0/5àð/5ð %ð/5ð ð	/5ð
 
ó/5ðbàðð ðð 
ó	ð"4
àð4
ð ð4
ð 
÷	4
r&   )'rp   Ú
__future__r   Útypingr   r   r   Únumpyr9   Úalbucorer   Úpydanticr   Ú$albumentations.augmentations.dropoutr	   r‹   Ú/albumentations.augmentations.dropout.functionalr
   r   r   r   r   Ú"albumentations.augmentations.pixelr   Úalbumentations.core.bbox_utilsr   r   r   Ú#albumentations.core.keypoints_utilsr   Ú(albumentations.core.transforms_interfacer   r   Ú$albumentations.core.type_definitionsr   r   Ú__all__r   r   r%   r&   r'   ú<module>r¤      sg   ðñõ #ç %Ñ %ã Ý %Ý å G÷õ õ Dß ^Ñ ^Ý Bß [ß EàÐ
€ôyL�-ô yLôxo
�=õ o
r&   