
    hC                   b   S r SSKJr  SSKrSSKJr  SSKJrJrJ	r	J
r
Jr  SSKrSSKrSSKJrJrJr  SSKJr  SSKJr  SS	KJrJrJr  SS
KJrJrJrJ r   SSK!J"r"J#r#  SSK$J%r%J&r&J'r'J(r(J)r)  SSK*Jr+  / SQr, " S S\-5      r. " S S\#5      r/ " S S\/5      r0 " S S\05      r1 " S S\05      r2 " S S\05      r3 " S S\/5      r4 " S S\"5      r5 " S S \#5      r6 " S! S"\65      r7 " S# S$\65      r8 " S% S&\/5      r9 " S' S(\/5      r: " S) S*\:5      r; " S+ S,\#5      r< " S- S.\/5      r= " S/ S0\/5      r>g)1a  Transform classes for cropping operations on images and other data types.

This module provides various crop transforms that can be applied to images, masks,
bounding boxes, and keypoints. The transforms include simple cropping, random cropping,
center cropping, cropping near bounding boxes, and other specialized cropping operations
that maintain the integrity of bounding boxes. These transforms are designed to work within
the albumentations pipeline and can be used for data augmentation in computer vision tasks.
    )annotationsN)Sequence)	AnnotatedAnyLiteralUnioncast)AfterValidatorFieldmodel_validator)Self)
functional)denormalize_bboxesnormalize_bboxesunion_of_bboxes)OnePlusIntRangeTypeZeroOneRangeTypecheck_range_boundsnondecreasing)BaseTransformInitSchemaDualTransform)ALL_TARGETSNUM_MULTI_CHANNEL_DIMENSIONSPAIRPercentTypePxType   )AtLeastOneBBoxRandomCropBBoxSafeRandomCrop
CenterCropCrop
CropAndPadCropNonEmptyMaskIfExists
RandomCropRandomCropFromBordersRandomCropNearBBoxRandomResizedCropRandomSizedBBoxSafeCropRandomSizedCropc                      \ rS rSrSrg)CropSizeError8    N)__name__
__module____qualname____firstlineno____static_attributes__r-       g/var/www/fran/franai/venv/lib/python3.13/site-packages/albumentations/augmentations/crops/transforms.pyr+   r+   8   s    r3   r+   c                      \ rS rSrSr\r        SS jr        SS jr        SS jr	        SS jr
        SS jr        SS jr        SS	 jr        SS
 jr\SS j5       rSrg)BaseCrop<   a"  Base class for transforms that only perform cropping.

This abstract class provides the foundation for all cropping transformations.
It handles cropping of different data types including images, masks, bounding boxes,
keypoints, and volumes while keeping their spatial relationships intact.

Child classes must implement the `get_params_dependent_on_data` method to determine
crop coordinates based on transform-specific logic. This method should return a dictionary
containing at least a 'crop_coords' key with a tuple value (x_min, y_min, x_max, y_max).

Args:
    p (float): Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    This class is not meant to be used directly. Instead, use or create derived
    transforms that implement the specific cropping behavior required.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> from albumentations.augmentations.crops.transforms import BaseCrop
    >>>
    >>> # Example of a custom crop transform that inherits from BaseCrop
    >>> class CustomCenterCrop(BaseCrop):
    ...     '''A simple custom center crop with configurable size'''
    ...     def __init__(self, crop_height, crop_width, p=1.0):
    ...         super().__init__(p=p)
    ...         self.crop_height = crop_height
    ...         self.crop_width = crop_width
    ...
    ...     def get_params_dependent_on_data(self, params, data):
    ...         '''Calculate crop coordinates based on center of image'''
    ...         image_height, image_width = params["shape"][:2]
    ...
    ...         # Calculate center crop coordinates
    ...         x_min = max(0, (image_width - self.crop_width) // 2)
    ...         y_min = max(0, (image_height - self.crop_height) // 2)
    ...         x_max = min(image_width, x_min + self.crop_width)
    ...         y_max = min(image_height, y_min + self.crop_height)
    ...
    ...         return {"crop_coords": (x_min, y_min, x_max, y_max)}
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Use the custom transform in a pipeline
    >>> transform = A.Compose(
    ...     [CustomCenterCrop(crop_height=80, crop_width=80)],
    ...     bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...     keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels'])
    ... )
    >>>
    >>> # Apply the transform to data
    >>> result = transform(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> transformed_image = result['image']  # Will be 80x80
    >>> transformed_mask = result['mask']    # Will be 80x80
    >>> transformed_bboxes = result['bboxes']  # Bounding boxes adjusted to the cropped area
    >>> transformed_bbox_labels = result['bbox_labels']  # Labels for bboxes that remain after cropping
    >>> transformed_keypoints = result['keypoints']  # Keypoints adjusted to the cropped area
    >>> transformed_keypoint_labels = result['keypoint_labels']  # Labels for keypoints that remain after cropping

c                H    [         R                  " XS   US   US   US   S9$ )a+  Apply the crop transform to an image.

Args:
    img (np.ndarray): The image to apply the crop transform to.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The cropped image.

r   r         )x_miny_minx_maxy_max)fcropscrop)selfimgcrop_coordsparamss       r4   applyBaseCrop.apply   s/    " {{3!nKNR]^_R`hstuhvwwr3   c                <    [         R                  " XUS   SS 5      $ )aF  Apply the crop transform to bounding boxes.

Args:
    bboxes (np.ndarray): The bounding boxes to apply the crop transform to.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The cropped bounding boxes.

shapeNr9   r?   crop_bboxes_by_coordsrA   bboxesrC   rD   s       r4   apply_to_bboxesBaseCrop.apply_to_bboxes   s$    " ++FQSRSATUUr3   c                .    [         R                  " X5      $ )a:  Apply the crop transform to keypoints.

Args:
    keypoints (np.ndarray): The keypoints to apply the crop transform to.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The cropped keypoints.

)r?   crop_keypoints_by_coords)rA   	keypointsrC   rD   s       r4   apply_to_keypointsBaseCrop.apply_to_keypoints   s    " ..yFFr3   c                L    [         R                  " XS   US   US   US   5      $ Nr   r   r9   r:   )r?   volume_crop_yx)rA   imagesrC   rD   s       r4   apply_to_imagesBaseCrop.apply_to_images   s/     $$V^[^[YZ^]hij]kllr3   c                (    U R                   " X40 UD6$ NrX   rA   volumerC   rD   s       r4   apply_to_volumeBaseCrop.apply_to_volume        ##FB6BBr3   c                L    [         R                  " XS   US   US   US   5      $ rU   )r?   volumes_crop_yx)rA   volumesrC   rD   s       r4   apply_to_volumesBaseCrop.apply_to_volumes   s/     %%g1~{1~{[\~_jkl_mnnr3   c                (    U R                   " X40 UD6$ r[   r\   rA   mask3drC   rD   s       r4   apply_to_mask3dBaseCrop.apply_to_mask3d   ra   r3   c                (    U R                   " X40 UD6$ r[   re   rA   masks3drC   rD   s       r4   apply_to_masks3dBaseCrop.apply_to_masks3d        $$WDVDDr3   c                    US S u  p#U u  pEpg[         R                  " USU5      n[         R                  " USU5      n[         R                  " XdU5      n[         R                  " XuU5      nXEXg4$ )Nr9   r   )npclip)bboximage_shapeheightwidthr;   r<   r=   r>   s           r4   
_clip_bboxBaseCrop._clip_bbox   sh    #BQ%)"eq%(q&)e,f-U))r3   r-   NrB   
np.ndarrayrC   tuple[int, int, int, int]rD   r   returnr}   rL   r}   rC   r~   rD   r   r   r}   rQ   r}   rC   r~   rD   r   r   r}   rW   r}   rC   r~   rD   r   r   r}   r^   r}   rC   r~   rD   r   r   r}   rd   r}   rC   r~   rD   r   r   r}   ri   r}   rC   r~   rD   r   r   r}   ro   r}   rC   r~   rD   r   r   r}   )rv   r~   rw   tuple[int, int]r   r~   )r.   r/   r0   r1   __doc__r   _targetsrE   rM   rR   rX   r_   re   rj   rp   staticmethodrz   r2   r-   r3   r4   r6   r6   <   s   Qf Hxx /x 	x
 
x&VV /V 	V
 
V&GG /G 	G
 
G&mm /m 	m
 
mCC /C 	C
 
Coo /o 	o
 
oCC /C 	C
 
CEE /E 	E
 
E * *r3   r6   c                  R  ^  \ rS rSrSr " S S\5      r            SU 4S jjrSS jr        SS jr	        SS jr
        SS	 jr        SS
 jr        SS jr        SS jr        SS jr        SS jr        SS jrSrU =r$ )BaseCropAndPad   a  Base class for transforms that need both cropping and padding.

This abstract class extends BaseCrop by adding padding capabilities. It's the foundation
for transforms that may need to both crop parts of the input and add padding, such as when
converting inputs to a specific target size. The class handles the complexities of applying
these operations to different data types (images, masks, bounding boxes, keypoints) while
maintaining their spatial relationships.

Child classes must implement the `get_params_dependent_on_data` method to determine
crop coordinates and padding parameters based on transform-specific logic.

