
    h_                        S r SSKJr  SSKJrJrJr  SSKJr  SSK	r
SSKJr  SSKJs  Js  Jr  SSKJr  SSKJr  SS	KJrJr  / S
Qr " S S\5      r " S S\5      r " S S\5      rg)a  Implementation of coarse dropout and random erasing augmentations.

This module provides several variations of coarse dropout augmentations, which drop out
rectangular regions from images. It includes CoarseDropout for randomly placed dropouts,
ConstrainedCoarseDropout for dropping out regions based on masks or bounding boxes,
and Erasing for random erasing augmentation. These techniques help models become more
robust to occlusions and varying object completeness.
    )annotations)	AnnotatedAnyLiteral)warnN)AfterValidator)BaseDropout)denormalize_bboxes)check_range_boundsnondecreasing)CoarseDropoutConstrainedCoarseDropoutErasingc                     ^  \ rS rSrSr " S S\R                  5      r      S	           S
U 4S jjjr          SS jrSS jr	Sr
U =r$ )r      a  CoarseDropout randomly drops out rectangular regions from the image and optionally,
the corresponding regions in an associated mask, to simulate occlusion and
varied object sizes found in real-world settings.

This transformation is an evolution of CutOut and RandomErasing, offering more
flexibility in the size, number of dropout regions, and fill values.

Args:
    num_holes_range (tuple[int, int]): Range (min, max) for the number of rectangular
        regions to drop out. Default: (1, 1)
    hole_height_range (tuple[int, int] | tuple[float, float]): Range (min, max) for the height
        of dropout regions. If int, specifies absolute pixel values. If float,
        interpreted as a fraction of the image height. Default: (0.1, 0.2)
    hole_width_range (tuple[int, int] | tuple[float, float]): Range (min, max) for the width
        of dropout regions. If int, specifies absolute pixel values. If float,
        interpreted as a fraction of the image width. Default: (0.1, 0.2)
    fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
        Value for the dropped pixels. Can be:
        - int or float: all channels are filled with this value
        - tuple: tuple of values for each channel
        - 'random': each pixel is filled with random values
        - 'random_uniform': each hole is filled with a single random color
        - 'inpaint_telea': uses OpenCV Telea inpainting method
        - 'inpaint_ns': uses OpenCV Navier-Stokes inpainting method
        Default: 0
    fill_mask (tuple[float, float] | float | None): Fill value for dropout regions in the mask.
        If None, mask regions corresponding to image dropouts are unchanged. Default: None
    p (float): Probability of applying the transform. Default: 0.5

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

Image types:
    uint8, float32

Note:
    - The actual number and size of dropout regions are randomly chosen within the specified ranges for each
        application.
    - When using float values for hole_height_range and hole_width_range, ensure they are between 0 and 1.
    - This implementation includes deprecation warnings for older parameter names (min_holes, max_holes, etc.).
    - Inpainting methods ('inpaint_telea', 'inpaint_ns') work only with grayscale or RGB images.
    - For 'random_uniform' fill, each hole gets a single random color, unlike 'random' where each pixel
        gets its own random value.

Example:
    >>> 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)
    >>> # Example with random uniform fill
    >>> aug_random = A.CoarseDropout(
    ...     num_holes_range=(3, 6),
    ...     hole_height_range=(10, 20),
    ...     hole_width_range=(10, 20),
    ...     fill="random_uniform",
    ...     p=1.0
    ... )
    >>> # Example with inpainting
    >>> aug_inpaint = A.CoarseDropout(
    ...     num_holes_range=(3, 6),
    ...     hole_height_range=(10, 20),
    ...     hole_width_range=(10, 20),
    ...     fill="inpaint_ns",
    ...     p=1.0
    ... )
    >>> transformed = aug_random(image=image, mask=mask)
    >>> transformed_image, transformed_mask = transformed["image"], transformed["mask"]

References:
    - CutOut: https://arxiv.org/abs/1708.04552
    - Random Erasing: https://arxiv.org/abs/1708.04896
    - OpenCV Inpainting methods: https://docs.opencv.org/master/df/d3d/tutorial_py_inpainting.html

