
    h}                        S r SSKJr  SSKrSSKJrJr  SSKrSSKr	SSK
Jr  SSKJr  SSKJr  SSKJr  SS	KJrJr  SS
KJr  SSKJr  / SQrSr " S S\5      r " S S\5      r " S S\5      r " S S\5      rg)zTransforms for rotating images and associated data.

This module provides classes for rotating images, masks, bounding boxes, and keypoints.
Includes transforms for 90-degree rotations and arbitrary angle rotations with various
border handling options.
    )annotationsN)Anycast)Literal)
functional)Affine)SymmetricRangeType)BaseTransformInitSchemaDualTransform)ALL_TARGETS   )RandomRotate90Rotate
SafeRotateg|=c                     ^  \ rS rSrSr\r S 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$ )r   !   u  Randomly rotate the input by 90 degrees zero or more times.

Even with p=1.0, the transform has a 1/4 probability of being identity:
- With probability p * 1/4: no rotation (0 degrees)
- With probability p * 1/4: rotate 90 degrees
- With probability p * 1/4: rotate 180 degrees
- With probability p * 1/4: rotate 270 degrees

For example:
- With p=1.0: Each rotation angle (including 0°) has 0.25 probability
- With p=0.8: Each rotation angle has 0.2 probability, and no transform has 0.2 probability
- With p=0.5: Each rotation angle has 0.125 probability, and no transform has 0.5 probability

Common applications:
- Aerial/satellite imagery: Objects can appear in any orientation
- Medical imaging: Scans/slides may not have a consistent orientation
- Document analysis: Pages or symbols might be rotated
- Microscopy: Cell orientation is often arbitrary
- Game development: Sprites/textures that should work in multiple orientations

Not recommended for:
- Natural scene images where gravity matters (e.g., landscape photography)
- Face detection/recognition tasks
- Text recognition (unless text can appear rotated)
- Tasks where object orientation is important for classification

Note:
    If your domain has both 90-degree rotation AND flip symmetries
    (e.g., satellite imagery, microscopy), consider using `D4` transform instead.
    `D4` is more efficient and mathematically correct as it:
    - Samples uniformly from all 8 possible combinations of rotations and flips
    - Properly represents the dihedral group D4 symmetries
    - Avoids potential correlation between separate rotation and flip augmentations

Args:
    p (float): probability of applying the transform. Default: 1.0.
        Note that even with p=1.0, there's still a 0.25 probability
        of getting a 0-degree rotation (identity transform).

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

Image types:
    uint8, float32

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> # Create example 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]  # Class labels for bounding boxes
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]  # Labels for keypoints
    >>> # Define the transform
    >>> transform = A.Compose([
    ...     A.RandomRotate90(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 to all targets
    >>> transformed = transform(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>> rotated_image = transformed["image"]
    >>> rotated_mask = transformed["mask"]
    >>> rotated_bboxes = transformed["bboxes"]
    >>> rotated_bbox_labels = transformed["bbox_labels"]
    >>> rotated_keypoints = transformed["keypoints"]
    >>> rotated_keypoint_labels = transformed["keypoint_labels"]

c                    > [         TU ]  US9  g )Np)super__init__)selfr   	__class__s     g/var/www/fran/franai/venv/lib/python3.13/site-packages/albumentations/augmentations/geometric/rotate.pyr   RandomRotate90.__init__r   s     	1    c                .    [         R                  " X5      $ )zApply rotation to the input image.

Args:
    img (np.ndarray): Image to rotate.
    factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Rotated image.

)
fgeometricrot90)r   imgfactorparamss       r   applyRandomRotate90.applyx   s     ,,r   c                >    SU R                   R                  SS5      0$ )zfGet parameters for the transform.

Returns:
    dict[str, int]: Dictionary with the rotation factor.