Args:
    pad_if_needed (bool): Whether to pad the input if the crop size exceeds input dimensions.
    border_mode (int): OpenCV border mode used for padding.
    fill (tuple[float, ...] | float): Value to fill the padded area if border_mode is BORDER_CONSTANT.
        For multi-channel images, this can be a tuple with a value for each channel.
    fill_mask (tuple[float, ...] | float): Value to fill the padded area in masks.
    pad_position (Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"]):
        Position of padding when pad_if_needed is True.
    p (float): Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    This class is not meant to be used directly. Instead, use or create derived
    transforms that implement the specific cropping and padding behavior required.

Examples:
    >>> import numpy as np
    >>> import cv2
    >>> import albumentations as A
    >>> from albumentations.augmentations.crops.transforms import BaseCropAndPad
    >>>
    >>> # Example of a custom transform that inherits from BaseCropAndPad
    >>> # This transform crops to a fixed size, padding if needed to maintain dimensions
    >>> class CustomFixedSizeCrop(BaseCropAndPad):
    ...     '''A custom fixed-size crop that pads if needed to maintain output size'''
    ...     def __init__(
    ...         self,
    ...         height=224,
    ...         width=224,
    ...         offset_x=0,  # Offset for crop position
    ...         offset_y=0,  # Offset for crop position
    ...         pad_if_needed=True,
    ...         border_mode=cv2.BORDER_CONSTANT,
    ...         fill=0,
    ...         fill_mask=0,
    ...         pad_position="center",
    ...         p=1.0,
    ...     ):
    ...         super().__init__(
    ...             pad_if_needed=pad_if_needed,
    ...             border_mode=border_mode,
    ...             fill=fill,
    ...             fill_mask=fill_mask,
    ...             pad_position=pad_position,
    ...             p=p,
    ...         )
    ...         self.height = height
    ...         self.width = width
    ...         self.offset_x = offset_x
    ...         self.offset_y = offset_y
    ...
    ...     def get_params_dependent_on_data(self, params, data):
    ...         '''Calculate crop coordinates and padding if needed'''
    ...         image_shape = params["shape"][:2]
    ...         image_height, image_width = image_shape
    ...
    ...         # Calculate crop coordinates with offsets
    ...         x_min = self.offset_x
    ...         y_min = self.offset_y
    ...         x_max = min(x_min + self.width, image_width)
    ...         y_max = min(y_min + self.height, image_height)
    ...
    ...         # Get padding params if needed
    ...         pad_params = self._get_pad_params(
    ...             image_shape,
    ...             (self.height, self.width)
    ...         ) if self.pad_if_needed else None
    ...
    ...         return {
    ...             "crop_coords": (x_min, y_min, x_max, y_max),
    ...             "pad_params": pad_params,
    ...         }
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Use the custom transform in a pipeline
    >>> # This will create a 224x224 crop with padding as needed
    >>> transform = A.Compose(
    ...     [CustomFixedSizeCrop(
    ...         height=224,
    ...         width=224,
    ...         offset_x=20,
    ...         offset_y=10,
    ...         fill=127,  # Gray color for padding
    ...         fill_mask=0
    ...     )],
    ...     bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...     keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform to data
    >>> result = transform(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> transformed_image = result['image']  # Will be 224x224 with padding
    >>> transformed_mask = result['mask']    # Will be 224x224 with padding
    >>> transformed_bboxes = result['bboxes']  # Bounding boxes adjusted to the cropped and padded area
    >>> transformed_bbox_labels = result['bbox_labels']  # Bounding box labels after crop
    >>> transformed_keypoints = result['keypoints']  # Keypoints adjusted to the cropped and padded area
    >>> transformed_keypoint_labels = result['keypoint_labels']  # Keypoint labels after crop

c                  H    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	\S
'   Srg)BaseCropAndPad.InitSchemai  boolpad_if_neededoLiteral[cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101]border_modetuple[float, ...] | floatfill	fill_maskSLiteral['center', 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'random']pad_positionr-   Nr.   r/   r0   r1   __annotations__r2   r-   r3   r4   
InitSchemar     s&    
 	
 (',,iir3   r   c                \   > [         TU ]  US9  Xl        X l        X0l        X@l        XPl        g Np)super__init__r   r   r   r   r   )rA   r   r   r   r   r   r   	__class__s          r4   r   BaseCropAndPad.__init__  s1     	1*&	"(r3   c           	        U R                   (       d  g[        R                  " UUS   US   SSS9u  p4pVX4s=:X  a  Us=:X  a  Us=:X  a  S:X  a   g  [        R                  " UUUUU R                  U R
                  S9u  p4pVUUUUS.$ )z'Calculate padding parameters if needed.Nr   r   )rw   
min_height	min_widthpad_height_divisorpad_width_divisorh_toph_bottomw_leftw_rightposition	py_randompad_top
pad_bottompad_left	pad_right)r   
fgeometricget_padding_paramsadjust_padding_by_positionr   r   )rA   rw   target_shape	h_pad_toph_pad_bottom
w_pad_leftw_pad_rights          r4   _get_pad_paramsBaseCropAndPad._get_pad_params  s    !!;E;X;X##A"1o#"<
8	 F
FkFQF G <F;`;`!&&nn<
8	 !&"$	
 	
r3   c           
         UR                  S5      nUb:  [        R                  " UUS   US   US   US   U R                  U R                  S9n[
        R                  " XU40 UD6$ )aF  Apply the crop and pad transform to an image.

Args:
    img (np.ndarray): The image to apply the crop and pad transform to.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The cropped and padded image.


pad_paramsr   r   r   r   r   value)getr   pad_with_paramsr   r   r6   rE   )rA   rB   rC   rD   r   s        r4   rE   BaseCropAndPad.apply  ss    " ZZ-
!,,9%<(:&;' ,,iiC ~~d???r3   c           
         UR                  S5      nUb:  [        R                  " UUS   US   US   US   U R                  U R                  S9n[
        R                  " X4SU0UD6$ )aC  Apply the crop and pad transform to a mask.

Args:
    mask (np.ndarray): The mask to apply the crop and pad transform to.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The cropped and padded mask.

r   r   r   r   r   r   rC   )r   r   r   r   r   r6   rE   )rA   maskrC   rD   r   s        r4   apply_to_maskBaseCropAndPad.apply_to_mask  sv    " ZZ-
!--9%<(:&;' ,,nnD ~~dLkLVLLr3   c                    UR                  S5      nUb<  [        R                  " UUS   US   US   US   SSU R                  U R                  S9	n[
        R                  " XU40 UD6$ )	Nr   r   r   r   r   r9   r:   h_axisw_axisr   	pad_value)r   r?   pad_along_axesr   r   r6   rX   )rA   rW   rC   rD   r   s        r4   rX   BaseCropAndPad.apply_to_images  s{     ZZ-
!**9%<(:&;' ,,))
F ''kLVLLr3   c                (    U R                   " X40 UD6$ r[   r\   r]   s       r4   r_   BaseCropAndPad.apply_to_volume  ra   r3   c                    UR                  S5      nUb<  [        R                  " UUS   US   US   US   SSU R                  U R                  S9	n[
        R                  " XU40 UD6$ )	Nr   r   r   r   r   r:      r   )r   r?   r   r   r   r6   re   )rA   rd   rC   rD   r   s        r4   re   BaseCropAndPad.apply_to_volumes   s{     ZZ-
!++9%<(:&;' ,,))
G ((NvNNr3   c                (    U R                   " X40 UD6$ r[   r\   rh   s       r4   rj   BaseCropAndPad.apply_to_mask3d5  ra   r3   c                (    U R                   " X40 UD6$ r[   rm   rn   s       r4   rp   BaseCropAndPad.apply_to_masks3d=  rr   r3   c           
     x   UR                  S5      nUS   SS nUb  [        X5      n[        R                  " UUS   US   US   US   U R                  US	9nUS
   US   -   US   -   nUS   US   -   US   -   nXx4n	[        Xi5      nXS'   [        R                  " XU40 UD6$ [        R                  " XU40 UD6$ )aa  Apply the crop and pad transform to bounding boxes.

Args:
    bboxes (np.ndarray): The bounding boxes to apply the crop and pad transform to.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The cropped and padded bounding boxes.

r   rH   Nr9   r   r   r   r   rw   r   r   )r   r   r   
pad_bboxesr   r   r6   rM   )
rA   rL   rC   rD   r   rw   	bboxes_nppadded_heightpadded_widthpadded_shapes
             r4   rM   BaseCropAndPad.apply_to_bboxesE  s    " ZZ-
Wobq)!*6?I #--9%<(:&;'  'I (NZ	-BBZP\E]]M&q>Jz,BBZP[E\\L)8L(AI*7O++D[SFSS ''kLVLLr3   c           
         UR                  S5      nUS   SS nUb[  US   US   -   US   -   nUS   US	   -   US
   -   n[        R                  " UUS   US   US	   US
   U R                  US9n0 UESXg40En[        R
                  " XU40 UD6$ )aU  Apply the crop and pad transform to keypoints.

Args:
    keypoints (np.ndarray): The keypoints to apply the crop and pad transform to.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The cropped and padded keypoints.

r   rH   Nr9   r   r   r   r   r   r   r   )r   r   pad_keypointsr   r6   rR   )rA   rQ   rC   rD   r   rw   r   r   s           r4   rR   !BaseCropAndPad.apply_to_keypointsv  s    " ZZ-
Wobq)!'NZ	-BBZP\E]]M&q>Jz,BBZP[E\\L #009%<(:&;'  'I HG-)FGF**4KR6RRr3   )r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   float)rw   r   r   r   r   zdict[str, Any] | Noner|   )r   r}   rC   r   rD   r   r   r}   r   r   r   r   r   r   r   )r.   r/   r0   r1   r   r   r   r   r   rE   r   rX   r_   re   rj   rp   rM   rR   r2   __classcell__r   s   @r4   r   r      s   AFj, j))
) () -) j) ),
@@@ /@ 	@
 
@<MM M 	M
 
M>MM /M 	M
 
M*CC /C 	C
 
COO /O 	O
 
O*CC /C 	C
 
CEE /E 	E
 
E/M/M //M 	/M
 
/Mb'S'S /'S 	'S
 
'S 'Sr3   r   c                     ^  \ rS rSrSr " S S\R                  5      rSS\R                  SSS4               SU 4S	 jjjr	      SS
 jr
SrU =r$ )r$   i  aT  Crop a random part of the input.

Args:
    height (int): height of the crop.
    width (int): width of the crop.
    pad_if_needed (bool): Whether to pad if crop size exceeds image size. Default: False.
    border_mode (OpenCV flag): OpenCV border mode used for padding. Default: cv2.BORDER_CONSTANT.
    fill (tuple[float, ...] | float): Padding value for images if border_mode is
        cv2.BORDER_CONSTANT. Default: 0.
    fill_mask (tuple[float, ...] | float): Padding value for masks if border_mode is
        cv2.BORDER_CONSTANT. Default: 0.
    pad_position (Literal['center', 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'random']):
        Position of padding. Default: 'center'.
    p (float): Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    If pad_if_needed is True and crop size exceeds image dimensions, the image will be padded
    before applying the random crop.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Example 1: Basic random crop
    >>> transform = A.Compose([
    ...     A.RandomCrop(height=64, width=64),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # 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']  # Will be 64x64
    >>> transformed_mask = transformed['mask']    # Will be 64x64
    >>> transformed_bboxes = transformed['bboxes']  # Bounding boxes adjusted to the cropped area
    >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels for boxes that remain after cropping
    >>> transformed_keypoints = transformed['keypoints']  # Keypoints adjusted to the cropped area
    >>> transformed_keypoint_labels = transformed['keypoint_labels']  # Labels for keypoints that remain
    >>>
    >>> # Example 2: Random crop with padding when needed
    >>> # This is useful when you want to crop to a size larger than some images
    >>> transform_padded = A.Compose([
    ...     A.RandomCrop(
    ...         height=120,  # Larger than original image height
    ...         width=120,   # Larger than original image width
    ...         pad_if_needed=True,
    ...         border_mode=cv2.BORDER_CONSTANT,
    ...         fill=0,      # Black padding for image
    ...         fill_mask=0  # Zero padding for mask
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the padded transform
    >>> padded_transformed = transform_padded(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # The result will be 120x120 with padding
    >>> padded_image = padded_transformed['image']
    >>> padded_mask = padded_transformed['mask']
    >>> padded_bboxes = padded_transformed['bboxes']  # Coordinates adjusted to the new dimensions

c                  H    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S	'   S
rg)RandomCrop.InitSchemai  Annotated[int, Field(ge=1)]rx   ry   r   r   r   r   r   r-   Nr   r-   r3   r4   r   r     &    ++**
 	
 (',,r3   r   Fcenter              ?c	           	     B   > [         T	U ]  UUUUUUS9  Xl        X l        g N)r   r   r   r   r   r   r   r   rx   ry   
rA   rx   ry   r   r   r   r   r   r   r   s
            r4   r   RandomCrop.__init__  5    " 	'#% 	 	
 
r3   c                   US   SS nUu  pEU R                   (       dJ  U R                  U:  d  U R                  U:  a*  [        SU R                  U R                  4 SUSS  35      eU R	                  X0R                  U R                  45      nUb  US   nUS   nUS   n	US	   n
XG-   U-   nXY-   U
-   nX4nU R
                  R                  5       nU R
                  R                  5       n[        R                  " XR                  U R                  4X5      nOaU R
                  R                  5       nU R
                  R                  5       n[        R                  " X0R                  U R                  4X5      nUUS
.$ )zGet parameters that depend on input data.

Args:
    params (dict[str, Any]): Parameters.
    data (dict[str, Any]): Input data.

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

rH   Nr9   DCrop size (height, width) exceeds image dimensions (height, width):  vs r   r   r   r   rC   r   )	r   rx   ry   r+   r   r   randomr?   get_crop_coords)rA   rD   datarw   image_heightimage_widthr   r   r   r   r   r   r   r   h_startw_startrC   s                    r4   get_params_dependent_on_data'RandomCrop.get_params_dependent_on_data(  s    Wobq)$/!!!t{{\'ATZZR]E][[$**-.d;r?2CE  ))+TZZ7PQ
 ! +G#L1J!*-H";/I(2Z?M&1I=L)8L nn++-Gnn++-G 00TZZ?XZakK nn++-Gnn++-G 00{{DJJ>WY`jK '$
 	
r3   rx   ry   rx   intry   r  r   r   r   r   r   r   r   r   r   r   r   r   rD   dict[str, Any]r   r  r   r  r.   r/   r0   r1   r   r   r   cv2BORDER_CONSTANTr   r  r2   r   r   s   @r4   r$   r$     s    [z-^.. -$ $lt *-/2  	
 j
 ( -  83
3
 3
 
	3
 3
r3   r$   c                     ^  \ rS rSrSr " S S\R                  5      rSS\R                  SSS4               SU 4S	 jjjr	      SS
 jr
SrU =r$ )r    i^  aJ  Crop the central part of the input.

This transform crops the center of the input image, mask, bounding boxes, and keypoints to the specified dimensions.
It's useful when you want to focus on the central region of the input, discarding peripheral information.

Args:
    height (int): The height of the crop. Must be greater than 0.
    width (int): The width of the crop. Must be greater than 0.
    pad_if_needed (bool): Whether to pad if crop size exceeds image size. Default: False.
    border_mode (OpenCV flag): OpenCV border mode used for padding. Default: cv2.BORDER_CONSTANT.
    fill (tuple[float, ...] | float): Padding value for images if border_mode is
        cv2.BORDER_CONSTANT. Default: 0.
    fill_mask (tuple[float, ...] | float): Padding value for masks if border_mode is
        cv2.BORDER_CONSTANT. Default: 0.
    pad_position (Literal['center', 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'random']):
        Position of padding. Default: 'center'.
    p (float): Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    - If pad_if_needed is False and crop size exceeds image dimensions, it will raise a CropSizeError.
    - If pad_if_needed is True and crop size exceeds image dimensions, the image will be padded.
    - For bounding boxes and keypoints, coordinates are adjusted appropriately for both padding and cropping.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Example 1: Basic center crop without padding
    >>> transform = A.Compose([
    ...     A.CenterCrop(height=64, width=64),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # 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']  # Will be 64x64
    >>> transformed_mask = transformed['mask']    # Will be 64x64
    >>> transformed_bboxes = transformed['bboxes']  # Bounding boxes adjusted to the cropped area
    >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels for boxes that remain after cropping
    >>> transformed_keypoints = transformed['keypoints']  # Keypoints adjusted to the cropped area
    >>> transformed_keypoint_labels = transformed['keypoint_labels']  # Labels for keypoints that remain
    >>>
    >>> # Example 2: Center crop with padding when needed
    >>> transform_padded = A.Compose([
    ...     A.CenterCrop(
    ...         height=120,  # Larger than original image height
    ...         width=120,   # Larger than original image width
    ...         pad_if_needed=True,
    ...         border_mode=cv2.BORDER_CONSTANT,
    ...         fill=0,      # Black padding for image
    ...         fill_mask=0  # Zero padding for mask
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the padded transform
    >>> padded_transformed = transform_padded(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # The result will be 120x120 with padding
    >>> padded_image = padded_transformed['image']
    >>> padded_mask = padded_transformed['mask']
    >>> padded_bboxes = padded_transformed['bboxes']  # Coordinates adjusted to the new dimensions
    >>> padded_keypoints = padded_transformed['keypoints']  # Coordinates adjusted to the new dimensions

c                  H    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S	'   S
rg)CenterCrop.InitSchemai  r   rx   ry   r   r   r   r   r   r-   Nr   r-   r3   r4   r   r    r   r3   r   Fr   r   r   c	           	     B   > [         T	U ]  UUUUUUS9  Xl        X l        g r   r   r   s
            r4   r   CenterCrop.__init__  r   r3   c                *   US   SS nUu  pEU R                   (       dJ  U R                  U:  d  U R                  U:  a*  [        SU R                  U R                  4 SUSS  35      eU R	                  X0R                  U R                  45      nUbR  US   nUS   nUS   n	US	   n
XG-   U-   nXY-   U
-   nX4n[
        R                  " XR                  U R                  45      nO,[
        R                  " X0R                  U R                  45      nUUS
.$ )Get the parameters dependent on the data.

Args:
    params (dict[str, Any]): The parameters of the transform.
    data (dict[str, Any]): The data of the transform.

rH   Nr9   r   r   r   r   r   r   r   )r   rx   ry   r+   r   r?   get_center_crop_coords)rA   rD   r   rw   r   r   r   r   r   r   r   r   r   r   rC   s                  r4   r  'CenterCrop.get_params_dependent_on_data  s;    Wobq)$/!!!t{{\'ATZZR]E][[$**-.d;r?2CE  ))+TZZ7PQ
 ! +G#L1J!*-H";/I(2Z?M&1I=L)8L !77{{TXT^T^F_`K !77kkSWS]S]E^_K '$
 	
r3   r  r  r  r  r   s   @r4   r    r    ^  s    _B-^.. -$ $lt *-/2  	
 j
 ( -  8,
,
 ,
 
	,
 ,
r3   r    c            
         ^  \ rS rSrSr " S S\R                  5      rSSSSSS\R                  SSS	4
                   SU 4S
 jjjr	SS jr
SS jrSS jrSrU =r$ )r!   i  a  Crop a specific region from the input image.

This transform crops a rectangular region from the input image, mask, bounding boxes, and keypoints
based on specified coordinates. It's useful when you want to extract a specific area of interest
from your inputs.

Args:
    x_min (int): Minimum x-coordinate of the crop region (left edge). Must be >= 0. Default: 0.
    y_min (int): Minimum y-coordinate of the crop region (top edge). Must be >= 0. Default: 0.
    x_max (int): Maximum x-coordinate of the crop region (right edge). Must be > x_min. Default: 1024.
    y_max (int): Maximum y-coordinate of the crop region (bottom edge). Must be > y_min. Default: 1024.
    pad_if_needed (bool): Whether to pad if crop coordinates exceed image dimensions. Default: False.
    border_mode (OpenCV flag): OpenCV border mode used for padding. Default: cv2.BORDER_CONSTANT.
    fill (tuple[float, ...] | float): Padding value if border_mode is cv2.BORDER_CONSTANT. Default: 0.
    fill_mask (tuple[float, ...] | float): Padding value for masks. Default: 0.
    pad_position (Literal['center', 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'random']):
        Position of padding. Default: 'center'.
    p (float): Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    - The crop coordinates are applied as follows: x_min <= x < x_max and y_min <= y < y_max.
    - If pad_if_needed is False and crop region extends beyond image boundaries, it will be clipped.
    - If pad_if_needed is True, image will be padded to accommodate the full crop region.
    - For bounding boxes and keypoints, coordinates are adjusted appropriately for both padding and cropping.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Example 1: Basic crop with fixed coordinates
    >>> transform = A.Compose([
    ...     A.Crop(x_min=20, y_min=20, x_max=80, y_max=80),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # 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']  # Will be 60x60 - cropped from (20,20) to (80,80)
    >>> transformed_mask = transformed['mask']    # Will be 60x60
    >>> transformed_bboxes = transformed['bboxes']  # Bounding boxes adjusted to the cropped area
    >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels for boxes that remain after cropping
    >>>
    >>> # Example 2: Crop with padding when the crop region extends beyond image dimensions
    >>> transform_padded = A.Compose([
    ...     A.Crop(
    ...         x_min=50, y_min=50, x_max=150, y_max=150,  # Extends beyond the 100x100 image
    ...         pad_if_needed=True,
    ...         border_mode=cv2.BORDER_CONSTANT,
    ...         fill=0,      # Black padding for image
    ...         fill_mask=0  # Zero padding for mask
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the padded transform
    >>> padded_transformed = transform_padded(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # The result will be 100x100 (50:150, 50:150) with padding on right and bottom
    >>> padded_image = padded_transformed['image']  # 100x100 with 50 pixels of original + 50 pixels of padding
    >>> padded_mask = padded_transformed['mask']
    >>> padded_bboxes = padded_transformed['bboxes']  # Coordinates adjusted to the cropped and padded area
    >>>
    >>> # Example 3: Crop with reflection padding and custom position
    >>> transform_reflect = A.Compose([
    ...     A.Crop(
    ...         x_min=-20, y_min=-20, x_max=80, y_max=80,  # Negative coordinates (outside image)
    ...         pad_if_needed=True,
    ...         border_mode=cv2.BORDER_REFLECT_101,  # Reflect image for padding
    ...         pad_position="top_left"  # Apply padding at top-left
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
    >>>
    >>> # The resulting crop will use reflection padding for the negative coordinates
    >>> reflect_result = transform_reflect(
    ...     image=image,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels
    ... )

c                  x    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S	'   S
\S'   S
\S'   \" SS9SS j5       rSrg)Crop.InitSchemai  zAnnotated[int, Field(ge=0)]r;   r<   zAnnotated[int, Field(gt=0)]r=   r>   r   r   r   r   r   aftermodec                    U R                   U R                  :  d  Sn[        U5      eU R                  U R                  :  d  Sn[        U5      eU $ )Nz x_max must be greater than x_minz y_max must be greater than y_min)r;   r=   
ValueErrorr<   r>   rA   msgs     r4   _validate_coordinates%Crop.InitSchema._validate_coordinates  sE    ::

*8 o%::

*8 o%Kr3   r-   Nr   r   )r.   r/   r0   r1   r   r   r  r2   r-   r3   r4   r   r    sI    ********
 	
 (',,	g	&	 
'	r3   r   r   i   Fr   r   c           	     Z   > [         TU ]  UUUU	UU
S9  Xl        X l        X0l        X@l        g r   )r   r   r;   r<   r=   r>   )rA   r;   r<   r=   r>   r   r   r   r   r   r   r   s              r4   r   Crop.__init__  s?    & 	'#% 	 	
 



r3   c                v    Sn[        SU R                  U-
  5      nSn[        SU R                  U-
  5      nX4XV4$ )Nr   )maxr>   r=   )rA   r   r   r   r   r   r   s          r4   _compute_min_paddingCrop._compute_min_padding  sA    DJJ56
4::34	H77r3   c           	         X-   nX4-   nUS-  nXW-
  nUS-  n	Xi-
  n
[         R                  " UUU	U
U R                  U R                  S9u  pp[	        X5      n[	        X5      n[	        X5      n[	        X5      nUUUUS.$ )Nr9   r   r   )r   r   r   r   r$  )rA   r   r   r   r   delta_hdelta_wpad_top_distpad_bottom_distpad_left_distpad_right_distpad_top_adjpad_bottom_adjpad_left_adjpad_right_adj	final_topfinal_bottom
final_leftfinal_rights                      r4   _compute_adjusted_paddingCrop._compute_adjusted_padding  s    &&!|!01 0EOEjEj$ "&&nnF
Bl -	>60
-3 !&"$	
 	
r3   c                t   US   SS nUu  pEU R                   (       d1  U R                  U R                  U R                  U R                  4SS.$ U R                  XE5      u  pgpSn
[        XgX/5      (       a  U R                  XgX5      n
U R                  U R                  U R                  U R                  4U
S.$ )zGet parameters for crop.

Args:
    params (dict): Dictionary with parameters for crop.
    data (dict): Dictionary with data.

Returns:
    dict: Dictionary with parameters for crop.

rH   Nr9   r   )r   r;   r<   r=   r>   r%  anyr6  )rA   rD   r   rw   r   r   r   r   r   r   r   s              r4   r  !Crop.get_params_dependent_on_data  s     Wobq)$/!!!$(JJ

DJJ

#Scghh373L3L\3g0X
X9::77XaJ $

DJJ

DJJO_ijjr3   )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  r   r  r   zdict[str, int]r  )r.   r/   r0   r1   r   r   r   r	  r
  r   r%  r6  r  r2   r   r   s   @r4   r!   r!     s    n`^.. : #lt *+/0#  	
   j
 (  -!" # B8
:k kr3   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  aR  Crop area with mask if mask is non-empty, else make random crop.

This transform attempts to crop a region containing a mask (non-zero pixels). If the mask is empty or not provided,
it falls back to a random crop. This is particularly useful for segmentation tasks where you want to focus on
regions of interest defined by the mask.

Args:
    height (int): Vertical size of crop in pixels. Must be > 0.
    width (int): Horizontal size of crop in pixels. Must be > 0.
    ignore_values (list of int, optional): Values to ignore in mask, `0` values are always ignored.
        For example, if background value is 5, set `ignore_values=[5]` to ignore it. Default: None.
    ignore_channels (list of int, optional): Channels to ignore in mask.
        For example, if background is the first channel, set `ignore_channels=[0]` to ignore it. Default: None.
    p (float): Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    - If a mask is provided, the transform will try to crop an area containing non-zero (or non-ignored) pixels.
    - If no suitable area is found in the mask or no mask is provided, it will perform a random crop.
    - The crop size (height, width) must not exceed the original image dimensions.
    - Bounding boxes and keypoints are also cropped along with the image and mask.

Raises:
    ValueError: If the specified crop size is larger than the input image dimensions.

Example:
    >>> import numpy as np
    >>> import albumentations as A
    >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
    >>> mask = np.zeros((100, 100), dtype=np.uint8)
    >>> mask[25:75, 25:75] = 1  # Create a non-empty region in the mask
    >>> transform = A.Compose([
    ...     A.CropNonEmptyMaskIfExists(height=50, width=50, p=1.0),
    ... ])
    >>> transformed = transform(image=image, mask=mask)
    >>> transformed_image = transformed['image']
    >>> transformed_mask = transformed['mask']
    # The resulting crop will likely include part of the non-zero region in the mask

Raises:
    ValueError: If the specified crop size is larger than the input image dimensions.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>>
    >>> # Prepare sample data
    >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
    >>> # Create a mask with non-empty region in the center
    >>> mask = np.zeros((100, 100), dtype=np.uint8)
    >>> mask[25:75, 25:75] = 1  # Create a non-empty region in the mask
    >>>
    >>> # Create bounding boxes and keypoints in the mask region
    >>> bboxes = np.array([
    ...     [20, 20, 60, 60],     # Box overlapping with non-empty region
    ...     [30, 30, 70, 70],     # Box mostly inside non-empty region
    ... ], dtype=np.float32)
    >>> bbox_labels = ['cat', 'dog']
    >>>
    >>> # Add some keypoints inside mask region
    >>> keypoints = np.array([
    ...     [40, 40],             # Inside non-empty region
    ...     [60, 60],             # At edge of non-empty region
    ...     [90, 90]              # Outside non-empty region
    ... ], dtype=np.float32)
    >>> keypoint_labels = ['eye', 'nose', 'ear']
    >>>
    >>> # Define transform that will crop around the non-empty mask region
    >>> transform = A.Compose([
    ...     A.CropNonEmptyMaskIfExists(
    ...         height=50,
    ...         width=50,
    ...         ignore_values=None,
    ...         ignore_channels=None,
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(
    ...     format='pascal_voc',
    ...     label_fields=['bbox_labels']
    ... ), keypoint_params=A.KeypointParams(
    ...     format='xy',
    ...     label_fields=['keypoint_labels']
    ... ))
    >>>
    >>> # 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']  # 50x50 image centered on mask region
    >>> transformed_mask = transformed['mask']    # 50x50 mask showing part of non-empty region
    >>> transformed_bboxes = transformed['bboxes']  # Bounding boxes adjusted to new coordinates
    >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels preserved for visible boxes
    >>> transformed_keypoints = transformed['keypoints']  # Keypoints adjusted to new coordinates
    >>> transformed_keypoint_labels = transformed['keypoint_labels']  # Labels for visible keypoints

c                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S'   Srg	)
#CropNonEmptyMaskIfExists.InitSchemais  list[int] | Noneignore_valuesignore_channelsr   rx   ry   r-   Nr   r-   r3   r4   r   r=  s  s    ''))++**r3   r   c                P   > [         TU ]  US9  Xl        X l        X0l        X@l        g r   )r   r   rx   ry   r?  r@  )rA   rx   ry   r?  r@  r   r   s         r4   r   !CropNonEmptyMaskIfExists.__init__y  s+     	1
*.r3   c                   UR                   S S u  p#U R                  bL  [        R                  " U R                  5      n[        R                  " [        R
                  " X5      SU5      nUR                  [        :X  ap  U R                  bc  [        R                  " [        UR                   S   5       Vs/ s H  oUU R                  ;  d  M  UPM     sn5      n[        R                  " XSS9nU R                  U:  d  U R                  U:  a,  [        SU R                   SU R                   SU SU S3	5      eU$ s  snf )	Nr9   r   axiszCrop size (,z) is larger than image ())rH   r?  rt   arraywhereisinndimr   r@  rangetakerx   ry   r  )rA   r   mask_height
mask_widthignore_values_npchtarget_channelss          r4   _preprocess_mask)CropNonEmptyMaskIfExists._preprocess_mask  s   "&**Ra.)!xx(:(:;88BGGD;QED99449M9M9Y hhU4::b>5J'm5JrX\XlXlNl5J'mnO774r:D;;$

Z(?dkk]!DJJ<7OP[}\]^h]iijk   (ns   6D=D=c                >   SU;   a  U R                  US   5      nOsSU;   a`  [        US   5      (       aM  US   nU R                  [        R                  " US   5      5      nUSS  H  nX0R                  U5      -  nM     OSn[	        U5      eUR
                  SS u  pxUR                  5       (       a  UR                  [        :X  a  UR                  SS	9OUn	[        R                  " U	5      n
U R                  R                  U
5      u  pXR                  R                  SU R                  S-
  5      -
  nXR                  R                  SU R                  S-
  5      -
  n[        R                   " USXR                  -
  5      n[        R                   " USXpR                  -
  5      nOPU R                  R                  SXR                  -
  5      nU R                  R                  SXpR                  -
  5      nXR                  -   nXR                  -   nS
XUU40$ )zGet crop coordinates based on mask content.

Args:
    params (dict[str, Any]): The parameters of the transform.
    data (dict[str, Any]): The data of the transform.

r   masksr   r   Nz.Can not find mask for CropNonEmptyMaskIfExistsr9   rD  rE  rC   )rT  lenrt   copyRuntimeErrorrH   r9  rL  r   sumargwherer   choicerandintry   rx   ru   )rA   rD   r   r   rW  mr  rO  rP  mask_sumnon_zero_yxyxr;   r<   r=   r>   s                    r4   r  5CropNonEmptyMaskIfExists.get_params_dependent_on_data  s    T>((f6D_T']!3!3ME((q):;D12Y--a00  CCs##"&**Ra.88::,0II9U,UtxxRx([_H++h/K>>((5DA ..q$**q.AAE..q$++/BBEGGE1j::&=>EGGE1kKK&?@E NN**1j::.EFENN**1kKK.GHE

"#eU;<<r3   )rx   r@  r?  ry   )NNr   )
rx   r  ry   r  r?  r>  r@  r>  r   r   )r   r}   r   r}   r  )r.   r/   r0   r1   r   r6   r   r   rT  r  r2   r   r   s   @r4   r#   r#     s    kZ+X(( + +/,0// / (	/
 */ / /$,=,= ,= 
	,= ,=r3   r#   c                       \ rS rSr% S\S'   Srg)BaseRandomSizedCropInitSchemai  GAnnotated[tuple[int, int], AfterValidator(check_range_bounds(1, None))]sizer-   Nr   r-   r3   r4   rf  rf    s    
QQr3   rf  c                  L  ^  \ rS rSrSr " S S\5      r\R                  \R                  SS4         SU 4S jjjr
SS jr        SS	 jr        SS
 jr        SS jr        SS jr        SS jr        SS jr        SS jrSrU =r$ )_BaseRandomSizedCropi  a.  Base class for transforms that crop an image randomly and resize it to a specific size.

This abstract class provides the foundation for RandomSizedCrop and RandomResizedCrop transforms.
It handles cropping and resizing for different data types (image, mask, bboxes, keypoints) while
maintaining their spatial relationships.

Child classes must implement the `get_params_dependent_on_data` method to determine how the
crop coordinates are selected according to transform-specific parameters and logic.

Args:
    size (tuple[int, int]): Target size (height, width) after cropping and resizing.
    interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm
        for image resizing. Default: cv2.INTER_LINEAR.
    mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation
        algorithm for mask resizing. Default: cv2.INTER_NEAREST.
    area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
        for downscaling. Options:
        - None: No automatic interpolation selection, always use the specified interpolation method
        - "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
        - "image_mask": Use INTER_AREA when downscaling both images and masks
        Default: None.
    p (float): Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    This class is not meant to be used directly. Instead, use derived transforms
    like RandomSizedCrop or RandomResizedCrop that implement specific crop selection
    strategies.
    When area_for_downscale is set, INTER_AREA interpolation will be used automatically for
    downscaling (when the crop is larger than the target size), which provides better quality for size reduction.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # Example of a custom transform that inherits from _BaseRandomSizedCrop
    >>> class CustomRandomCrop(_BaseRandomSizedCrop):
    ...     def __init__(
    ...         self,
    ...         size=(224, 224),
    ...         custom_parameter=0.5,
    ...         interpolation=cv2.INTER_LINEAR,
    ...         mask_interpolation=cv2.INTER_NEAREST,
    ...         area_for_downscale="image",
    ...         p=1.0
    ...     ):
    ...         super().__init__(
    ...             size=size,
    ...             interpolation=interpolation,
    ...             mask_interpolation=mask_interpolation,
    ...             area_for_downscale=area_for_downscale,
    ...             p=p,
    ...         )
    ...         self.custom_parameter = custom_parameter
    ...
    ...     def get_params_dependent_on_data(self, params, data):
    ...         # Custom logic to select crop coordinates
    ...         image_height, image_width = params["shape"][:2]
    ...
    ...         # Simple example: calculate crop size based on custom_parameter
    ...         crop_height = int(image_height * self.custom_parameter)
    ...         crop_width = int(image_width * self.custom_parameter)
    ...
    ...         # Random position
    ...         y1 = self.py_random.randint(0, image_height - crop_height + 1)
    ...         x1 = self.py_random.randint(0, image_width - crop_width + 1)
    ...         y2 = y1 + crop_height
    ...         x2 = x1 + crop_width
    ...
    ...         return {"crop_coords": (x1, y1, x2, y2)}
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Create a pipeline with our custom transform
    >>> transform = A.Compose(
    ...     [CustomRandomCrop(size=(64, 64), custom_parameter=0.6, area_for_downscale="image")],
    ...     bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...     keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels'])
    ... )
    >>>
    >>> # 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']  # Will be 64x64
    >>> transformed_mask = transformed['mask']    # Will be 64x64
    >>> transformed_bboxes = transformed['bboxes']  # Bounding boxes adjusted to new dimensions
    >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels for bboxes that remain after cropping
    >>> transformed_keypoints = transformed['keypoints']  # Keypoints adjusted to new dimensions
    >>> transformed_keypoint_labels = transformed['keypoint_labels']  # Labels for keypoints that remain

c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg)	_BaseRandomSizedCrop.InitSchemai>  Literal[cv2.INTER_NEAREST, cv2.INTER_NEAREST_EXACT, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4, cv2.INTER_LINEAR_EXACT]interpolationmask_interpolation$Literal[None, 'image', 'image_mask']area_for_downscaler-   Nr   r-   r3   r4   r   rl  >  s    
 	

 	
 A@r3   r   Nr   c                P   > [         TU ]  US9  Xl        X l        X0l        X@l        g r   )r   r   rh  rn  ro  rq  )rA   rh  rn  ro  rq  r   r   s         r4   r   _BaseRandomSizedCrop.__init__S  s,    0 	1	*"4"4r3   c                   Uu  p4U R                   u  pVX5:  =(       d    XF:  nU(       a  US:X  a  U R                  S;   d  US:X  a   U R                  S:X  a  [        R                  $ US:X  a  U R                  $ U R
                  $ )zGet the appropriate interpolation method for resizing.

Args:
    crop_shape: Shape of the crop (height, width)
    target_type: Either "image" or "mask" to determine base interpolation

Returns:
    OpenCV interpolation flag

image)ru  
image_maskr   rv  )rh  rq  r	  
INTER_AREArn  ro  )rA   
crop_shapetarget_typecrop_height
crop_widthtarget_heighttarget_widthis_downscales           r4   _get_interpolation_for_resize2_BaseRandomSizedCrop._get_interpolation_for_resizeq  s     #-&*ii# $3S9R kW49P9PTk9k6!d&=&=&M>>!%0G%;t!!XAXAXXr3   c                    [         R                  " U/UQ76 nU R                  UR                  SS S5      n[        R
                  " X@R                  U5      $ )zApply the crop to the image.

Args:
    img (np.ndarray): The image to crop.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    **params (Any): Additional parameters.

Nr9   ru  r?   r@   r  rH   r   resizerh  )rA   rB   rC   rD   r@   rn  s         r4   rE   _BaseRandomSizedCrop.apply  sJ     {{3--::4::bq>7S  yy-@@r3   c                    [         R                  " U/UQ76 nU R                  UR                  SS S5      n[        R
                  " X@R                  U5      $ )zApply the crop to the mask.

Args:
    mask (np.ndarray): The mask to crop.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    **params (Any): Additional parameters.

Nr9   r   r  )rA   r   rC   rD   r@   rn  s         r4   r   "_BaseRandomSizedCrop.apply_to_mask  sJ     {{4.+.::4::bq>6R  yy-@@r3   c                6    [         R                  " XUS   5      $ )zApply the crop to the bounding boxes.

Args:
    bboxes (np.ndarray): The bounding boxes to crop.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    **params (Any): Additional parameters.

rH   rI   rK   s       r4   rM   $_BaseRandomSizedCrop.apply_to_bboxes  s     ++FQQr3   c                    [         R                  " X5      nUS   US   -
  nUS   US   -
  nU R                  S   U-  nU R                  S   U-  n[        R                  " XGU5      $ )zApply the crop to the keypoints.

Args:
    keypoints (np.ndarray): The keypoints to crop.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    **params (Any): Additional parameters.

r:   r   r9   r   )r?   rP   rh  r   keypoints_scale)	rA   rQ   rC   rD   cropped_keypointsrz  r{  scale_xscale_ys	            r4   rR   '_BaseRandomSizedCrop.apply_to_keypoints  sw     #;;IS "!n{1~5 ^k!n4
 ))A,+))A,, ))*;gNNr3   c           
     6   [         R                  " U/UQ76 nU R                  UR                  SS S5      n[        R
                  " [        UR                  S   5       Vs/ s H'  n[        R                  " XF   U R                  U5      PM)     sn5      $ s  snf )a  Apply the crop and resize to a volume/images.

This method crops the volume first (reducing data size), then resizes using
a helper method with batch transform decorator.

Args:
    images (np.ndarray): The volume/images to crop and resize with shape (D, H, W) or (D, H, W, C).
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    **params (Any): Additional parameters.

r   r:   ru  r   )
r?   rV   r  rH   rt   stackrM  r   r  rh  )rA   rW   rC   rD   r@   rn  is          r4   rX   $_BaseRandomSizedCrop.apply_to_images  s    $ $$V:k: ::4::a?GT xxW\]c]i]ijk]lWmnWmRS**47DII}MWmnoons   !.Bc                (    U R                   " X40 UD6$ )zApply the crop and resize to a volume.

Args:
    volume (np.ndarray): The volume to crop.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    **params (Any): Additional parameters.

r\   r]   s       r4   r_   $_BaseRandomSizedCrop.apply_to_volume       ##FB6BBr3   c                (    U R                   " X40 UD6$ )zApply the crop and resize to a mask3d.

Args:
    mask3d (np.ndarray): The mask3d to crop.
    crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
    **params (Any): Additional parameters.

r\   rh   s       r4   rj   $_BaseRandomSizedCrop.apply_to_mask3d  r  r3   )rq  rn  ro  rh  )
rh  r   rn  rm  ro  rm  rq  rp  r   r   )rx  r   ry  strr   r  r|   r   r}   rC   r~   rD   r   r   r}   r   r   r   r   r   )r.   r/   r0   r1   r   rf  r   r	  INTER_LINEARINTER_NEARESTr   r  rE   r   rM   rR   rX   r_   rj   r2   r   r   s   @r4   rj  rj    s   n`A2 A@  CG-55
5
5* A+5, -5 5<Y2AA /A 	A
 
A$AA /A 	A
 
A$RR /R 	R
 
R OO /O 	O
 
O8pp /p 	p
 
p4CC /C 	C
 
C CC /C 	C
 
C Cr3   rj  c                     ^  \ rS rSrSr\r " S S\5      rS\	R                  \	R                  SS4             S
U 4S jjjr      SS jrS	rU =r$ )r)   i  a  Crop a random part of the input and rescale it to a specific size.

This transform first crops a random portion of the input and then resizes it to a specified size.
The size of the random crop is controlled by the 'min_max_height' parameter.

Args:
    min_max_height (tuple[int, int]): Minimum and maximum height of the crop in pixels.
    size (tuple[int, int]): Target size for the output image, i.e. (height, width) after crop and resize.
    w2h_ratio (float): Aspect ratio (width/height) of crop. Default: 1.0
    interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
        cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
        Default: cv2.INTER_LINEAR.
    mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
        Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
        Default: cv2.INTER_NEAREST.
    area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
        for downscaling. Options:
        - None: No automatic interpolation selection, always use the specified interpolation method
        - "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
        - "image_mask": Use INTER_AREA when downscaling both images and masks
        Default: None.
    p (float): Probability of applying the transform. Default: 1.0

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

Image types:
    uint8, float32

Note:
    - The crop size is randomly selected for each execution within the range specified by 'min_max_height'.
    - The aspect ratio of the crop is determined by the 'w2h_ratio' parameter.
    - After cropping, the result is resized to the specified 'size'.
    - Bounding boxes that end up fully outside the cropped area will be removed.
    - Keypoints that end up outside the cropped area will be removed.
    - This transform differs from RandomResizedCrop in that it allows more control over the crop size
      through the 'min_max_height' parameter, rather than using a scale parameter.
    - When area_for_downscale is set, INTER_AREA interpolation will be used automatically for
      downscaling (when the crop is larger than the target size), which provides better quality for size reduction.

Mathematical Details:
    1. A random crop height h is sampled from the range [min_max_height[0], min_max_height[1]].
    2. The crop width w is calculated as: w = h * w2h_ratio
    3. A random location for the crop is selected within the input image.
    4. The image is cropped to the size (h, w).
    5. The crop is then resized to the specified 'size'.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Define transform with parameters as tuples
    >>> transform = A.Compose([
    ...     A.RandomSizedCrop(
    ...         min_max_height=(50, 80),
    ...         size=(64, 64),
    ...         w2h_ratio=1.0,
    ...         interpolation=cv2.INTER_LINEAR,
    ...         mask_interpolation=cv2.INTER_NEAREST,
    ...         area_for_downscale="image",  # Use INTER_AREA for image downscaling
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # 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']       # Shape: (64, 64, 3)
    >>> transformed_mask = transformed['mask']         # Shape: (64, 64)
    >>> transformed_bboxes = transformed['bboxes']     # Bounding boxes adjusted to new crop and size
    >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels for the preserved bboxes
    >>> transformed_keypoints = transformed['keypoints']      # Keypoints adjusted to new crop and size
    >>> transformed_keypoint_labels = transformed['keypoint_labels']  # Labels for the preserved keypoints

c                  R    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	\S
'   S\S'   Srg)RandomSizedCrop.InitSchemaiv  rm  rn  ro  r   min_max_heightzAnnotated[float, Field(gt=0)]	w2h_ratiorg  rh  rp  rq  r-   Nr   r-   r3   r4   r   r  v  s0    
 	

 	
 ,+00UU@@r3   r   r   Nc                @   > [         TU ]  UUUUUS9  Xl        X0l        g N)rh  rn  ro  rq  r   )r   r   r  r  )	rA   r  rh  r  rn  ro  rq  r   r   s	           r4   r   RandomSizedCrop.__init__  s3    4 	'11 	 	
 -"r3   c                *   US   SS nU R                   R                  " U R                  6 n[        X@R                  -  5      nXE4nU R                   R                  5       nU R                   R                  5       n[        R                  " X6Xx5      n	SU	0$ )r  rH   Nr9   rC   )r   r^  r  r  r  r   r?   r   )
rA   rD   r   rw   rz  r{  rx  r   r   rC   s
             r4   r  ,RandomSizedCrop.get_params_dependent_on_data  s     Wobq)nn,,d.A.AB~~56
!.
..'')..''),,[gW{++r3   )r  r  )r  r   rh  r   r  r   rn  rm  ro  rm  rq  rp  r   r   rD   r  r   r  r   z$dict[str, tuple[int, int, int, int]]r.   r/   r0   r1   r   r   r   r   r   r	  r  r  r   r  r2   r   r   s   @r4   r)   r)     s    \| HA, A8   CG1"#'"# "# 	"#

"#
"#. A/"#0 1"# "#H,, , 
.	, ,r3   r)   c                     ^  \ rS rSrSr\r " S S\5      rSS\	R                  \	R                  SS4             SU 4S	 jjjr      SS
 jrSrU =r$ )r'   i  a  Crop a random part of the input and rescale it to a specified size.

This transform first crops a random portion of the input image (or mask, bounding boxes, keypoints)
and then resizes the crop to a specified size. It's particularly useful for training neural networks
on images of varying sizes and aspect ratios.

Args:
    size (tuple[int, int]): Target size for the output image, i.e. (height, width) after crop and resize.
    scale (tuple[float, float]): Range of the random size of the crop relative to the input size.
        For example, (0.08, 1.0) means the crop size will be between 8% and 100% of the input size.
        Default: (0.08, 1.0)
    ratio (tuple[float, float]): Range of aspect ratios of the random crop.
        For example, (0.75, 1.3333) allows crop aspect ratios from 3:4 to 4:3.
        Default: (0.75, 1.3333333333333333)
    interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
        cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
        Default: cv2.INTER_LINEAR
    mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
        Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
        Default: cv2.INTER_NEAREST
    area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
        for downscaling. Options:
        - None: No automatic interpolation selection, always use the specified interpolation method
        - "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
        - "image_mask": Use INTER_AREA when downscaling both images and masks
        Default: None.
    p (float): Probability of applying the transform. Default: 1.0

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

Image types:
    uint8, float32

Note:
    - This transform attempts to crop a random area with an aspect ratio and relative size
      specified by 'ratio' and 'scale' parameters. If it fails to find a suitable crop after
      10 attempts, it will return a crop from the center of the image.
    - The crop's aspect ratio is defined as width / height.
    - Bounding boxes that end up fully outside the cropped area will be removed.
    - Keypoints that end up outside the cropped area will be removed.
    - After cropping, the result is resized to the specified size.
    - When area_for_downscale is set, INTER_AREA interpolation will be used automatically for
      downscaling (when the crop is larger than the target size), which provides better quality for size reduction.

Mathematical Details:
    1. A target area A is sampled from the range [scale[0] * input_area, scale[1] * input_area].
    2. A target aspect ratio r is sampled from the range [ratio[0], ratio[1]].
    3. The crop width and height are computed as:
       w = sqrt(A * r)
       h = sqrt(A / r)
    4. If w and h are within the input image dimensions, the crop is accepted.
       Otherwise, steps 1-3 are repeated (up to 10 times).
    5. If no valid crop is found after 10 attempts, a centered crop is taken.
    6. The crop is then resized to the specified size.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Define transform with parameters as tuples
    >>> transform = A.Compose([
    ...     A.RandomResizedCrop(
    ...         size=(64, 64),
    ...         scale=(0.5, 0.9),  # Crop size will be 50-90% of original image
    ...         ratio=(0.75, 1.33),  # Aspect ratio will vary from 3:4 to 4:3
    ...         interpolation=cv2.INTER_LINEAR,
    ...         mask_interpolation=cv2.INTER_NEAREST,
    ...         area_for_downscale="image",  # Use INTER_AREA for image downscaling
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # 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']       # Shape: (64, 64, 3)
    >>> transformed_mask = transformed['mask']         # Shape: (64, 64)
    >>> transformed_bboxes = transformed['bboxes']     # Bounding boxes adjusted to new crop and size
    >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels for the preserved bboxes
    >>> transformed_keypoints = transformed['keypoints']      # Keypoints adjusted to new crop and size
    >>> transformed_keypoint_labels = transformed['keypoint_labels']  # Labels for the preserved keypoints

c                  R    \ rS rSr% S\S'   S\S'   S\S'   S\S	'   S\S
'   S\S'   Srg)RandomResizedCrop.InitSchemai7  zgAnnotated[tuple[float, float], AfterValidator(check_range_bounds(0, 1)), AfterValidator(nondecreasing)]scalezjAnnotated[tuple[float, float], AfterValidator(check_range_bounds(0, None)), AfterValidator(nondecreasing)]ratiorg  rh  rm  rn  ro  rp  rq  r-   Nr   r-   r3   r4   r   r  7  s8    vv
 	

 VU
 	

 	
 A@r3   r   )g{Gz?r   )g      ?gUUUUUU?Nr   c                @   > [         TU ]  UUUUUS9  X l        X0l        g r  )r   r   r  r  )	rA   rh  r  r  rn  ro  rq  r   r   s	           r4   r   RandomResizedCrop.__init__S  s2    4 	'11 	 	
 

r3   c                ,   US   SS nUu  pEXE-  nU R                   S   U-  nU R                   S   U-  n[        R                  " U R                  S   5      n	[        R                  " U R                  S   5      n
[	        S5       GH  nU R
                  R                  Xx5      n[        R                  " U R
                  R                  X5      5      n[        [        R                  " X-  5      5      n[        [        R                  " X-  5      5      nSUs=:  a  U::  d  M  O  M  SUs=:  a  U::  d  M  O  M  U R
                  R                  5       nU R
                  R                  5       n[        R                  " X?U4UU5      nSU0s  $    XT-  nUU R                  S   :  a  Un[        XPR                  S   -  5      nO4UU R                  S   :  a  Un[        XR                  S   -  5      nOUnUn[        R                  " X?U45      nSU0$ )r  rH   Nr9   r   r   
   rC   )r  mathlogr  rM  r   uniformexproundsqrtr   r?   r   r  )rA   rD   r   rw   r   r   areascale_min_areascale_max_arealog_ratio_minlog_ratio_max_target_areaaspect_ratiory   rx   r   r   rC   in_ratios                       r4   r  .RandomResizedCrop.get_params_dependent_on_dataw  s    Wobq)$/!) A-A-A/A/rA..00PK88DNN$:$:=$XYL$))K$>?@E499[%?@AF5'K''A,F,,F,F..//1..//1$44[5/SZ\cd%{33  -djjm#E;A67F

1%!F&::a=01EE!F33K%Q{++r3   )r  r  )rh  r   r  tuple[float, float]r  r  rn  rm  ro  rm  rq  rp  r   r   r  r  r   s   @r4   r'   r'     s    eN HA, A> &1%?  CG1"" #" #	"

"
". A/"0 1" "H1,1, 1, 
.	1, 1,r3   r'   c                     ^  \ rS rSrSr\r " S S\5      r   S	     S
U 4S jjjr	      SS jr
\SS j5       rSrU =r$ )r&   i  a-  Crop bbox from image with random shift by x,y coordinates

Args:
    max_part_shift (float, (float, float)): Max shift in `height` and `width` dimensions relative
        to `cropping_bbox` dimension.
        If max_part_shift is a single float, the range will be (0, max_part_shift).
        Default (0, 0.3).
    cropping_bbox_key (str): Additional target key for cropping box. Default `cropping_bbox`.
    p (float): probability of applying the transform. Default: 1.

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

Image types:
    uint8, float32

Examples:
    >>> aug = Compose([RandomCropNearBBox(max_part_shift=(0.1, 0.5), cropping_bbox_key='test_bbox')],
    >>>              bbox_params=BboxParams("pascal_voc"))
    >>> result = aug(image=image, bboxes=bboxes, test_bbox=[0, 5, 10, 20])

c                  *    \ rS rSr% S\S'   S\S'   Srg)RandomCropNearBBox.InitSchemai  r   max_part_shiftr  cropping_bbox_keyr-   Nr   r-   r3   r4   r   r    s    ((r3   r   c                N   > [         TU ]  US9  [        SU5      U l        X l        g )Nr   r  )r   r   r	   r  r  )rA   r  r  r   r   s       r4   r   RandomCropNearBBox.__init__  s+     	1"#8.I!2r3   c                   X R                      nUS   SS nU R                  X45      n[        US   US   -
  U R                  S   -  5      n[        US   US   -
  U R                  S   -  5      nUS   U R                  R                  U* U5      -
  nUS   U R                  R                  U* U5      -   nUS   U R                  R                  U* U5      -
  n	US   U R                  R                  U* U5      -   n
U R                  XyX4U5      nUS   US   :X  d  US   US   :X  a,  US   US   -
  US   US   -
  4n[        R                  " XL5      nSU0$ )r  rH   Nr9   r:   r   r   rC   )r  rz   r  r  r   r^  r?   r  )rA   rD   r   rv   rw   h_max_shiftw_max_shiftr;   r=   r<   r>   rC   rx  s                r4   r  /RandomCropNearBBox.get_params_dependent_on_data  su    **+Wobq)t1T!WtAw.$2E2Ea2HHIT!WtAw.$2E2Ea2HHIQ$..00+{KKQ$..00+{KKQ$..00+{KKQ$..00+{KKoouU&BKPq>[^+{1~Q/Oq'DG+T!WtAw->?J 77PK{++r3   c                    U R                   /$ )zTGet the targets as parameters.

Returns:
    list[str]: The targets as parameters.

)r  )rA   s    r4   targets_as_params$RandomCropNearBBox.targets_as_params  s     &&''r3   )r  r  ))r   g333333?cropping_bboxr   )r  ztuple[float, float] | floatr  r  r   r   )rD   r  r   r  r   zdict[str, tuple[float, ...]])r   z	list[str])r.   r/   r0   r1   r   r   r   r   r   r   r  propertyr  r2   r   r   s   @r4   r&   r&     s    . H,  7?!0	333 3 	3 3!,!, !, 
&	!,F ( (r3   r&   c                  n   ^  \ rS rSrSr\r " S S\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	  aS  Crop an area from image while ensuring all bounding boxes are preserved in the crop.

Similar to AtLeastOneBboxRandomCrop, but with a key difference:
- BBoxSafeRandomCrop ensures ALL bounding boxes are preserved in the crop when erosion_rate=0.0
- AtLeastOneBboxRandomCrop ensures AT LEAST ONE bounding box is present in the crop

This makes BBoxSafeRandomCrop more suitable for scenarios where:
- You need to preserve all objects in the scene
- Losing any bounding box would be problematic (e.g., rare object classes)
- You're training a model that needs to detect multiple objects simultaneously

The algorithm:
1. If bounding boxes exist:
    - Computes the union of all bounding boxes
    - Applies erosion based on erosion_rate to this union
    - Clips the eroded union to valid image coordinates [0,1]
    - Randomly samples crop coordinates within the clipped union area
2. If no bounding boxes exist:
    - Computes crop height based on erosion_rate
    - Sets crop width to maintain original aspect ratio
    - Randomly places the crop within the image

Args:
    erosion_rate (float): Controls how much the valid crop region can deviate from the bbox union.
        Must be in range [0.0, 1.0].
        - 0.0: crop must contain the exact bbox union (safest option that guarantees all boxes are preserved)
        - 1.0: crop can deviate maximally from the bbox union (increases likelihood of cutting off some boxes)
        Defaults to 0.0.
    p (float, optional): Probability of applying the transform. Defaults to 1.0.

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

Image types:
    uint8, float32

Raises:
    CropSizeError: If requested crop size exceeds image dimensions

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.random.randint(0, 2, (100, 100), dtype=np.uint8)
    >>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Define transform with erosion_rate parameter
    >>> transform = A.Compose([
    ...     A.BBoxSafeRandomCrop(erosion_rate=0.2),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> result = transform(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> transformed_image = result['image']  # Cropped image containing all bboxes
    >>> transformed_mask = result['mask']    # Cropped mask
    >>> transformed_bboxes = result['bboxes']  # All bounding boxes preserved with adjusted coordinates
    >>> transformed_bbox_labels = result['bbox_labels']  # Original labels preserved
    >>> transformed_keypoints = result['keypoints']  # Keypoints with adjusted coordinates
    >>> transformed_keypoint_labels = result['keypoint_labels']  # Original keypoint labels preserved
    >>>
    >>> # Example with a different erosion_rate
    >>> transform_more_flexible = A.Compose([
    ...     A.BBoxSafeRandomCrop(erosion_rate=0.5),  # More flexibility in crop placement
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
    >>>
    >>> # Apply transform with only image and bboxes
    >>> result_bboxes_only = transform_more_flexible(
    ...     image=image,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels
    ... )
    >>> transformed_image = result_bboxes_only['image']
    >>> transformed_bboxes = result_bboxes_only['bboxes']  # All bboxes still preserved

Note:
    - IMPORTANT: Using erosion_rate > 0.0 may result in some bounding boxes being cut off,
      particularly narrow boxes at the boundary of the union area. For guaranteed preservation
      of all bounding boxes, use erosion_rate=0.0.
    - Aspect ratio is preserved only when no bounding boxes are present
    - May be more restrictive in crop placement compared to AtLeastOneBboxRandomCrop
    - The crop size is determined by the bounding boxes when present

c                  .    \ rS rSr% \" SSS9rS\S'   Srg)	BBoxSafeRandomCrop.InitSchemaig	  r   r   geler   erosion_rater-   N)r.   r/   r0   r1   r   r  r   r2   r-   r3   r4   r   r  g	  s    #
e 	
r3   r   c                ,   > [         TU ]  US9  Xl        g r   )r   r   r  )rA   r  r   r   s      r4   r   BBoxSafeRandomCrop.__init__m	  s    1(r3   c                @   Uu  p#[        USU R                  -
  -  5      nXB:  a  UOU R                  R                  XB5      n[        XS-  U-  5      nU R                  R	                  5       nU R                  R	                  5       nXV4n	[
        R                  " XXx5      $ )Nr   )r  r  r   r^  r   r?   r   )
rA   rw   r   r   	erosive_hrz  r{  r   r   rx  s
             r4   _get_coords_no_bbox&BBoxSafeRandomCrop._get_coords_no_bboxq	  s    $/!d.?.?(?@A	&/&?lT^^E[E[\eEt2\AB
..'')..'')!.
%%kwPPr3   c                   US   SS n[        US   5      S:X  a  U R                  U5      nSU0$ [        US   U R                  S9nUc  U R                  U5      nSU0$ Uu  pgp[        R
                  " USS5      n[        R
                  " USS5      n[        R
                  " XS5      n[        R
                  " XS5      n	Uu  p[        X`R                  R                  5       -  U-  5      n[        XpR                  R                  5       -  U
-  5      nUSU-
  U R                  R                  5       -  -   nU	SU	-
  U R                  R                  5       -  -   n[        X-  5      n[        X-  5      nSXUU40$ )	r  rH   Nr9   rL   r   rC   )rL   r  r   )	rX  r  r   r  rt   ru   r  r   r   )rA   rD   r   rw   rC   
bbox_unionr;   r<   r=   r>   r   r   
crop_x_min
crop_y_min	bbox_xmax	bbox_ymax
crop_x_max
crop_y_maxs                     r4   r  /BBoxSafeRandomCrop.get_params_dependent_on_data	  sw    Wobq)tH~!#22;?K!;//$DNIZIZ[
22;?K!;//%/"eq!$q!$a(a($/!!6!6!88;FG
!6!6!88<GH
QY$..*?*?*AAA	QY$..*?*?*AAA	01
12