c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg)	CoarseDropout.InitSchemaf   fAnnotated[tuple[int, int], AfterValidator(check_range_bounds(1, None)), AfterValidator(nondecreasing)]num_holes_rangez|Annotated[tuple[float, float] | tuple[int, int], AfterValidator(nondecreasing), AfterValidator(check_range_bounds(0, None))]hole_height_rangehole_width_range N__name__
__module____qualname____firstlineno____annotations____static_attributes__r       m/var/www/fran/franai/venv/lib/python3.13/site-packages/albumentations/augmentations/dropout/coarse_dropout.py
InitSchemar   f   s     
 	

 	

 	
r!   r#   c                F   > [         TU ]  XEUS9  Xl        X l        X0l        g N)fill	fill_maskp)super__init__r   r   r   )selfr   r   r   r&   r'   r(   	__class__s          r"   r*   CoarseDropout.__init__y   s)     	d1=.!2 0r!   c                   USS u  pVUS   S:  a  US   n[        US   U5      nUS   n	[        US   U5      n
U R                  R                  [        U5      [        US-   5      US9nU R                  R                  [        U	5      [        U
S-   5      US9nX4$ XPR                  R                  " USU06-  R                  [        5      nX`R                  R                  " USU06-  R                  [        5      nX4$ )z>Calculate random hole dimensions based on the provided ranges.N      r   sizer2   )minrandom_generatorintegersintuniformastype)r+   image_shapeheight_rangewidth_ranger2   heightwidth
min_height
max_height	min_width	max_widthhole_heightshole_widthss                r"   calculate_hole_dimensions'CoarseDropout.calculate_hole_dimensions   s    $BQ?a%aJ\!_f5J#AIKNE2I0099#j/3z\]~K^ei9jL//88YYYZ]I[bf8gK (( #%:%:%B%BL%\W[%\\ddehiL #8#8#@#@+#YTX#YYaabefK((r!   c                   US   SS nU R                   R                  " U R                  6 nU R                  UU R                  U R
                  US9u  pVUSS u  pxU R                  R                  SXu-
  S-   US9n	U R                  R                  SX-
  S-   US9n
X-   nX-   n[        R                  " XX/SS9nXR                  R                  SS	5      S
.$ )zGet 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.

shapeNr/   r1   r   r0   )axis    holesseed)
	py_randomrandintr   rD   r   r   r4   r5   npstack)r+   paramsdatar9   	num_holesrB   rC   r<   r=   y_minx_miny_maxx_maxrL   s                 r"   get_params_dependent_on_data*CoarseDropout.get_params_dependent_on_data   s     Wobq)NN**D,@,@A	$($B$B""!!	 %C %
! $BQ%%..q&2G!2KR[.\%%..q%2E2IPY.Z$#%5B?(=(=(F(Fq)(TUUr!   )r   r   r   ))r0   r/   皙?g?r[   r   N      ?)r   tuple[int, int]r   %tuple[float, float] | tuple[int, int]r   r_   r&   ^tuple[float, ...] | float | Literal['random', 'random_uniform', 'inpaint_telea', 'inpaint_ns']r'    tuple[float, ...] | float | Noner(   float)
r9   r^   r:   r_   r;   r_   r2   r6   returnztuple[np.ndarray, np.ndarray]rR   dict[str, Any]rS   re   rc   re   )r   r   r   r   __doc__r	   r#   r*   rD   rY   r    __classcell__r,   s   @r"   r   r      s    IV
[++ 
* ,2CMBLop6:1(1 A1 @	1
 m1 41 1 1)$) <) ;	)
 ) 
')4V Vr!   r   c                     ^  \ rS rSrSr " S S\R                  5      r     S         S	U 4S jjjrS
S jrSr	U =r
$ )r      a
  Randomly erases rectangular regions in an image, following the Random Erasing Data Augmentation technique.

This augmentation helps improve model robustness by randomly masking out rectangular regions in the image,
simulating occlusions and encouraging the model to learn from partial information. It's particularly
effective for image classification and person re-identification tasks.

Args:
    scale (tuple[float, float]): Range for the proportion of image area to erase.
        The actual area will be randomly sampled from (scale[0] * image_area, scale[1] * image_area).
        Default: (0.02, 0.33)
    ratio (tuple[float, float]): Range for the aspect ratio (width/height) of the erased region.
        The actual ratio will be randomly sampled from (ratio[0], ratio[1]).
        Default: (0.3, 3.3)
    fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
        Value used to fill the erased regions. Can be:
        - int or float: fills all channels with this value
        - tuple: fills each channel with corresponding value
        - "random": fills each pixel with random values
        - "random_uniform": fills entire erased region with a single random color
        - "inpaint_telea": uses OpenCV Telea inpainting method
        - "inpaint_ns": uses OpenCV Navier-Stokes inpainting method
        Default: 0
    fill_mask (tuple[float, float] | float | None): Value used to fill erased regions in the mask.
        If None, mask regions are not modified. Default: None
    p (float): Probability of applying the transform. Default: 0.5

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