r!   r      )	py_randomrandint)r   s    r   
get_paramsRandomRotate90.get_params   s      $..00A677r   c                .    [         R                  " X5      $ )a  Apply rotation to bounding boxes.

Args:
    bboxes (np.ndarray): Bounding boxes to rotate.
    factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Rotated bounding boxes.

)r   bboxes_rot90)r   bboxesr!   r"   s       r   apply_to_bboxesRandomRotate90.apply_to_bboxes   s    " &&v66r   c                6    [         R                  " XUS   5      $ )zApply rotation to keypoints.

Args:
    keypoints (np.ndarray): Keypoints to rotate.
    factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Rotated keypoints.

shape)r   keypoints_rot90)r   	keypointsr!   r"   s       r   apply_to_keypoints!RandomRotate90.apply_to_keypoints   s    " )))VG_MMr   c                .    [         R                  " X5      $ )zApply rotation to the input volume.

Args:
    volume (np.ndarray): Volume to rotate.
    factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Rotated volume.

r   volume_rot90)r   volumer!   r"   s       r   apply_to_volumeRandomRotate90.apply_to_volume        &&v66r   c                .    [         R                  " X5      $ )zApply rotation to the input volumes.

Args:
    volumes (np.ndarray): Volumes to rotate.
    factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Rotated volumes.

r   volumes_rot90)r   volumesr!   r"   s       r   apply_to_volumesRandomRotate90.apply_to_volumes        ''88r   c                .    [         R                  " X5      $ )zApply rotation to the input mask3d.

Args:
    mask3d (np.ndarray): Mask3d to rotate.
    factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Rotated mask3d.

r7   )r   mask3dr!   r"   s       r   apply_to_mask3dRandomRotate90.apply_to_mask3d   r<   r   c                .    [         R                  " X5      $ )zApply rotation to the input masks3d.

Args:
    masks3d (np.ndarray): Masks3d to rotate.
    factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Rotated masks3d.

r>   )r   masks3dr!   r"   s       r   apply_to_masks3dRandomRotate90.apply_to_masks3d   rC   r    )r   )r   float)r    
np.ndarrayr!   Literal[0, 1, 2, 3]r"   r   returnrN   )rP   dict[str, int])r-   rN   r!   rO   r"   r   rP   rN   )r3   rN   r!   rO   r"   r   rP   rN   )r9   rN   r!   rO   r"   r   rP   rN   )r@   rN   r!   rO   r"   r   rP   rN   )rE   rN   r!   rO   r"   r   rP   rN   )rI   rN   r!   rO   r"   r   rP   rN   )__name__
__module____qualname____firstlineno____doc__r   _targetsr   r#   r)   r.   r4   r:   rA   rF   rJ   __static_attributes____classcell__r   s   @r   r   r   !   s    L\ H  -877 $7 	7
 
7&NN $N 	N
 
N&7979 9r   r   c                  R    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	\S
'   S\S'   Srg)RotateInitSchema   r	   limitaLiteral[cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]interpolationmask_interpolationoLiteral[cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101]border_modetuple[float, ...] | floatfillz tuple[float, ...] | float | None	fill_maskrL   NrR   rS   rT   rU   __annotations__rX   rL   r   r   r\   r\      s0    tt   $#//r   r\   c            	        ^  \ rS rSrSr\r " S S\5      rS\	R                  \	R                  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S jr\        SS j5       r      SS jrSrU =r$ )r   i  uY  Rotate the input by an angle selected randomly from the uniform distribution.

Args:
    limit (float | tuple[float, float]): Range from which a random angle is picked. If limit is a single float,
        an angle is picked from (-limit, limit). Default: (-90, 90)
    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.
    border_mode (OpenCV flag): Flag that is used to specify the pixel extrapolation method. Should be one of:
        cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.
        Default: cv2.BORDER_CONSTANT
    fill (tuple[float, ...] | float): Padding value if border_mode is cv2.BORDER_CONSTANT.
    fill_mask (tuple[float, ...] | float): Padding value if border_mode is cv2.BORDER_CONSTANT applied for masks.
    rotate_method (Literal["largest_box", "ellipse"]): Method to rotate bounding boxes.
        Should be 'largest_box' or 'ellipse'. Default: 'largest_box'
    crop_border (bool): Whether to crop border after rotation. If True, the output image size might differ
        from the input. Default: False
    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.
    p (float): Probability of applying the transform. Default: 0.5.

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