JOPPr3   )r  r   r   )r  r   r   r   )rw   r   r   r~   r  )r.   r/   r0   r1   r   r   r   r   r   r   r  r  r2   r   r   s   @r4   r   r   	  sY    aF H
, 
) )Q)Q)Q )Q 
.	)Q )Qr3   r   c                     ^  \ rS rSrSr\r " S S\5      rS\	R                  \	R                  S4           SU 4S jjjr        SS jr        SS	 jr        SS
 jrSrU =r$ )r(   i	  a  Crop a random part of the input and rescale it to a specific size without loss of bounding boxes.

This transform first attempts to crop a random portion of the input image while ensuring that all bounding boxes
remain within the cropped area. It then resizes the crop to the specified size. This is particularly useful for
object detection tasks where preserving all objects in the image is crucial while also standardizing the image size.

Args:
    height (int): Height of the output image after resizing.
    width (int): Width of the output image after resizing.
    erosion_rate (float): A value between 0.0 and 1.0 that determines the minimum allowable size of the crop
        as a fraction of the original image size. For example, an erosion_rate of 0.2 means the crop will be
        at least 80% of the original image height and width. Default: 0.0 (no minimum size).
    interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
        cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.AREA, cv2.INTER_LANCZOS4.
        Default: cv2.INTER_LINEAR.
    mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
        Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.AREA, cv2.INTER_LANCZOS4.
        Default: cv2.INTER_NEAREST.
    p (float): Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    - This transform ensures that all bounding boxes in the original image are fully contained within the
      cropped area. If it's not possible to find such a crop (e.g., when bounding boxes are too spread out),
      it will default to cropping the entire image.
    - After cropping, the result is resized to the specified (height, width) size.
    - Bounding box coordinates are adjusted to match the new image size.
    - Keypoints are moved along with the crop and scaled to the new image size.
    - If there are no bounding boxes in the image, it will fall back to a random crop.

Mathematical Details:
    1. A crop region is selected that includes all bounding boxes.
    2. The crop size is determined by the erosion_rate:
       min_crop_size = (1 - erosion_rate) * original_size
    3. If the selected crop is smaller than min_crop_size, it's expanded to meet this requirement.
    4. The crop is then resized to the specified (height, width) size.
    5. Bounding box coordinates are transformed to match the new image size:
       new_coord = (old_coord - crop_start) * (new_size / crop_size)

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # Prepare sample data
    >>> image = np.random.randint(0, 256, (300, 300, 3), dtype=np.uint8)
    >>> mask = np.random.randint(0, 2, (300, 300), dtype=np.uint8)
    >>>
    >>> # Create bounding boxes with some overlap and separation
    >>> bboxes = np.array([
    ...     [10, 10, 80, 80],    # top-left box
    ...     [100, 100, 200, 200], # center box
    ...     [210, 210, 290, 290]  # bottom-right box
    ... ], dtype=np.float32)
    >>> bbox_labels = ['cat', 'dog', 'bird']
    >>>
    >>> # Create keypoints inside the bounding boxes
    >>> keypoints = np.array([
    ...     [45, 45],    # inside first box
    ...     [150, 150],  # inside second box
    ...     [250, 250]   # inside third box
    ... ], dtype=np.float32)
    >>> keypoint_labels = ['nose', 'eye', 'tail']
    >>>
    >>> # Example 1: Basic usage with default parameters
    >>> transform_basic = A.Compose([
    ...     A.RandomSizedBBoxSafeCrop(height=224, width=224, p=1.0),
    ... ], bbox_params=A.BboxParams(
    ...     format='pascal_voc',
    ...     label_fields=['bbox_labels']
    ... ), keypoint_params=A.KeypointParams(
    ...     format='xy',
    ...     label_fields=['keypoint_labels']
    ... ))
    >>>
    >>> # Apply the transform
    >>> result_basic = transform_basic(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Access the transformed data
    >>> transformed_image = result_basic['image']  # Shape will be (224, 224, 3)
    >>> transformed_mask = result_basic['mask']    # Shape will be (224, 224)
    >>> transformed_bboxes = result_basic['bboxes']  # All original bounding boxes preserved
    >>> transformed_bbox_labels = result_basic['bbox_labels']  # Original labels preserved
    >>> transformed_keypoints = result_basic['keypoints']  # Keypoints adjusted to new coordinates
    >>> transformed_keypoint_labels = result_basic['keypoint_labels']  # Original labels preserved
    >>>
    >>> # Example 2: With erosion_rate for more flexibility in crop placement
    >>> transform_erosion = A.Compose([
    ...     A.RandomSizedBBoxSafeCrop(
    ...         height=256,
    ...         width=256,
    ...         erosion_rate=0.2,  # Allows 20% flexibility in crop placement
    ...         interpolation=cv2.INTER_CUBIC,  # Higher quality interpolation
    ...         mask_interpolation=cv2.INTER_NEAREST,  # Preserve mask edges
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(
    ...     format='pascal_voc',
    ...     label_fields=['bbox_labels'],
    ...     min_visibility=0.3  # Only keep bboxes with at least 30% visibility
    ... ), keypoint_params=A.KeypointParams(
    ...     format='xy',
    ...     label_fields=['keypoint_labels'],
    ...     remove_invisible=True  # Remove keypoints outside the crop
    ... ))
    >>>
    >>> # Apply the transform with erosion
    >>> result_erosion = transform_erosion(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # With erosion_rate=0.2, the crop has more flexibility in placement
    >>> # while still ensuring all bounding boxes are included

c                  V    \ rS rSr% S\S'   S\S'   \" SSS9rS\S	'   S
\S'   S
\S'   Srg)"RandomSizedBBoxSafeCrop.InitSchemai4
  r   rx   ry   r   r   r  r   r  rm  rn  ro  r-   N)r.   r/   r0   r1   r   r   r  r2   r-   r3   r4   r   r  4
  s9    ++**#
e 	

 	

 	
r3   r   r   r   c                P   > [         TU ]  X6S9  Xl        X l        X@l        XPl        g )N)r  r   )r   r   rx   ry   rn  ro  )rA   rx   ry   r  rn  ro  r   r   s          r4   r    RandomSizedBBoxSafeCrop.__init__N
  s+    2 	l8