Image types:
    uint8, float32

Note:
    - The transform attempts to find valid erasing parameters up to 10 times.
      If unsuccessful, no erasing is performed.
    - The actual erased area and aspect ratio are randomly sampled within
      the specified ranges for each application.
    - When using inpainting methods, only grayscale or RGB images are supported.

Example:
    >>> import numpy as np
    >>> import albumentations as A
    >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
    >>> # Basic usage with default parameters
    >>> transform = A.Erasing()
    >>> transformed = transform(image=image)
    >>> # Custom configuration
    >>> transform = A.Erasing(
    ...     scale=(0.1, 0.4),
    ...     ratio=(0.5, 2.0),
    ...     fill_value="random_uniform",
    ...     p=1.0
    ... )
    >>> transformed = transform(image=image)

References:
    - Paper: https://arxiv.org/abs/1708.04896
    - Implementation inspired by torchvision:
      https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.RandomErasing

c                  *    \ rS rSr% S\S'   S\S'   Srg)Erasing.InitSchemai  zjAnnotated[tuple[float, float], AfterValidator(nondecreasing), AfterValidator(check_range_bounds(0, None))]scaleratior   Nr   r   r!   r"   r#   rl     s    
 	


 	
r!   r#   c                :   > [         TU ]  X4US9  Xl        X l        g r%   )r)   r*   rm   rn   )r+   rm   rn   r&   r'   r(   r,   s         r"   r*   Erasing.__init__  s!     	d1=