Image types:
    uint8, float32

Note:
    - The rotation angle is randomly selected for each execution within the range specified by 'limit'.
    - When 'crop_border' is False, the output image will have the same size as the input, potentially
      introducing black triangles in the corners.
    - When 'crop_border' is True, the output image is cropped to remove black triangles, which may result
      in a smaller image.
    - Bounding boxes are rotated and may change size or shape.
    - Keypoints are rotated around the center of the image.

Mathematical Details:
    1. An angle θ is randomly sampled from the range specified by 'limit'.
    2. The image is rotated around its center by θ degrees.
    3. The rotation matrix R is:
       R = [cos(θ)  -sin(θ)]
           [sin(θ)   cos(θ)]
    4. Each point (x, y) in the image is transformed to (x', y') by:
       [x']   [cos(θ)  -sin(θ)] [x - cx]   [cx]
       [y'] = [sin(θ)   cos(θ)] [y - cy] + [cy]
       where (cx, cy) is the center of the image.
    5. If 'crop_border' is True, the image is cropped to the largest rectangle that fits inside the rotated image.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> # Create example 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]  # Class labels for bounding boxes
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]  # Labels for keypoints
    >>> # Define the transform
    >>> transform = A.Compose([
    ...     A.Rotate(limit=45, 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 to all targets
    >>> transformed = transform(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>> rotated_image = transformed["image"]
    >>> rotated_mask = transformed["mask"]
    >>> rotated_bboxes = transformed["bboxes"]
    >>> rotated_bbox_labels = transformed["bbox_labels"]
    >>> rotated_keypoints = transformed["keypoints"]
    >>> rotated_keypoint_labels = transformed["keypoint_labels"]

c                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	rg
)Rotate.InitSchemai]  !Literal['largest_box', 'ellipse']rotate_methodboolcrop_borderrd   re   rf   rL   Nrg   rL   r   r   
InitSchemark   ]  s    88'',,r   rp   iZ   largest_boxFr         ?c
                   > [         T
U ]  U	S9  [        SU5      U l        X l        X`l        X0l        Xpl        Xl        X@l	        XPl
        g )Nr   tuple[float, float])r   r   r   r^   r`   ra   rc   re   rf   rm   ro   )r   r^   r`   rc   rm   ro   ra   re   rf   r   r   s             r   r   Rotate.__init__d  sL    < 	1/7
*"4&	"*&r   c           
         [         R                  " UUU R                  U R                  U R                  US   SS 5      nU R
                  (       a  [        R                  " XXTU5      $ U$ )a  Apply affine transformation to the image.

Args:
    img (np.ndarray): Image to transform.
    matrix (np.ndarray): Affine transformation matrix.
    x_min (int): Minimum x-coordinate for cropping (if crop_border is True).
    x_max (int): Maximum x-coordinate for cropping (if crop_border is True).
    y_min (int): Minimum y-coordinate for cropping (if crop_border is True).
    y_max (int): Maximum y-coordinate for cropping (if crop_border is True).
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Transformed image.

r1   N   )r   warp_affiner`   re   rc   ro   fcropscrop)	r   r    matrixx_minx_maxy_miny_maxr"   img_outs	            r   r#   Rotate.apply  sd    2 ((II7OBQ
 ;;wuUCCr   c           
         [         R                  " UUU R                  U R                  U R                  US   SS 5      nU R
                  (       a  [        R                  " XXTU5      $ U$ )a  Apply affine transformation to the mask.

Args:
    mask (np.ndarray): Mask to transform.
    matrix (np.ndarray): Affine transformation matrix.
    x_min (int): Minimum x-coordinate for cropping (if crop_border is True).
    x_max (int): Maximum x-coordinate for cropping (if crop_border is True).
    y_min (int): Minimum y-coordinate for cropping (if crop_border is True).
    y_max (int): Maximum y-coordinate for cropping (if crop_border is True).
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Transformed mask.

r1   Nry   )r   rz   ra   rf   rc   ro   r{   r|   )	r   maskr}   r~   r   r   r   r"   r   s	            r   apply_to_maskRotate.apply_to_mask  sd    2 ((##NN7OBQ
 ;;wuUCCr   c                    US   SS n[         R                  " UUU R                  UU R                  U5      n	U R                  (       a  [
        R                  " U	X5XF4U5      $ U	$ )aQ  Apply affine transformation to bounding boxes.

Args:
    bboxes (np.ndarray): Bounding boxes to transform.
    bbox_matrix (np.ndarray): Affine transformation matrix for bounding boxes.
    x_min (int): Minimum x-coordinate for cropping (if crop_border is True).
    x_max (int): Maximum x-coordinate for cropping (if crop_border is True).
    y_min (int): Minimum y-coordinate for cropping (if crop_border is True).
    y_max (int): Maximum y-coordinate for cropping (if crop_border is True).
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Transformed bounding boxes.

r1   Nry   )r   bboxes_affinerm   rc   ro   r{   crop_bboxes_by_coords)
r   r-   bbox_matrixr~   r   r   r   r"   image_shape
bboxes_outs
             r   r.   Rotate.apply_to_bboxes  sv    2 Wobq)--

 //u, 
 r   c                    [         R                  " UUUS   SS SSS.U R                  S9nU R                  (       a  [        R
                  " UX5XF45      $ U$ )a-  Apply affine transformation to keypoints.

Args:
    keypoints (np.ndarray): Keypoints to transform.
    matrix (np.ndarray): Affine transformation matrix.
    x_min (int): Minimum x-coordinate for cropping (if crop_border is True).
    x_max (int): Maximum x-coordinate for cropping (if crop_border is True).
    y_min (int): Minimum y-coordinate for cropping (if crop_border is True).
    y_max (int): Maximum y-coordinate for cropping (if crop_border is True).
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Transformed keypoints.

r1   Nry   r   xy)scalerc   )r   keypoints_affinerc   ro   r{   crop_keypoints_by_coords)	r   r3   r}   r~   r   r   r   r"   keypoints_outs	            r   r4   Rotate.apply_to_keypoints   sj    2 #337OBQ"((
 22u,  r   c                   [         R                  " U5      nX:  nU(       a  X4OX4u  pE[        [         R                  " U5      5      [        [         R                  " U5      5      pvUSU-  U-  U-  ::  d  [        Xg-
  5      [
        :  a  SU-  nU(       a  X-  X-  4OX-  X-  4u  pO Xw-  Xf-  -
  nX-  X-  -
  U-  X-  X-  -
  U-  p[        S[        US-  U	S-  -
  5      5      [        U[        US-  U	S-  -   5      5      [        S[        U S-  U
S-  -
  5      5      [        U [        U S-  U
S-  -   5      5      S.$ )aW  Given a rectangle of size wxh that has been rotated by 'angle' (in
degrees), computes the width and height of the largest possible
axis-aligned rectangle (maximal area) within the rotated rectangle.

References:
    Rotate image and crop out black borders: https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders

g       @rt   r   ry   r~   r   r   r   )	mathradiansabssincosSMALL_NUMBERmaxintmin)heightwidthanglewidth_is_longer	side_long
side_shortsin_acos_ar   wrhrcos_2as               r   _rotated_rect_with_max_area"Rotate._rotated_rect_with_max_area'  sQ    U#/3B	 488E?+S%-Auuu,y88C<NQ]<] j A/>ai+QYPQPYDZFB ]U]2F/69%-/69  C	BF 234EAIQ$6 78C
R!V 345VaZ"q&%8!9:	
 	
r   c                   U R                   R                  " U R                  6 nU R                  (       a  US   SS u  pEU R	                  XEU5      nOSSSSS.n[
        R                  " US   SS 5      n[
        R                  " US   SS 5      nSSS.n	SSS.n
SSS.nUn[
        R                  " U	U
UUU5      n[
        R                  " U	U
UUU5      nXS	'   XS
'   U$ )Get parameters dependent on the data.

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

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

r1   Nry   r   r   r   r   r}   r   )	r'   uniformr^   ro   r   r   centercenter_bbox#create_affine_transformation_matrix)r   r"   datar   r   r   
out_paramsr   bbox_center	translateshearr   rotater}   r   s                  r   get_params_dependent_on_data#Rotate.get_params_dependent_on_dataP  s    &&

3"7OBQ/MF99&OJ#%R"MJ""6'?2A#67 ,,VG_Ra-@A*+!$4	()"2()"2??
 !DD
  &8$/=!r   )rc   ro   re   rf   r`   r^   ra   rm   )r^   tuple[float, float] | floatr`   r_   rc   rb   rm   rl   ro   rn   ra   r_   re   rd   rf   rd   r   rM   )r    rN   r}   rN   r~   r   r   r   r   r   r   r   r"   r   rP   rN   )r   rN   r}   rN   r~   r   r   r   r   r   r   r   r"   r   rP   rN   )r-   rN   r   rN   r~   r   r   r   r   r   r   r   r"   r   rP   rN   )r3   rN   r}   rN   r~   r   r   r   r   r   r   r   r"   r   rP   rN   )r   r   r   r   r   rM   rP   rQ   r"   dict[str, Any]r   r   rP   r   )rR   rS   rT   rU   rV   r   rW   r\   rp   cv2INTER_LINEARBORDER_CONSTANTINTER_NEARESTr   r#   r   r.   r4   staticmethodr   r   rX   rY   rZ   s   @r   r   r     se   Pd H-% - .7  ;H! *+/09&'*&'
&'
&'" 9#&'$ %&'&
'&'4 (5&'6 -7&'8 9&' &'P## # 	#
 # # # # 
#J## # 	#
 # # # # 
#J((  ( 	(
 ( ( ( ( 
(T%% % 	%
 % % % % 
%N &
&
&
 &
 
	&
 &
P00 0 
	0 0r   r   c                     ^  \ rS rSrSr\r " S S\5      rS\	R                  \	R                  S\	R                  SSS4               SU 4S	 jjjr        SS
 jr      SS jrSrU =r$ )r   i  uu  Rotate the input inside the input's frame by an angle selected randomly from the uniform distribution.

This transformation ensures that the entire rotated image fits within the original frame by scaling it
down if necessary. The resulting image maintains its original dimensions but may contain artifacts due to the
rotation and scaling process.

Args:
    limit (float | tuple[float, float]): Range from which a random angle is picked. If limit is a single float,
        an angle is picked from (-limit, limit). Default: (-90, 90)
    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.
    border_mode (OpenCV flag): Flag that is used to specify the pixel extrapolation method. Should be one of:
        cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.
        Default: cv2.BORDER_REFLECT_101
    fill (tuple[float, float] | float): Padding value if border_mode is cv2.BORDER_CONSTANT.
    fill_mask (tuple[float, float] | float): Padding value if border_mode is cv2.BORDER_CONSTANT applied
        for masks.
    rotate_method (Literal["largest_box", "ellipse"]): Method to rotate bounding boxes.
        Should be 'largest_box' or 'ellipse'. Default: 'largest_box'
    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.
    p (float): Probability of applying the transform. Default: 0.5.

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

Image types:
    uint8, float32

Note:
    - The rotation is performed around the center of the image.
    - After rotation, the image is scaled to fit within the original frame, which may cause some distortion.
    - The output image will always have the same dimensions as the input image.
    - Bounding boxes and keypoints are transformed along with the image.

Mathematical Details:
    1. An angle θ is randomly sampled from the range specified by 'limit'.
    2. The image is rotated around its center by θ degrees.
    3. The rotation matrix R is:
       R = [cos(θ)  -sin(θ)]
           [sin(θ)   cos(θ)]
    4. The scaling factor s is calculated to ensure the rotated image fits within the original frame:
       s = min(width / (width * |cos(θ)| + height * |sin(θ)|),
               height / (width * |sin(θ)| + height * |cos(θ)|))
    5. The combined transformation matrix T is:
       T = [s*cos(θ)  -s*sin(θ)  tx]
           [s*sin(θ)   s*cos(θ)  ty]
       where tx and ty are translation factors to keep the image centered.
    6. Each point (x, y) in the image is transformed to (x', y') by:
       [x']   [s*cos(θ)   s*sin(θ)] [x - cx]   [cx]
       [y'] = [-s*sin(θ)  s*cos(θ)] [y - cy] + [cy]
       where (cx, cy) is the center of the image.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> # Create example 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]  # Class labels for bounding boxes
    >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
    >>> keypoint_labels = [0, 1]  # Labels for keypoints
    >>> # Define the transform
    >>> transform = A.Compose([
    ...     A.SafeRotate(limit=45, 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 to all targets
    >>> transformed = transform(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>> rotated_image = transformed["image"]
    >>> rotated_mask = transformed["mask"]
    >>> rotated_bboxes = transformed["bboxes"]
    >>> rotated_bbox_labels = transformed["bbox_labels"]
    >>> rotated_keypoints = transformed["keypoints"]
    >>> rotated_keypoint_labels = transformed["keypoint_labels"]

c                       \ rS rSr% S\S'   Srg)SafeRotate.InitSchemai  rl   rm   rL   Nrg   rL   r   r   rp   r     s    88r   rp   rq   rs   r   rt   c	                R   > [         T	U ]  UUUUUUSUUS9	  [        SU5      U l        g )NT)	r   r`   rc   re   rf   rm   
fit_outputra   r   rv   )r   r   r   r^   )
r   r^   r`   rc   rm   ra   re   rf   r   r   s
            r   r   SafeRotate.__init__  sC    : 	'#'1 	 
	
 /7
r   c                   US S u  pE[         R                  " X!S5      n[        US   5      n[        US   5      n[        XH-  XW-  -   5      n	[        XG-  XX-  -   5      n
US==   U	S-  US   -
  -  ss'   US==   U
S-  US   -
  -  ss'   XY-  nXJ-  n[        R
                  " USS/SUS// S	Q/5      nU[        R                  " U/ S	Q/5      -  nXUS
.4$ )Nry   g      ?)r   r   )r   r   )r   ry   r   )r   ry   r   )r   r   r   r   )r   getRotationMatrix2Dr   r   nparrayvstack)r   r   r   r   r   r   rotation_matabs_cosabs_sinnew_wnew_hscale_xscale_y	scale_matr}   s                  r   _create_safe_rotate_matrix%SafeRotate._create_safe_rotate_matrix  s    $BQ..vcB l4()l4()F$u67F$u67 	Teai&)33Teai&)33 -. HHw1o7A	JK	 RYYi'@AA7333r   c                   US   SS nU R                   R                  " U R                  6 n[        R                  " U5      n[        R
                  " U5      nU R                  UUU5      u  pxU R                  UUU5      u  pUUUU	US.$ )r   r1   Nry   )r   r   r}   r   output_shape)r'   r   r^   r   r   r   r   )r   r"   r   r   r   image_centerr   r}   r   r   _s              r   r   'SafeRotate.get_params_dependent_on_data*  s     Wobq)&&

3 "((5 ,,[9 77

 88
 &'
 	
r   )r^   )r^   r   r`   r_   rc   rb   rm   rl   ra   r_   re   rd   rf   rd   r   rM   )r   rM   r   rv   r   ztuple[int, int]rP   z#tuple[np.ndarray, dict[str, float]]r   )rR   rS   rT   rU   rV   r   rW   r\   rp   r   r   r   r   r   r   r   rX   rY   rZ   s   @r   r   r     s    Vp H9% 9
 .7  ;H *+/07(8*(8
(8
(8" 9#(8$
%(82 (3(84 -5(86 7(8 (8T44 $4 %	4
 
-4>(
(
 (
 
	(
 (
r   r   ) rV   
__future__r   r   typingr   r   r   numpyr   typing_extensionsr   "albumentations.augmentations.cropsr   r{   1albumentations.augmentations.geometric.transformsr   albumentations.core.pydanticr	   (albumentations.core.transforms_interfacer
   r   $albumentations.core.type_definitionsr    r   __all__r   r   r\   r   r   rL   r   r   <module>r      sw    #   
  % C D ; = &
4K9] K9\0. 02x] xvO
 O
r   