*"4r3   c                    [         R                  " U/UQ76 n[        R                  " X@R                  U R
                  4U R                  5      $ )a  Apply the crop and pad transform to an image.

Args:
    img (np.ndarray): The image to apply the crop and pad transform to.
    crop_coords (tuple[int, int, int, int]): The parameters for the crop.
    params (dict[str, Any]): Additional parameters for the transform.

)r?   r@   r   r  rx   ry   rn  )rA   rB   rC   rD   r@   s        r4   rE   RandomSizedBBoxSafeCrop.applym
  s=     {{3--  TZZ'@$BTBTUUr3   c                    [         R                  " U/UQ76 n[        R                  " X@R                  U R
                  4U R                  5      $ )a  Apply the crop and pad transform to a mask.

Args:
    mask (np.ndarray): The mask to apply the crop and pad transform to.
    crop_coords (tuple[int, int, int, int]): The parameters for the crop.
    params (dict[str, Any]): Additional parameters for the transform.

)r?   r@   r   r  rx   ry   ro  )rA   r   rC   rD   r@   s        r4   r   %RandomSizedBBoxSafeCrop.apply_to_mask~
  s=     {{4.+.  TZZ'@$BYBYZZr3   c                    [         R                  " X5      nUS   US   -
  nUS   US   -
  nU R                  U-  nU R                  U-  n[        R
                  " XUS9$ )ac  Apply the crop and pad transform to keypoints.

Args:
    keypoints (np.ndarray): The keypoints to apply the crop and pad transform to.
    crop_coords (tuple[int, int, int, int]): The parameters for the crop.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The keypoints after the crop and pad transform.

r:   r   r9   r   )r  r  )r?   rP   rx   ry   r   r  )rA   rQ   rC   rD   rz  r{  r  r  s           r4   rR   *RandomSizedBBoxSafeCrop.apply_to_keypoints
  sg    " 33IK	!!n{1~5 ^k!n4
+++**z))))gVVr3   )rx   rn  ro  ry   )rx   r  ry   r  r  r   rn  rm  ro  rm  r   r   r|   r  r   )r.   r/   r0   r1   r   r   r   r   r   r	  r  r  r   rE   r   rR   r2   r   r   s   @r4   r(   r(   	  s   CJ H
, 
< "  /55 5 	5

5
5. /5 5>VV /V 	V
 
V"[[ /[ 	[
 
["WW /W 	W
 
W Wr3   r(   c            
        ^  \ rS rSrSr\r " S S\5      rSSSS\	R                  \	R                  \	R                  SSS4
                   SU 4S	 jjjr            SS
 jr            SS jr            SS jr            SS jr\SS j5       r\SS j5       rSS jrSS jrSS jr    SS jrSrU =r$ ) r"   i
  aj  Crop and pad images by pixel amounts or fractions of image sizes.

This transform allows for simultaneous cropping and padding of images. Cropping removes pixels from the sides
(i.e., extracts a subimage), while padding adds pixels to the sides (e.g., black pixels). The amount of
cropping/padding can be specified either in absolute pixels or as a fraction of the image size.

Args:
    px (int, tuple of int, tuple of tuples of int, or None):
        The number of pixels to crop (negative values) or pad (positive values) on each side of the image.
        Either this or the parameter `percent` may be set, not both at the same time.
        - If int: crop/pad all sides by this value.
        - If tuple of 2 ints: crop/pad by (top/bottom, left/right).
        - If tuple of 4 ints: crop/pad by (top, right, bottom, left).
        - Each int can also be a tuple of 2 ints for a range, or a list of ints for discrete choices.
        Default: None.

    percent (float, tuple of float, tuple of tuples of float, or None):
        The fraction of the image size to crop (negative values) or pad (positive values) on each side.
        Either this or the parameter `px` may be set, not both at the same time.
        - If float: crop/pad all sides by this fraction.
        - If tuple of 2 floats: crop/pad by (top/bottom, left/right) fractions.
        - If tuple of 4 floats: crop/pad by (top, right, bottom, left) fractions.
        - Each float can also be a tuple of 2 floats for a range, or a list of floats for discrete choices.
        Default: None.

    border_mode (int):
        OpenCV border mode used for padding. Default: cv2.BORDER_CONSTANT.

    fill (tuple[float, ...] | float):
        The constant value to use for padding if border_mode is cv2.BORDER_CONSTANT.
        Default: 0.

    fill_mask (tuple[float, ...] | float):
        Same as fill but used for mask padding. Default: 0.

    keep_size (bool):
        If True, the output image will be resized to the input image size after cropping/padding.
        Default: True.

    sample_independently (bool):
        If True and ranges are used for px/percent, sample a value for each side independently.
        If False, sample one value and use it for all sides. Default: True.

    interpolation (int):
        OpenCV interpolation flag used for resizing if keep_size is True.
        Default: cv2.INTER_LINEAR.

    mask_interpolation (int):
        OpenCV interpolation flag used for resizing if keep_size is True.
        Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
        Default: cv2.INTER_NEAREST.

    p (float):
        Probability of applying the transform. Default: 1.0.

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

Image types:
    uint8, float32

Note:
    - This transform will never crop images below a height or width of 1.
    - When using pixel values (px), the image will be cropped/padded by exactly that many pixels.
    - When using percentages (percent), the amount of crop/pad will be calculated based on the image size.
    - Bounding boxes that end up fully outside the image after cropping will be removed.
    - Keypoints that end up outside the image after cropping will be removed.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # 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([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Example 1: Using px parameter with specific values for each side
    >>> # Crop 10px from top, pad 20px on right, pad 30px on bottom, crop 40px from left
    >>> transform_px = A.Compose([
    ...     A.CropAndPad(
    ...         px=(-10, 20, 30, -40),  # (top, right, bottom, left)
    ...         border_mode=cv2.BORDER_CONSTANT,
    ...         fill=128,  # Gray padding color
    ...         fill_mask=0,
    ...         keep_size=False,  # Don't resize back to original dimensions
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> result_px = transform_px(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data with px parameters
    >>> transformed_image_px = result_px['image']  # Shape will be different from original
    >>> transformed_mask_px = result_px['mask']
    >>> transformed_bboxes_px = result_px['bboxes']  # Adjusted to new dimensions
    >>> transformed_bbox_labels_px = result_px['bbox_labels']  # Bounding box labels after crop
    >>> transformed_keypoints_px = result_px['keypoints']  # Adjusted to new dimensions
    >>> transformed_keypoint_labels_px = result_px['keypoint_labels']  # Keypoint labels after crop
    >>>
    >>> # Example 2: Using percent parameter as a single value
    >>> # This will pad all sides by 10% of image dimensions
    >>> transform_percent = A.Compose([
    ...     A.CropAndPad(
    ...         percent=0.1,  # Pad all sides by 10%
    ...         border_mode=cv2.BORDER_REFLECT,  # Use reflection padding
    ...         keep_size=True,  # Resize back to original dimensions
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> result_percent = transform_percent(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data with percent parameters
    >>> # Since keep_size=True, image dimensions remain the same (100x100)
    >>> transformed_image_pct = result_percent['image']
    >>> transformed_mask_pct = result_percent['mask']
    >>> transformed_bboxes_pct = result_percent['bboxes']
    >>> transformed_bbox_labels_pct = result_percent['bbox_labels']
    >>> transformed_keypoints_pct = result_percent['keypoints']
    >>> transformed_keypoint_labels_pct = result_percent['keypoint_labels']
    >>>
    >>> # Example 3: Random padding within a range
    >>> # Pad top and bottom by 5-15%, left and right by 10-20%
    >>> transform_random = A.Compose([
    ...     A.CropAndPad(
    ...         percent=[(0.05, 0.15), (0.1, 0.2), (0.05, 0.15), (0.1, 0.2)],  # (top, right, bottom, left)
    ...         sample_independently=True,  # Sample each side independently
    ...         border_mode=cv2.BORDER_CONSTANT,
    ...         fill=0,  # Black padding
    ...         keep_size=False,
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Result dimensions will vary based on the random padding values chosen

c                      \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	\S
'   S	\S'   S\S'   S\S'   S\S'   \" SS9SS j5       rSrg)CropAndPad.InitSchemaiO  zPxType | NonepxzPercentType | Nonepercentr   	keep_sizesample_independentlyrm  rn  ro  r   r   r   r   r   r  r  c                    U R                   c  U R                  c  Sn[        U5      eU R                   b  U R                  b  Sn[        U5      eU $ )Nz=Both px and percent parameters cannot be None simultaneously.zOnly px or percent may be set!)r  r  r  r  s     r4   _check_px_percent'CropAndPad.InitSchema._check_px_percentp  sJ    ww4<<#7U o%ww"t||'?6 o%Kr3   r-   Nr   )r.   r/   r0   r1   r   r   r  r2   r-   r3   r4   r   r  O  s^    ##""
 	

 	
 (',,
 	
 
g	&	 
'	r3   r   NTr   r   c                   > [         TU ]  U
S9  Xl        X l        Xpl        Xl        Xl        X0l        X@l        XPl	        X`l
        g r   )r   r   r  r  r   r   r   r  r  rn  ro  )rA   r  r  r  r  rn  ro  r   r   r   r   r   s              r4   r   CropAndPad.__init__{  sG    F 	1&	""$8!*"4r3   c           
         [         R                  " UUUUUS   SS U R                  U R                  U R                  5      $ )a  Apply the crop and pad transform to an image.

Args:
    img (np.ndarray): The image to apply the crop and pad transform to.
    crop_params (Sequence[int]): The parameters for the crop.
    pad_params (Sequence[int]): The parameters for the pad.
    fill (tuple[float, ...] | float): The value to fill the image with.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The image after the crop and pad transform.

rH   Nr9   )r?   crop_and_padrn  r   r  )rA   rB   crop_paramsr   r   rD   s         r4   rE   CropAndPad.apply  sJ    * ""7OBQNN	
 		
r3   c           
         [         R                  " UUUUUS   SS U R                  U R                  U R                  5      $ )a  Apply the crop and pad transform to a mask.

Args:
    mask (np.ndarray): The mask to apply the crop and pad transform to.
    crop_params (Sequence[int]): The parameters for the crop.
    pad_params (Sequence[int]): The parameters for the pad.
    fill_mask (tuple[float, ...] | float): The value to fill the mask with.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The mask after the crop and pad transform.

rH   Nr9   )r?   r  ro  r   r  )rA   r   r  r   r   rD   s         r4   r   CropAndPad.apply_to_mask  sJ    * ""7OBQ##NN	
 		
r3   c                >    [         R                  " XX5S   SS U5      $ )a  Apply the crop and pad transform to bounding boxes.

Args:
    bboxes (np.ndarray): The bounding boxes to apply the crop and pad transform to.
    crop_params (tuple[int, int, int, int]): The parameters for the crop.
    pad_params (tuple[int, int, int, int]): The parameters for the pad.
    result_shape (tuple[int, int]): The shape of the result.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The bounding boxes after the crop and pad transform.

rH   Nr9   )r?   crop_and_pad_bboxes)rA   rL   r  r   result_shaperD   s         r4   rM   CropAndPad.apply_to_bboxes  s(    * ))&zRY?[]\]K^`lmmr3   c                X    [         R                  " UUUUS   SS UU R                  5      $ )a  Apply the crop and pad transform to keypoints.

Args:
    keypoints (np.ndarray): The keypoints to apply the crop and pad transform to.
    crop_params (tuple[int, int, int, int]): The parameters for the crop.
    pad_params (tuple[int, int, int, int]): The parameters for the pad.
    result_shape (tuple[int, int]): The shape of the result.
    params (dict[str, Any]): Additional parameters for the transform.

Returns:
    np.ndarray: The keypoints after the crop and pad transform.

rH   Nr9   )r?   crop_and_pad_keypointsr  )rA   rQ   r  r   r  rD   s         r4   rR   CropAndPad.apply_to_keypoints  s8    * ,,7OBQNN
 	
r3   c                    [        U5      S-   nUS-  nUS-  nXE-   U:  a  US-  nX@:  a  X@-
  nU nXV-  nOXQ:  a
  XQ-
  nUnXF-  nX-
  X-
  4$ )Nr   r9   )abs)val1val2max_valregainregain1regain2diffs          r4   __prevent_zeroCropAndPad.__prevent_zero"  su    W!A+A+v%qLG>>DGOG^>DGOG~t~--r3   c                    U u  p4pVXU-   -
  nX&U-   -
  nUS:  a  [         R                  X5U5      u  p5US:  a  [         R                  XdU5      u  pd[        US5      [        US5      [        US5      [        US5      /$ )Nr   r   )r"   _CropAndPad__prevent_zeror$  )	r  rx   ry   toprightbottomleftremaining_heightremaining_widths	            r4   _prevent_zeroCropAndPad._prevent_zero5  s    #. F!6\2%<0a$33CHKCQ$33DGKDCS]CNCaLIIr3   c           	        US   SS u  p4U R                   b  U R                  5       nORU R                  5       n[        US   U-  5      [        US   U-  5      [        US   U-  5      [        US   U-  5      /nU Vs/ s H  n[	        US5      PM     nnU R                  U Vs/ s H  n[        US5      * PM     snX45      n	U	u  ppXXK-
  X<-
  /n	U	S   U	S   -
  nU	S   U	S   -
  nX:X  a  X:X  a  / n	Uu  ppXX/n[        U5      (       a  XU-   -  nXU-   -  nO/ nU	=(       d    SU=(       d    SUc  SOU R                  U R                  5      Uc  SO$U R                  [        SU R                  5      5      X4S.$ s  snf s  snf )	zGet the parameters for the crop.

Args:
    params (dict[str, Any]): The parameters for the transform.
    data (dict[str, Any]): The data for the transform.

Returns:
    dict[str, Any]: The parameters for the crop.

rH   Nr9   r   r   r:   zUnion[tuple[float, ...], float])r  r   r   r   r  )r  _get_px_params_get_percent_paramsr  r$  r   minr9  _get_pad_valuer   r	   r   )rA   rD   r   rx   ry   
new_paramspercent_paramsr  r   r  r  r  r  r  result_rowsresult_colss                   r4   r  'CropAndPad.get_params_dependent_on_dataC  s    w+77,,.J!557NN1%./N1%-.N1%./N1%-.	J *44Ac!Qi
4((j)Ij3q!9*j)I6Y#. F%-A!!n{1~5!!n{1~5K$9K#- F4/
z??<'K%<'KJ '.$$,&.DD4G4G		4R! $$T*KT^^%\](6
 	
' 5)Is   ?F &Fc                D   U R                   c  Sn[        U5      e[        U R                   [        5      (       a  U R                   /S-  $ [	        U R                   5      [
        :X  av  U R                  (       a<  [        S5       Vs/ s H%  o R                  R                  " U R                   6 PM'     sn$ U R                  R                  " U R                   6 nU/S-  $ [        U R                   S   [        5      (       a  U R                   $ [	        U R                   S   5      [
        :X  a3  U R                    Vs/ s H  o@R                  R                  " U6 PM     sn$ U R                    Vs/ s H  o@R                  R                  U5      PM     sn$ s  snf s  snf s  snf )Nzpx is not setr   r   )r  r  
isinstancer  rX  r   r  rM  r   	randranger]  )rA   r  r  r  r  s        r4   r#  CropAndPad._get_px_paramsx  s.   77?!CS/!dggs##GG9q= tww<4((DI!HMHq00$'':HMM))4773B4!8Odggaj#&&77Ntwwqz?d":>''B'QNN,,a0'BB26'':'Q%%a(':: N C:s   ,F9"F,$Fc                d   U R                   c  Sn[        U5      e[        U R                   [        5      (       a  U R                   /S-  nU$ [	        U R                   5      [
        :X  az  U R                  (       a=  [        S5       Vs/ s H%  o0R                  R                  " U R                   6 PM'     nnU$ U R                  R                  " U R                   6 nU/S-  n U$ [        U R                   S   [        [        45      (       a  U R                   nU$ [	        U R                   S   5      [
        :X  a4  U R                    Vs/ s H  oPR                  R                  " U6 PM     nnU$ U R                    Vs/ s H  oPR                  R                  U5      PM     nnU$ s  snf s  snf s  snf )Nzpercent is not setr   r   )r  r  r-  r   rX  r   r  rM  r   r  r  r]  )rA   r  rD   r  r  r  s         r4   r$  CropAndPad._get_percent_params  sd   <<&CS/!dllE**ll^a'F  $&((INqRA..00$,,?R  ^^++T\\:  Q#u66\\F  a!T):>,,G,Qnn,,a0,FG  9=E1nn++A.FE S HEs   ,F#"F(;$F-c                   [        U[        [        45      (       a  [        U5      [        :X  ad  Uu  p#[        U[
        5      (       a0  [        U[
        5      (       a  U R                  R                  X#5      $ U R                  R                  X#5      $ U R                  R                  U5      $ [        U[
        [        45      (       a  U$ Sn[        U5      e)Nz9fill should be a number or list, or tuple of two numbers.)r-  listtuplerX  r   r  r   r^  r  r]  r   r  )rA   r   abr  s        r4   r&  CropAndPad._get_pad_value  s     dT5M**4yD a%%*Q*<*<>>11!77~~--a33>>((..dS%L))KIor3   )	r   r   r   rn  r  ro  r  r  r  )r  zint | list[int] | Noner  zfloat | list[float] | Noner  r   r  r   rn  rm  ro  rm  r   r   r   r   r   r   r   r   )rB   r}   r  Sequence[int]r   r8  r   r   rD   r   r   r}   )r   r}   r  r8  r   r8  r   r   rD   r   r   r}   )rL   r}   r  r~   r   r~   r  r   rD   r   r   r}   )rQ   r}   r  r~   r   r~   r  r   rD   r   r   r}   )r  r  r  r  r  r  r   r   )r  	list[int]rx   r  ry   r  r   r9  r  )r   r9  )r   zlist[float])r   zSequence[float] | floatr   zint | float)r.   r/   r0   r1   r   r   r   r   r   r	  r  r  r
  r   rE   r   rM   rR   r   r  r   r  r#  r$  r&  r2   r   r   s   @r4   r"   r"   
  s$   `D H*, *\ &*.2%)   *+/0C05"05 ,05 	05
 #05
05
050
105> (?05@ -A05B C05 05d

 #
 "	

 (
 
 

@

 #
 "	

 -
 
 

@nn /n .	n
 &n n 
n.

 /
 .	

 &
 
 

< . .$ J J3
j;&,% 
 r3   r"   c                     ^  \ rS rSrSr\r " S S\5      r     S         S	U 4S jjjr	      S
S jr
SrU =r$ )r%   i  a  Randomly crops the input from its borders without resizing.

This transform randomly crops parts of the input (image, mask, bounding boxes, or keypoints)
from each of its borders. The amount of cropping is specified as a fraction of the input's
dimensions for each side independently.

Args:
    crop_left (float): The maximum fraction of width to crop from the left side.
        Must be in the range [0.0, 1.0]. Default: 0.1
    crop_right (float): The maximum fraction of width to crop from the right side.
        Must be in the range [0.0, 1.0]. Default: 0.1
    crop_top (float): The maximum fraction of height to crop from the top.
        Must be in the range [0.0, 1.0]. Default: 0.1
    crop_bottom (float): The maximum fraction of height to crop from the bottom.
        Must be in the range [0.0, 1.0]. Default: 0.1
    p (float): Probability of applying the transform. Default: 1.0

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

Image types:
    uint8, float32

Note:
    - The actual amount of cropping for each side is randomly chosen between 0 and
      the specified maximum for each application of the transform.
    - The sum of crop_left and crop_right must not exceed 1.0, and the sum of
      crop_top and crop_bottom must not exceed 1.0. Otherwise, a ValueError will be raised.
    - This transform does not resize the input after cropping, so the output dimensions
      will be smaller than the input dimensions.
    - Bounding boxes that end up fully outside the cropped area will be removed.
    - Keypoints that end up outside the cropped area will be removed.

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.random.randint(0, 2, (100, 100), dtype=np.uint8)
    >>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
    >>> bbox_labels = [1, 2]
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]
    >>>
    >>> # Define transform with crop fractions for each border
    >>> transform = A.Compose([
    ...     A.RandomCropFromBorders(
    ...         crop_left=0.1,     # Max 10% crop from left
    ...         crop_right=0.2,    # Max 20% crop from right
    ...         crop_top=0.15,     # Max 15% crop from top
    ...         crop_bottom=0.05,  # Max 5% crop from bottom
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply transform
    >>> result = transform(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Access transformed data
    >>> transformed_image = result['image']  # Reduced size image with borders cropped
    >>> transformed_mask = result['mask']    # Reduced size mask with borders cropped
    >>> transformed_bboxes = result['bboxes']  # Bounding boxes adjusted to new dimensions
    >>> transformed_bbox_labels = result['bbox_labels']  # Bounding box labels after crop
    >>> transformed_keypoints = result['keypoints']  # Keypoints adjusted to new dimensions
    >>> transformed_keypoint_labels = result['keypoint_labels']  # Keypoint labels after crop
    >>>
    >>> # The resulting output shapes will be smaller, with dimensions reduced by
    >>> # the random crop amounts from each side (within the specified maximums)
    >>> print(f"Original image shape: (100, 100, 3)")
    >>> print(f"Transformed image shape: {transformed_image.shape}")  # e.g., (85, 75, 3)

c                      \ rS rSr% \" SSS9rS\S'   \" SSS9rS\S'   \" SSS9rS\S'   \" SSS9r	S\S	'   \
" S
S9SS j5       rSrg) RandomCropFromBorders.InitSchemai	  r   r   r  r   	crop_left
crop_rightcrop_topcrop_bottomr  r  c                    U R                   U R                  -   S:  a  Sn[        U5      eU R                  U R                  -   S:  a  Sn[        U5      eU $ )Nr   z1The sum of crop_left and crop_right must be <= 1.z1The sum of crop_top and crop_bottom must be <= 1.)r=  r>  r  r?  r@  r  s     r4   _validate_crop_values6RandomCropFromBorders.InitSchema._validate_crop_values  sQ    ~~/#5I o%}}t///#5I o%Kr3   r-   Nr   )r.   r/   r0   r1   r   r=  r   r>  r?  r@  r   rB  r2   r-   r3   r4   r   r<  	  s}     
	5 	
 "

E 	
  
% 	
 #
U 	

 
g	&	 
'	r3   r   c                P   > [         TU ]  US9  Xl        X l        X0l        X@l        g r   )r   r   r=  r>  r?  r@  )rA   r=  r>  r?  r@  r   r   s         r4   r   RandomCropFromBorders.__init__%  s*     	1"$ &r3   c           	        US   SS u  p4U R                   R                  S[        U R                  U-  5      5      nU R                   R                  [	        US-   [        SU R
                  -
  U-  5      5      U5      nU R                   R                  S[        U R                  U-  5      5      nU R                   R                  [	        US-   [        SU R                  -
  U-  5      5      U5      nXWXh4n	SU	0$ )zGet the parameters for the crop.

Args:
    params (dict[str, Any]): The parameters for the transform.
    data (dict[str, Any]): The data for the transform.

Returns:
    dict[str, tuple[int, int, int, int]]: The parameters for the crop.

rH   Nr9   r   r   rC   )r   r^  r  r=  r$  r>  r?  r@  )
rA   rD   r   rx   ry   r;   r=   r<   r>   rC   s
             r4   r  2RandomCropFromBorders.get_params_dependent_on_data3  s     w+&&q#dnnu.D*EF&&s519c1t;NRW:W6X'Y[`a&&q#dmmf.D*EF&&s519c1t?O?O;OSY:Y6Z'[]cdE0{++r3   )r@  r=  r>  r?  )皙?rH  rH  rH  r   )
r=  r   r>  r   r?  r   r@  r   r   r   r  )r.   r/   r0   r1   r   r   r   r   r   r   r  r2   r   r   s   @r4   r%   r%     s    Pd H, <  '' ' 	'
 ' ' ',, , 
.	, ,r3   r%   c                     ^  \ rS rSrSr\r " S S\R                  5      r  S       S	U 4S jjjr	      S
S jr
SrU =r$ )r   iO  a  Crop an area from image while ensuring at least one bounding box is present in the crop.

Similar to BBoxSafeRandomCrop, but with a key difference:
- BBoxSafeRandomCrop ensures ALL bounding boxes are preserved in the crop
- AtLeastOneBBoxRandomCrop ensures AT LEAST ONE bounding box is present in the crop

This makes AtLeastOneBBoxRandomCrop more flexible for scenarios where:
- You want to focus on individual objects rather than all objects
- You're willing to lose some bounding boxes to get more varied crops
- The image has many bounding boxes and keeping all of them would be too restrictive

The algorithm:
1. If bounding boxes exist:
    - Randomly selects a reference bounding box from available boxes
    - Computes an eroded version of this box (shrunk by erosion_factor)
    - Calculates valid crop bounds that ensure overlap with the eroded box
    - Randomly samples crop coordinates within these bounds
2. If no bounding boxes exist:
    - Uses full image dimensions as valid bounds
    - Randomly samples crop coordinates within these bounds

Args:
    height (int): Fixed height of the crop
    width (int): Fixed width of the crop
    erosion_factor (float, optional): Factor by which to erode (shrink) the reference
        bounding box when computing valid crop regions. Must be in range [0.0, 1.0].
        - 0.0 means no erosion (crop must fully contain the reference box)
        - 1.0 means maximum erosion (crop can be anywhere that intersects the reference box)
        Defaults to 0.0.
    p (float, optional): Probability of applying the transform. Defaults to 1.0.

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

Image types:
    uint8, float32

Raises:
    CropSizeError: If requested crop size exceeds image dimensions

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # Prepare sample data
    >>> image = np.random.randint(0, 256, (300, 300, 3), dtype=np.uint8)
    >>> mask = np.random.randint(0, 2, (300, 300), dtype=np.uint8)
    >>> # Create multiple bounding boxes - the transform will ensure at least one is in the crop
    >>> bboxes = np.array([
    ...     [30, 50, 100, 140],   # first box
    ...     [150, 120, 270, 250], # second box
    ...     [200, 30, 280, 90]    # third box
    ... ], dtype=np.float32)
    >>> bbox_labels = [1, 2, 3]
    >>> keypoints = np.array([
    ...     [50, 70],    # keypoint inside first box
    ...     [190, 170],  # keypoint inside second box
    ...     [240, 60]    # keypoint inside third box
    ... ], dtype=np.float32)
    >>> keypoint_labels = [0, 1, 2]
    >>>
    >>> # Define transform with different erosion_factor values
    >>> transform = A.Compose([
    ...     A.AtLeastOneBBoxRandomCrop(
    ...         height=200,
    ...         width=200,
    ...         erosion_factor=0.2,  # Allows moderate flexibility in crop placement
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
    ...    keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
    >>>
    >>> # 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']       # Shape: (200, 200, 3)
    >>> transformed_mask = transformed['mask']         # Shape: (200, 200)
    >>> transformed_bboxes = transformed['bboxes']     # At least one bbox is guaranteed
    >>> transformed_bbox_labels = transformed['bbox_labels']  # Labels for the preserved bboxes
    >>> transformed_keypoints = transformed['keypoints']      # Only keypoints in crop are kept
    >>> transformed_keypoint_labels = transformed['keypoint_labels']  # Their labels
    >>>
    >>> # Verify that at least one bounding box was preserved
    >>> assert len(transformed_bboxes) > 0, "Should have at least one bbox in the crop"
    >>>
    >>> # With erosion_factor=0.0, the crop must fully contain the selected reference bbox
    >>> conservative_transform = A.Compose([
    ...     A.AtLeastOneBBoxRandomCrop(
    ...         height=200,
    ...         width=200,
    ...         erosion_factor=0.0,  # No erosion - crop must fully contain a bbox
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
    >>>
    >>> # With erosion_factor=1.0, the crop must only intersect with the selected reference bbox
    >>> flexible_transform = A.Compose([
    ...     A.AtLeastOneBBoxRandomCrop(
    ...         height=200,
    ...         width=200,
    ...         erosion_factor=1.0,  # Maximum erosion - crop only needs to intersect a bbox
    ...         p=1.0
    ...     ),
    ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))

Note:
    - Uses fixed crop dimensions (height and width)
    - Bounding boxes that end up partially outside the crop will be adjusted
    - Bounding boxes that end up completely outside the crop will be removed
    - If no bounding boxes are provided, acts as a regular random crop

c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg)	#AtLeastOneBBoxRandomCrop.InitSchemai  r   rx   ry   z'Annotated[float, Field(ge=0.0, le=1.0)]erosion_factorr-   Nr   r-   r3   r4   r   rK    s    ++**??r3   r   c                D   > [         TU ]  US9  Xl        X l        X0l        g r   )r   r   rx   ry   rL  )rA   rx   ry   rL  r   r   s        r4   r   !AtLeastOneBBoxRandomCrop.__init__  s%     	1
,r3   c                n   US   SS u  p4UR                  S/ 5      nU R                  U:  d  U R                  U:  a(  [        SU R                  U R                  4 SX44 35      e[	        U5      S:  Ga  [        XSU4S9nU R                  R                  U5      nUSS	 u  pxpU R                  S
:  a  X-
  nX-
  nUS
U R                  -
  -  nUS
U R                  -
  -  n[        R                  " X}-   U R                  -
  SX@R                  -
  S9n[        R                  " X-
  SX@R                  -
  S9n[        R                  " X-   U R                  -
  SX0R                  -
  S9n[        R                  " X-
  SX0R                  -
  S9nO[        R                  " XpR                  -
  SX@R                  -
  S9n[        R                  " U	SX@R                  -
  S9n[        R                  " XR                  -
  SX0R                  -
  S9n[        R                  " U
SX0R                  -
  S9nO SnX@R                  -
  nSnX0R                  -
  n[        U R                  R                  UUS95      n[        U R                  R                  UUS95      nUU R                  -   nUU R                  -   nSUUUU40$ )zGet the parameters for the crop.

Args:
    params (dict[str, Any]): The parameters for the transform.
    data (dict[str, Any]): The data for the transform.

rH   Nr9   rL   r   r   r   )rH   r   r   r   )r5  a_mina_max)r5  r6  rC   )r   rx   ry   r+   rX  r   r   r]  rL  rt   ru   r  r  )rA   rD   r   r   r   rL   reference_bboxbbox_x1bbox_y1bbox_x2bbox_y2
bbox_widthbbox_heighteroded_widtheroded_height
min_crop_x
max_crop_x
min_crop_y
max_crop_ycrop_x1crop_y1crop_x2crop_y2s                          r4   r  5AtLeastOneBBoxRandomCrop.get_params_dependent_on_data  s    %+7OBQ$7!(B';;%k)A[[$**-.d<3L2MO 
 v;?'[6QRF "^^226:N1?1C.Gg
 ""S($.
%/)S43F3F-FG +sT5H5H/H IWW,tzz9%

2

  WW,%

2
  WW-;&4

  WW-&4
  WW

*%

2

  WW%

2
  WW+&4

  WW&4
 J$zz1JJ%3J dnn,,zZ,HIdnn,,zZ,HIDJJ&DKK''7CDDr3   )rL  rx   ry   r  )rx   r  ry   r  rL  r   r   r   r  )r.   r/   r0   r1   r   r   r   r6   r   r   r  r2   r   r   s   @r4   r   r   O  s    xt H@X(( @ !$
-
- 
- 	
-
 
- 
-bEbE bE 
.	bE bEr3   r   )?r   
__future__r   r  collections.abcr   typingr   r   r   r   r	   r	  numpyrt   pydanticr
   r   r   typing_extensionsr   &albumentations.augmentations.geometricr   r   albumentations.core.bbox_utilsr   r   r   albumentations.core.pydanticr   r   r   r   (albumentations.core.transforms_interfacer   r   $albumentations.core.type_definitionsr   r   r   r   r    r?   __all__	Exceptionr+   r6   r   r$   r    r!   r#   rf  rj  r)   r'   r&   r   r(   r"   r%   r   r-   r3   r4   <module>rr     sc   #  $ 7 7 
  ; ; " K ` `  \  # 	I 	@*} @*F^SX ^SB{
 {
|x
 x
vik> ikXA=x A=HR$; REC= ECP
u,* u,p[,, [,|S( S(lhQ hQV{W0 {W|G GTX,H X,vpEx pEr3   