r!   c                R  ^^ US   SS u  mmTT-  nX0R                   S   -  nX0R                   S   -  nU R                  u  pgSU4S jjnSU4S jjn	[        U" U5      U" U5      5      n
[        U	" U5      U	" U5      5      n[        XJU5      nX:  a4  S[        R                  " / [        R
                  S	9R                  S
5      0$ U R                  R                  X\5      n[        UTT-  U-  5      n[        XmTT-  -  5      nX:  a4  S[        R                  " / [        R
                  S	9R                  S
5      0$ U R                  R                  X5      n[        [        R                  " UU-  5      5      n[        [        R                  " UU-  5      5      nU R                  R                  STU-
  5      nU R                  R                  STU-
  5      n[        R                  " UUUU-   UU-   //[        R
                  S	9nUU R                  R                  SS5      S.$ )u4  Calculate erasing parameters using direct mathematical derivation.

Given:
- Image dimensions (H, W)
- Target area (A)
- Aspect ratio (r = w/h)

We know:
- h * w = A (area equation)
- w = r * h (aspect ratio equation)

Therefore:
- h * (r * h) = A
- h² = A/r
- h = sqrt(A/r)
- w = r * sqrt(A/r) = sqrt(A*r)
rG   Nr/   r0   r   c                   > U T-  T-  $ Nr   )rr<   s    r"   area_constraint_h?Erasing.get_params_dependent_on_data.<locals>.area_constraint_h9  s    v:&&r!   c                   > TT-  U -  $ rs   r   )rt   r=   s    r"   area_constraint_w?Erasing.get_params_dependent_on_data.<locals>.area_constraint_w<  s    5=1$$r!   rL   dtyper      rJ   rK   )rt   rb   rc   rb   )rm   rn   r3   rP   arrayint32reshaperN   r7   maxroundsqrtrO   r4   r5   )r+   rR   rS   
total_areamax_areamin_arear_minr_maxru   rx   
max_area_h
max_area_wmax_valid_area
erase_areamax_rmin_raspect_ratiohwtopleftrL   r<   r=   s                         @@r"   rY   $Erasing.get_params_dependent_on_data  s   $ w+e^
 

1-

1-
 zz	'	% *513DU3KL
*513DU3KL
X:>$RXXb9AA&IJJ ^^++HE
 E55=:56E&9:=RXXb9AA&IJJ~~--e; "''*|345"''*|345 nn$$Q
3~~%%a34dQha89J(=(=(F(Fq)(TUUr!   )rn   rm   ))g{Gz?gQ?)g333333?gffffff
@r   Nr]   )
rm   tuple[float, float]rn   r   r&   r`   r'   ra   r(   rb   rd   )r   r   r   r   rf   r	   r#   r*   rY   r    rg   rh   s   @r"   r   r      su    <|

[++ 

 &2%/op6:" # m	
 4  AV AVr!   r   c                     ^  \ rS rSrSr " S S\R                  5      r        S	               S
U 4S jjjrSS jrSS jr	Sr
U =r$ )r   i_  a  Applies coarse dropout to regions containing specific objects in the image.

This augmentation creates holes (dropout regions) for each target object in the image.
Objects can be specified either by their class indices in a segmentation mask or
by their labels in bounding box annotations.

The hole generation differs between mask and box modes:

Mask mode:
1. For each connected component in the mask matching target indices:
    - Samples N points randomly from within the object region (with replacement)
    - Creates holes centered at these points
    - Hole sizes are proportional to sqrt(component area), not total object area
    - Each component's holes are sized based on its own area

Box mode:
1. For each bounding box matching target labels:
    - Creates N holes with random positions inside the box
    - Hole sizes are proportional to the box dimensions

In both modes:
- N is sampled once from num_holes_range and used for all objects
- For example, if num_holes_range=(2,4) and 3 is sampled:
    * With 3 target objects, you'll get exactly 3 holes per object (9 total)
    * Holes may overlap within or between objects
    * All holes are clipped to image boundaries

Args:
    num_holes_range (tuple[int, int]): Range for number of holes per object (min, max)
    hole_height_range (tuple[float, float]): Range for hole height as proportion
        of object height/size (min, max). E.g., (0.2, 0.4) means:
        - For boxes: 20-40% of box height
        - For masks: 20-40% of sqrt(component area)
    hole_width_range (tuple[float, float]): Range for hole width, similar to height
    fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
        Value used to fill the erased regions. Can be:
        - int or float: fills all channels with this value
        - tuple: fills each channel with corresponding value
        - "random": fills each pixel with random values
        - "random_uniform": fills entire erased region with a single random color
        - "inpaint_telea": uses OpenCV Telea inpainting method
        - "inpaint_ns": uses OpenCV Navier-Stokes inpainting method
        Default: 0
    fill_mask (tuple[float, float] | float | None): Value used to fill erased regions in the mask.
        If None, mask regions are not modified. Default: None
    p (float): Probability of applying the transform
    mask_indices (List[int], optional): List of class indices in segmentation mask to target.
        Only objects of these classes will be considered for hole placement.
    bbox_labels (List[str | int | float], optional): List of object labels in bbox
        annotations to target. String labels will be automatically encoded.
        When multiple label fields are specified in BboxParams, only the first
        label field is used for filtering.

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

Image types:
    uint8, float32

Requires one of:
    - 'mask' key with segmentation mask where:
        * 0 represents background
        * Non-zero values represent different object instances/classes
        * Values must correspond to mask_indices
    - 'bboxes' key with bounding boxes in format [x_min, y_min, x_max, y_max, label, ...]

Note:
    At least one of mask_indices or bbox_labels must be provided.
    If both are provided, mask_indices takes precedence.

Examples:
    >>> # Using segmentation mask
    >>> transform = ConstrainedCoarseDropout(
    ...     num_holes_range=(2, 4),        # 2-4 holes per object
    ...     hole_height_range=(0.2, 0.4),  # 20-40% of sqrt(object area)
    ...     hole_width_range=(0.2, 0.4),   # 20-40% of sqrt(object area)
    ...     mask_indices=[1, 2],           # Target objects of class 1 and 2
    ...     fill=0,                        # Fill holes with black
    ... )
    >>> # Apply to image and its segmentation mask
    >>> transformed = transform(image=image, mask=mask)

    >>> # Using bounding boxes with Compose
    >>> transform = A.Compose([
    ...     ConstrainedCoarseDropout(
    ...         num_holes_range=(1, 3),
    ...         hole_height_range=(0.3, 0.5),  # 30-50% of box height
    ...         hole_width_range=(0.3, 0.5),   # 30-50% of box width
    ...         bbox_labels=['person'],        # Target people
    ...         fill=127,                      # Fill holes with gray
    ...     )
    ... ], bbox_params=A.BboxParams(
    ...     format='pascal_voc',  # [x_min, y_min, x_max, y_max]
    ...     label_fields=['labels']  # Specify field containing labels
    ... ))
    >>> # Apply to image and its bounding boxes
    >>> transformed = transform(
    ...     image=image,
    ...     bboxes=[[0, 0, 100, 100, 'car'], [150, 150, 300, 300, 'person']],
    ...     labels=['car', 'person']
    ... )

c                  L    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	rS
\S'   Srg	)#ConstrainedCoarseDropout.InitSchemai  r   r   zkAnnotated[tuple[float, float], AfterValidator(nondecreasing), AfterValidator(check_range_bounds(0.0, 1.0))]r   r   zHAnnotated[list[int] | None, AfterValidator(check_range_bounds(1, None))]mask_indicesNlist[str | int | float] | Nonebbox_labelsr   )r   r   r   r   r   r   r    r   r!   r"   r#   r     s7    
 	

 	

 	

 	

 7;3:r!   r#   c	                ^   > [         T	U ]  XEUS9  Xl        X l        X0l        Xpl        Xl        g r%   )r)   r*   r   r   r   r   r   )
r+   r   r   r   r&   r'   r(   r   r   r,   s
            r"   r*   !ConstrainedCoarseDropout.__init__  s5     	d1=.!2 0(&r!   c                f   [        U5      S:X  d  U R                  c  gU R                  S5      nUc  g[        S U R                   5       5      (       d  UR                  R
                  nUc  [        S5      eUS   nUR                  R                  S   U   nUR                  c  [        SU 35      eUR                  R                  U R                  5      nO [        R                  " U R                  5      n[        R                  " USS2S4   U5      nXSS24   n[        U5      S:  a  U$ S$ )ztGet bounding boxes that match specified labels.

Uses BboxProcessor's label encoder if bbox_labels contain strings.
r   Nbboxesc              3  N   #    U  H  n[        U[        [        45      v   M     g 7frs   )
isinstancer6   rb   ).0labels     r"   	<genexpr>AConstrainedCoarseDropout.get_boxes_from_bboxes.<locals>.<genexpr>  s      Q@Pu:ec5\22@Ps   #%zBBboxParams.label_fields must be specified when using string labelsz!No encoder found for label field r}   )lenr   get_processorallrR   label_fields
ValueErrorlabel_managermetadataencoder	transformrP   r~   isin)	r+   r   bbox_processorr   first_class_labelr   target_labelsmaskfiltered_boxess	            r"   get_boxes_from_bboxes.ConstrainedCoarseDropout.get_boxes_from_bboxes  s+   
 v;!t//7 ++H5!Q@P@PQQQ)00==L# !eff ,Q%33<<XFGXYH' #DEVDW!XYY$,,66t7G7GHMHHT%5%56M wwvad|]3bqb)!$^!4q!8~BdBr!   c                   U R                   R                  " U R                  6 nU R                  bM  SU;   aG  [        R
                  " US   UU R                  U R                  U R                  U R                  5      nOU R                  b  SU;   a  U R                  US   5      nUc3  [        R                  " / [        R                  S9R                  S5      nO[        XRS   R                   SS 5      n[        R"                  " UUU R                  U R                  U R                  5      nO<[%        SSS	9  [        R                  " / [        R                  S9R                  S5      nUU R                  R'                  S
S5      S.$ )z@Get hole parameters based on either mask indices or bbox labels.Nr   r   rz   r|   imager/   zONeither valid mask nor bboxes provided, do not apply Constrained Coarse Dropout)
stacklevelr   rJ   rK   )rN   rO   r   r   fdropoutget_holes_from_maskr   r   r4   r   r   rP   r~   r   r   r
   rG   get_holes_from_boxesr   r5   )r+   rR   rS   num_holes_per_objrL   target_boxess         r"   rY   5ConstrainedCoarseDropout.get_params_dependent_on_data  s[    NN22D4H4HI(Vt^00V!!!&&%%%%E )h$.>55d8nEL#2884<<VD1,W@S@STVUV@WX 55 %**)))) bopqHHRrxx088@E ))221i@
 	
r!   )r   r   r   r   r   ))r0   r0   r\   r\   r   r   Nr]   NN)r   r^   r   r   r   r   r&   r`   r'   ra   r(   rb   r   zlist[int] | Noner   r   )r   z
np.ndarrayrc   znp.ndarray | Nonerd   )r   r   r   r   rf   r	   r#   r*   r   rY   r    rg   rh   s   @r"   r   r   _  s    fP;[++ ;8 ,21;0:op6:)-6:'(' /' .	'
 m' 4' ' '' 4' '$ CD!
 !
r!   r   )rf   
__future__r   typingr   r   r   warningsr   numpyrP   pydanticr   /albumentations.augmentations.dropout.functionalaugmentationsdropout
functionalr   /albumentations.augmentations.dropout.transformsr	   albumentations.core.bbox_utilsr
   albumentations.core.pydanticr   r   __all__r   r   r   r   r!   r"   <module>r      sb    # * *   # B B G = J
BfVK fVRYVk YVxX
{ X
r!   