
    h                    `   S r SSKJr  SSKJrJrJrJr  SSKJ	r	  SSK
r
SSKrSSKJr  SSKJrJrJrJr  SSKJr  SS	KJrJr  SS
KJrJrJr  SSKJrJr  SSK J!r!J"r"  SSK#J$r$  SSK%J&r'  / SQr( " S S\5      r) " S S\)5      r* " S S\)5      r+ " S S\)5      r, " S S\)5      r- " S S\)5      r.g)aN  Geometric distortion transforms for image augmentation.

This module provides various geometric distortion transformations that modify the spatial arrangement
of pixels in images while preserving their intensity values. These transforms can create
non-rigid deformations that are useful for data augmentation, especially when training models
that need to be robust to geometric variations.

Available transforms:
- ElasticTransform: Creates random elastic deformations by displacing pixels along random vectors
- GridDistortion: Distorts the image by moving the nodes of a grid placed on the image
- OpticalDistortion: Simulates lens distortion effects (barrel/pincushion) using camera or fisheye models
- PiecewiseAffine: Divides the image into a grid and applies random affine transformations to each cell
- ThinPlateSpline: Applies smooth deformations based on the thin plate spline interpolation technique

All transforms inherit from BaseDistortion, which provides a common interface and functionality
for applying distortion maps to various target types (images, masks, bounding boxes, keypoints).
These transforms are particularly useful for:

- Data augmentation to increase training set diversity
- Simulating real-world distortion effects like camera lens aberrations
- Creating more challenging test cases for computer vision models
- Medical image analysis where anatomy might appear in different shapes

Each transform supports customization through various parameters controlling the strength,
type, and characteristics of the distortion, as well as interpolation methods for different
target types.
    )annotations)	AnnotatedAnyLiteralcast)warnN)batch_transform)AfterValidatorFieldValidationInfofield_validator)check_range)denormalize_bboxesnormalize_bboxes)NonNegativeFloatRangeTypeSymmetricRangeTypecheck_range_bounds)BaseTransformInitSchemaDualTransform)ALL_TARGETSBIG_INTEGER)to_tuple   )
functional)ElasticTransformGridDistortionOpticalDistortionPiecewiseAffineThinPlateSplinec                  z  ^  \ rS rSrSr\r " S S\5      r\	R                  SS4             SU 4S jjjr          SS jr\" SS	S
S9SS j5       r\" SS
S	S9SS j5       r\" SS	S	S9SS j5       r\" SS	S
S9SS j5       r          SS jr          SS jr          SS jrSrU =r$ )BaseDistortionK   a  Base class for distortion-based transformations.

This class provides a foundation for implementing various types of image distortions,
such as optical distortions, grid distortions, and elastic transformations. It handles
the common operations of applying distortions to images, masks, bounding boxes, and keypoints.

Args:
    interpolation (int): Interpolation method to be used for image transformation.
        Should be one of the OpenCV interpolation types (e.g., cv2.INTER_LINEAR,
        cv2.INTER_CUBIC).
    mask_interpolation (int): 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.
    keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
        - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
          less accurate for large distortions. Recommended for large images or many keypoints.
        - "direct": Uses inverse mapping. More accurate for large distortions but slower.
        Default: "mask"
    p (float): Probability of applying the transform.

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

Image types:
    uint8, float32

Note:
    - This is an abstract base class and should not be used directly.
    - Subclasses should implement the `get_params_dependent_on_data` method to generate
      the distortion maps (map_x and map_y).
    - The distortion is applied consistently across all targets (image, mask, bboxes, keypoints)
      to maintain coherence in the augmented data.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> class CustomDistortion(A.BaseDistortion):
    ...     def __init__(self, distort_limit=0.3, *args, **kwargs):
    ...         super().__init__(*args, **kwargs)
    ...         self.distort_limit = distort_limit
    ...
    ...     def get_params_dependent_on_data(self, params, data):
    ...         height, width = params["shape"][:2]
    ...         # Create distortion maps - a simple radial distortion in this example
    ...         map_x = np.zeros((height, width), dtype=np.float32)
    ...         map_y = np.zeros((height, width), dtype=np.float32)
    ...
    ...         # Calculate distortion center
    ...         center_x = width / 2
    ...         center_y = height / 2
    ...
    ...         # Generate distortion maps
    ...         for y in range(height):
    ...             for x in range(width):
    ...                 # Distance from center
    ...                 dx = (x - center_x) / width
    ...                 dy = (y - center_y) / height
    ...                 r = np.sqrt(dx * dx + dy * dy)
    ...
    ...                 # Apply radial distortion
    ...                 factor = 1 + self.distort_limit * r
    ...                 map_x[y, x] = x + dx * factor
    ...                 map_y[y, x] = y + dy * factor
    ...
    ...         return {"map_x": map_x, "map_y": map_y}
    >>>
    >>> # 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 the custom distortion
    >>> transform = A.Compose([
    ...     CustomDistortion(
    ...         distort_limit=0.2,
    ...         interpolation=cv2.INTER_LINEAR,
    ...         mask_interpolation=cv2.INTER_NEAREST,
    ...         keypoint_remapping_method="mask",
    ...         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']
    >>> transformed_mask = transformed['mask']
    >>> transformed_bboxes = transformed['bboxes']
    >>> transformed_keypoints = transformed['keypoints']

c                  R    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	\S
'   S	\S'   Srg)BaseDistortion.InitSchema   aLiteral[cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]interpolationmask_interpolationLiteral['direct', 'mask']keypoint_remapping_methodoLiteral[cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101]border_modetuple[float, ...] | floatfill	fill_mask N__name__
__module____qualname____firstlineno____annotations____static_attributes__r0       k/var/www/fran/franai/venv/lib/python3.13/site-packages/albumentations/augmentations/geometric/distortion.py
InitSchemar$      s2    xx
 	
 $=<
 	
 (',,r8   r:   r   c                h   > [         TU ]  US9  Xl        X l        X0l        XPl        X`l        Xpl        g )N)p)super__init__r'   r(   r*   r,   r.   r/   )	selfr'   r(   r*   r<   r,   r.   r/   	__class__s	           r9   r>   BaseDistortion.__init__   s7    8 	1*"4)B&&	"r8   c                t    [         R                  " UUUU R                  U R                  U R                  5      $ )a2  Apply the distortion to the input image.

Args:
    img (np.ndarray): Input image to be distorted.
    map_x (np.ndarray): X-coordinate map of the distortion.
    map_y (np.ndarray): Y-coordinate map of the distortion.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Distorted image.

)
fgeometricremapr'   r,   r.   )r?   imgmap_xmap_yparamss        r9   applyBaseDistortion.apply   s9    & II
 	
r8   spatialTF)has_batch_dimhas_depth_dimc                (    U R                   " U40 UD6$ )zApply the distortion to a batch of images.

Args:
    images (np.ndarray): Batch of images to be distorted.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Batch of distorted images.

rI   )r?   imagesrH   s      r9   apply_to_imagesBaseDistortion.apply_to_images       zz&+F++r8   c                (    U R                   " U40 UD6$ )zApply the distortion to a volume.

Args:
    volume (np.ndarray): Volume to be distorted.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Distorted volume.

rO   )r?   volumerH   s      r9   apply_to_volumeBaseDistortion.apply_to_volume  rS   r8   c                (    U R                   " U40 UD6$ )zApply the distortion to a batch of volumes.

Args:
    volumes (np.ndarray): Batch of volumes to be distorted.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Batch of distorted volumes.

rO   )r?   volumesrH   s      r9   apply_to_volumesBaseDistortion.apply_to_volumes'  s     zz',V,,r8   c                (    U R                   " U40 UD6$ )zApply the distortion to a 3D mask.

Args:
    mask3d (np.ndarray): 3D mask to be distorted.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Distorted 3D mask.

)apply_to_mask)r?   mask3drH   s      r9   apply_to_mask3dBaseDistortion.apply_to_mask3d5  s     !!&3F33r8   c                t    [         R                  " UUUU R                  U R                  U R                  5      $ )a"  Apply the distortion to a mask.

Args:
    mask (np.ndarray): Mask to be distorted.
    map_x (np.ndarray): X-coordinate map of the distortion.
    map_y (np.ndarray): Y-coordinate map of the distortion.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Distorted mask.

)rC   rD   r(   r,   r/   )r?   maskrF   rG   rH   s        r9   r]   BaseDistortion.apply_to_maskC  s9    & ##NN
 	
r8   c                p    US   SS n[        X5      n[        R                  " UUUU5      n[        Xu5      $ )a@  Apply the distortion to bounding boxes.

Args:
    bboxes (np.ndarray): Bounding boxes to be distorted.
    map_x (np.ndarray): X-coordinate map of the distortion.
    map_y (np.ndarray): Y-coordinate map of the distortion.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Distorted bounding boxes.

shapeN   )r   rC   remap_bboxesr   )r?   bboxesrF   rG   rH   image_shapebboxes_denormbboxes_returneds           r9   apply_to_bboxesBaseDistortion.apply_to_bboxes_  sG    & Wobq)*6?$11	
  ==r8   c                    U R                   S:X  a  [        R                  " XX4S   5      $ [        R                  " XX4S   5      $ )a4  Apply the distortion to keypoints.

Args:
    keypoints (np.ndarray): Keypoints to be distorted.
    map_x (np.ndarray): X-coordinate map of the distortion.
    map_y (np.ndarray): Y-coordinate map of the distortion.
    **params (Any): Additional parameters.

Returns:
    np.ndarray: Distorted keypoints.

directre   )r*   rC   remap_keypointsremap_keypoints_via_mask)r?   	keypointsrF   rG   rH   s        r9   apply_to_keypoints!BaseDistortion.apply_to_keypoints|  sA    & ))X5--igWW229USZO\\r8   )r,   r.   r/   r'   r*   r(   )r'   r&   r(   r&   r*   r)   r<   floatr,   r+   r.   r-   r/   r-   )
rE   
np.ndarrayrF   rv   rG   rv   rH   r   returnrv   )rP   rv   rH   r   rw   rv   )rU   rv   rH   r   rw   rv   )rY   rv   rH   r   rw   rv   )r^   rv   rH   r   rw   rv   )
rb   rv   rF   rv   rG   rv   rH   r   rw   rv   )
rh   rv   rF   rv   rG   rv   rH   r   rw   rv   )
rr   rv   rF   rv   rG   rv   rH   r   rw   rv   )r2   r3   r4   r5   __doc__r   _targetsr   r:   cv2BORDER_CONSTANTr>   rI   r	   rQ   rV   rZ   r_   r]   rl   rs   r7   __classcell__r@   s   @r9   r!   r!   K   s   gR H-, -X *+/05"#
"#
"#  $=!"#" #"#$
%"#2 (3"#4 -5"# "#H

 
 	

 
 

8 Yd%H, I, Ye4H, I, Yd$G- H- Yd%H4 I4

 
 	

 
 

8>> > 	>
 > 
>:]] ] 	]
 ] 
] ]r8   r!   c                     ^  \ rS rSrSr " S S\R                  5      rSS\R                  SS\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  aX  Apply elastic deformation to images, masks, bounding boxes, and keypoints.

This transformation introduces random elastic distortions to the input data. It's particularly
useful for data augmentation in training deep learning models, especially for tasks like
image segmentation or object detection where you want to maintain the relative positions of
features while introducing realistic deformations.

The transform works by generating random displacement fields and applying them to the input.
These fields are smoothed using a Gaussian filter to create more natural-looking distortions.

Args:
    alpha (float): Scaling factor for the random displacement fields. Higher values result in
        more pronounced distortions. Default: 1.0
    sigma (float): Standard deviation of the Gaussian filter used to smooth the displacement
        fields. Higher values result in smoother, more global distortions. Default: 50.0
    interpolation (int): Interpolation method to be used for image transformation. Should be one
        of the OpenCV interpolation types. Default: cv2.INTER_LINEAR
    approximate (bool): Whether to use an approximate version of the elastic transform. If True,
        uses a fixed kernel size for Gaussian smoothing, which can be faster but potentially
        less accurate for large sigma values. Default: False
    same_dxdy (bool): Whether to use the same random displacement field for both x and y
        directions. Can speed up the transform at the cost of less diverse distortions. Default: False
    mask_interpolation (int): 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.
    noise_distribution (Literal["gaussian", "uniform"]): Distribution used to generate the displacement fields.
        "gaussian" generates fields using normal distribution (more natural deformations).
        "uniform" generates fields using uniform distribution (more mechanical deformations).
        Default: "gaussian".
    keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
        - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
          less accurate for large distortions. Recommended for large images or many keypoints.
        - "direct": Uses inverse mapping. More accurate for large distortions but slower.
        Default: "mask"

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

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

Image types:
    uint8, float32

Note:
    - The transform will maintain consistency across all targets (image, mask, bboxes, keypoints)
      by using the same displacement fields for all.
    - The 'approximate' parameter determines whether to use a precise or approximate method for
      generating displacement fields. The approximate method can be faster but may be less
      accurate for large sigma values.
    - Bounding boxes that end up outside the image after transformation will be removed.
    - Keypoints that end up outside the image after transformation will be removed.

Examples:
    >>> import albumentations as A
    >>> transform = A.Compose([
    ...     A.ElasticTransform(alpha=1, sigma=50, p=0.5),
    ... ])
    >>> transformed = transform(image=image, mask=mask, bboxes=bboxes, keypoints=keypoints)
    >>> transformed_image = transformed['image']
    >>> transformed_mask = transformed['mask']
    >>> transformed_bboxes = transformed['bboxes']
    >>> transformed_keypoints = transformed['keypoints']

c                  R    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	\S
'   S\S'   Srg)ElasticTransform.InitSchemai  zAnnotated[float, Field(ge=0)]alphazAnnotated[float, Field(ge=1)]sigmaboolapproximate	same_dxdyLiteral['gaussian', 'uniform']noise_distributionr)   r*   r0   Nr1   r0   r8   r9   r:   r     s%    ,,,,::#<<r8   r:   r   2   Fgaussianrb   r         ?c           
     h   > [         TU ]  UUUUU	U
US9  Xl        X l        X@l        XPl        Xpl        g N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@   s                r9   r>   ElasticTransform.__init__  sJ    B 	'1&?# 	 	
 

&""4r8   c           
     B   US   SS u  p4U R                   (       a  SOSn[        R                  " X44U R                  U R                  U R
                  UU R                  U R                  S9u  pg[        R                  " [        R                  " [        R                  " U5      [        R                  " U5      5      5      nU[        R                  " Xg/5      -   n	U	S   R                  [        R                  5      U	S   R                  [        R                  5      S	.$ )
a=  Generate displacement fields for the elastic transform.

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

Returns:
    dict[str, Any]: Dictionary containing displacement fields for the elastic transform.

re   Nrf   )   r   )r   r   )r   kernel_sizerandom_generatorr   r   r   rF   rG   )r   rC   generate_displacement_fieldsr   r   r   r   r   npstackmeshgridarangeastypefloat32)
r?   rH   dataheightwidthr   dxdycoordsmapss
             r9   get_params_dependent_on_data-ElasticTransform.get_params_dependent_on_data  s     w+"&"2"2h 88OJJJJnn#!22#66
 "++bii&6		&8IJK"**!W^^BJJ/!W^^BJJ/
 	
r8   )r   r   r   r   r   )r   ru   r   ru   r'   r&   r   r   r   r   r(   r&   r   r   r*   r)   r,   r+   r.   r-   r/   r-   r<   ru   rH   dict[str, Any]r   r   rw   r   r2   r3   r4   r5   rx   r!   r:   rz   INTER_LINEARINTER_NEARESTr{   r>   r   r7   r|   r}   s   @r9   r   r     s    ?B=^.. =  ! =G?E *+/0?.5.5 .5
	.5 .5 .5
.5( ;).5* $=+.5,
-.5: (;.5< -=.5> ?.5 .5`#
#
 #
 
	#
 #
r8   r   c                     ^  \ rS rSrSr " S S\R                  5      rSSS\R                  \R                  SSS	\R                  S
S
4                     SU 4S jjjr      SS jrSrU =r$ )r   i4  a  Apply piecewise affine transformations to the input image.

This augmentation places a regular grid of points on an image and randomly moves the neighborhood of these points
around via affine transformations. This leads to local distortions in the image.

Args:
    scale (tuple[float, float] | float): Standard deviation of the normal distributions. These are used to sample
        the random distances of the subimage's corners from the full image's corners.
        If scale is a single float value, the range will be (0, scale).
        Recommended values are in the range (0.01, 0.05) for small distortions,
        and (0.05, 0.1) for larger distortions. Default: (0.03, 0.05).
    nb_rows (tuple[int, int] | int): Number of rows of points that the regular grid should have.
        Must be at least 2. For large images, you might want to pick a higher value than 4.
        If a single int, then that value will always be used as the number of rows.
        If a tuple (a, b), then a value from the discrete interval [a..b] will be uniformly sampled per image.
        Default: 4.
    nb_cols (tuple[int, int] | int): Number of columns of points that the regular grid should have.
        Must be at least 2. For large images, you might want to pick a higher value than 4.
        If a single int, then that value will always be used as the number of columns.
        If a tuple (a, b), then a value from the discrete interval [a..b] will be uniformly sampled per image.
        Default: 4.
    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.
    absolute_scale (bool): If set to True, the value of the scale parameter will be treated as an absolute
        pixel value. If set to False, it will be treated as a fraction of the image height and width.
        Default: False.
    keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
        - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
          less accurate for large distortions. Recommended for large images or many keypoints.
        - "direct": Uses inverse mapping. More accurate for large distortions but slower.
        Default: "mask"
    p (float): Probability of applying the transform. Default: 0.5.

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

Image types:
    uint8, float32

Note:
    - This augmentation is very slow. Consider using `ElasticTransform` instead, which is at least 10x faster.
    - The augmentation may not always produce visible effects, especially with small scale values.
    - For keypoints and bounding boxes, the transformation might move them outside the image boundaries.
      In such cases, the keypoints will be set to (-1, -1) and the bounding boxes will be removed.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
    >>> transform = A.Compose([
    ...     A.PiecewiseAffine(scale=(0.03, 0.05), nb_rows=4, nb_cols=4, p=0.5),
    ... ])
    >>> transformed = transform(image=image)
    >>> transformed_image = transformed["image"]

c                  v    \ rS rSr% S\S'   S\S'   S\S'   S\S'   \" SS5      \      SS	 j5       5       rS
rg)PiecewiseAffine.InitSchemair  r   scaletuple[int, int] | intnb_rowsnb_colsr   absolute_scalec                \    S[         4n[        X5      n[        U/UQUR                  P76   U$ )Nrf   )r   r   r   
field_name)clsvalueinfoboundsresults        r9   _process_range)PiecewiseAffine.InitSchema._process_rangex  s2     ^Fe+F999Mr8   r0   N)r   r   r   r   rw   tuple[int, int])	r2   r3   r4   r5   r6   r   classmethodr   r7   r0   r8   r9   r:   r   r  sW    ((&&&&	I	.		(	 !	 		 
 
/	r8   r:   )gQ?皙?)   r   Frb   r   r   c           
        > [         TU ]  UUUUU	U
US9  [        SSS9  [        SU5      U l        [        SU5      U l        [        SU5      U l        X`l        g )N)r<   r'   r(   r*   r,   r.   r/   zcThis augmenter is very slow. Try to use ``ElasticTransform`` instead, which is at least 10x faster.rf   )
stackleveltuple[float, float]r   )r=   r>   r   r   r   r   r   r   )r?   r   r   r   r'   r(   r   r*   r<   r,   r.   r/   r@   s               r9   r>   PiecewiseAffine.__init__  sr    @ 	'1&?# 	 	
 	q	

 /7
-w7-w7,r8   c                   US   SS n[         R                  " U R                  R                  " U R                  6 SS5      n[         R                  " U R                  R                  " U R
                  6 SS5      nU R                  R                  " U R                  6 n[        R                  " UXE4UU R                  U R                  S9u  pxXxS.$ )Get the parameters dependent on the data.

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

Returns:
    dict[str, Any]: Parameters.

re   Nrf   )ri   gridr   r   r   r   )r   clip	py_randomrandintr   r   uniformr   rC   create_piecewise_affine_mapsr   r   )	r?   rH   r   ri   r   r   r   rF   rG   s	            r9   r   ,PiecewiseAffine.get_params_dependent_on_data  s     Wobq)''$..00$,,?DI''$..00$,,?DI&&

3!>>##..!22
 //r8   )r   r   r   r   )r   tuple[float, float] | floatr   r   r   r   r'   r&   r(   r&   r   r   r*   r)   r<   ru   r,   r+   r.   r-   r/   r-   r   r   r}   s   @r9   r   r   4  s    ;z^.. ( .:)/)/  $?E *+/0=2-*2- '2- '	2-

2-
2-& '2-( $=)2-* +2-,
-2-: (;2-< -=2- 2-h00 0 
	0 0r8   r   c            	         ^  \ rS rSrSr " S S\R                  5      rS\R                  \R                  SSS\R                  S	S	4	                 SU 4S
 jjjr      SS jrSrU =r$ )r   i  u 
  Apply optical distortion to images, masks, bounding boxes, and keypoints.

Supports two distortion models:
1. Camera matrix model (original):
   Uses OpenCV's camera calibration model with k1=k2=k distortion coefficients

2. Fisheye model:
   Direct radial distortion: r_dist = r * (1 + gamma * r²)

Args:
    distort_limit (float | tuple[float, float]): Range of distortion coefficient.
        For camera model: recommended range (-0.05, 0.05)
        For fisheye model: recommended range (-0.3, 0.3)
        Default: (-0.05, 0.05)

    mode (Literal['camera', 'fisheye']): Distortion model to use:
        - 'camera': Original camera matrix model
        - 'fisheye': Fisheye lens model
        Default: 'camera'

    interpolation (OpenCV flag): Interpolation method used for image transformation.
        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.

    keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
        - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
          less accurate for large distortions. Recommended for large images or many keypoints.
        - "direct": Uses inverse mapping. More accurate for large distortions but slower.
        Default: "mask"

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

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

Image types:
    uint8, float32

Note:
    - The distortion is applied using OpenCV's initUndistortRectifyMap and remap functions.
    - The distortion coefficient (k) is randomly sampled from the distort_limit range.
    - Bounding boxes and keypoints are transformed along with the image to maintain consistency.
    - Fisheye model directly applies radial distortion

Examples:
    >>> import albumentations as A
    >>> transform = A.Compose([
    ...     A.OpticalDistortion(distort_limit=0.1, p=1.0),
    ... ])
    >>> transformed = transform(image=image, mask=mask, bboxes=bboxes, keypoints=keypoints)
    >>> transformed_image = transformed['image']
    >>> transformed_mask = transformed['mask']
    >>> transformed_bboxes = transformed['bboxes']
    >>> transformed_keypoints = transformed['keypoints']

c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg	)
OpticalDistortion.InitSchemai  r   distort_limitLiteral['camera', 'fisheye']moder)   r*   r0   Nr1   r0   r8   r9   r:   r     s    ))**#<<r8   r:   )gr   camerarb   r   r   c
           
     Z   > [         T
U ]  UUUUUUU	S9  [        SU5      U l        X@l        g Nr   r   )r=   r>   r   r   r   )r?   r   r'   r(   r   r*   r<   r,   r.   r/   r@   s             r9   r>   OpticalDistortion.__init__  sC    < 	'1&?# 	 	
 ""7G	r8   c                    US   SS nU R                   R                  " U R                  6 nU R                  S:X  a  [        R
                  " UU5      u  pVO[        R                  " UU5      u  pVXVS.$ )r   re   Nrf   r   r   )r   r   r   r   rC   !get_camera_matrix_distortion_mapsget_fisheye_distortion_maps)r?   rH   r   ri   krF   rG   s          r9   r   .OpticalDistortion.get_params_dependent_on_dataE  s}     Wobq) NN""D$6$67 99 %GGLE5
 &AALE
 //r8   )r   r   )r   r   r'   r&   r(   r&   r   r   r*   r)   r<   ru   r,   r+   r.   r-   r/   r-   r   r   r}   s   @r9   r   r     s    ;z=^.. = 6C  -5?E *+/09(2(
(
(" +#($ $=%(& '((
)(6 (7(8 -9( (T 0 0  0 
	 0  0r8   r   c            
         ^  \ rS rSrSr " S S\R                  5      rSS\R                  S\R                  SS	\R                  S
S
4
                   SU 4S jjjr      SS jrSrU =r$ )r   ih  a
  Apply grid distortion to images, masks, bounding boxes, and keypoints.

This transformation divides the image into a grid and randomly distorts each cell,
creating localized warping effects. It's particularly useful for data augmentation
in tasks like medical image analysis, OCR, and other domains where local geometric
variations are meaningful.

Args:
    num_steps (int): Number of grid cells on each side of the image. Higher values
        create more granular distortions. Must be at least 1. Default: 5.
    distort_limit (float or tuple[float, float]): Range of distortion. If a single float
        is provided, the range will be (-distort_limit, distort_limit). Higher values
        create stronger distortions. Should be in the range of -1 to 1.
        Default: (-0.3, 0.3).
    interpolation (int): OpenCV interpolation method used for image transformation.
        Options include cv2.INTER_LINEAR, cv2.INTER_CUBIC, etc. Default: cv2.INTER_LINEAR.
    normalized (bool): If True, ensures that the distortion does not move pixels
        outside the image boundaries. This can result in less extreme distortions
        but guarantees that no information is lost. Default: True.
    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.
    keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
        - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
          less accurate for large distortions. Recommended for large images or many keypoints.
        - "direct": Uses inverse mapping. More accurate for large distortions but slower.
        Default: "mask"
    p (float): Probability of applying the transform. Default: 0.5.

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

Image types:
    uint8, float32

Note:
    - The same distortion is applied to all targets (image, mask, bboxes, keypoints)
      to maintain consistency.
    - When normalized=True, the distortion is adjusted to ensure all pixels remain
      within the image boundaries.

Examples:
    >>> import albumentations as A
    >>> transform = A.Compose([
    ...     A.GridDistortion(num_steps=5, distort_limit=0.3, p=1.0),
    ... ])
    >>> transformed = transform(image=image, mask=mask, bboxes=bboxes, keypoints=keypoints)
    >>> transformed_image = transformed['image']
    >>> transformed_mask = transformed['mask']
    >>> transformed_bboxes = transformed['bboxes']
    >>> transformed_keypoints = transformed['keypoints']

c                  t    \ rS rSr% S\S'   S\S'   S\S'   S\S	'   \" S5      \      SS
 j5       5       rSrg)GridDistortion.InitSchemai  zAnnotated[int, Field(ge=1)]	num_stepsr   r   r   
normalizedr)   r*   c                P    Sn[        U5      n[        U/UQUR                  P76   U$ )N)r   )r   r   r   )r   vr   r   r   s        r9   _check_limits'GridDistortion.InitSchema._check_limits  s-     Fa[F999Mr8   r0   N)r   r   r   r   rw   r   )	r2   r3   r4   r5   r6   r   r   r   r7   r0   r8   r9   r:   r     sU    ..))#<<		)		"	 !	 !		 
 
*	r8   r:      )g333333ӿg333333?Trb   r   r   c           
     f   > [         TU ]  UUUUUU	U
S9  Xl        [        SU5      U l        X@l        g r   )r=   r>   r   r   r   r   )r?   r   r   r'   r   r(   r*   r<   r,   r.   r/   r@   s              r9   r>   GridDistortion.__init__  sH    > 	'1&?# 	 	
 #!"7G$r8   c                "   US   SS n[        U R                  S-   5       Vs/ s H)  nSU R                  R                  " U R                  6 -   PM+     nn[        U R                  S-   5       Vs/ s H)  nSU R                  R                  " U R                  6 -   PM+     nnU R
                  (       a,  [        R                  " UU R                  UU5      nUS   US   pe[        R                  " UUUU R                  5      u  pXS.$ s  snf s  snf )r   re   Nrf   r   steps_xsteps_yr   )	ranger   r   r   r   r   rC   normalize_grid_distortion_stepsgenerate_grid)
r?   rH   r   ri   _r   r   normalized_paramsrF   rG   s
             r9   r   +GridDistortion.get_params_dependent_on_data  s    Wobq)LQRVR`R`cdRdLefLeq1t~~--t/A/ABBLefLQRVR`R`cdRdLefLeq1t~~--t/A/ABBLef?? * J J	! "),!), 
 "//NN	
 //- gfs   0D/0D)r   r   r   )r   intr   r   r'   r&   r   r   r(   r&   r*   r)   r<   ru   r,   r+   r.   r-   r/   r-   r   r   r}   s   @r9   r   r   h  s    4l^.. ( 5@  ?E *+/0;*%*% 3*%
	*% *%
*%& $='*%( )*%*
+*%8 (9*%: -;*% *%X&0&0 &0 
	&0 &0r8   r   c            	         ^  \ rS rSrSr " S S\R                  5      rSS\R                  \R                  SS\R                  S	S	4	                 SU 4S
 jjjr      SS jrSrU =r$ )r   i  az  Apply Thin Plate Spline (TPS) transformation to create smooth, non-rigid deformations.

Imagine the image printed on a thin metal plate that can be bent and warped smoothly:
- Control points act like pins pushing or pulling the plate
- The plate resists sharp bending, creating smooth deformations
- The transformation maintains continuity (no tears or folds)
- Areas between control points are interpolated naturally

The transform works by:
1. Creating a regular grid of control points (like pins in the plate)
2. Randomly displacing these points (like pushing/pulling the pins)
3. Computing a smooth interpolation (like the plate bending)
4. Applying the resulting deformation to the image


Args:
    scale_range (tuple[float, float]): Range for random displacement of control points.
        Values should be in [0.0, 1.0]:
        - 0.0: No displacement (identity transform)
        - 0.1: Subtle warping
        - 0.2-0.4: Moderate deformation (recommended range)
        - 0.5+: Strong warping
        Default: (0.2, 0.4)

    num_control_points (int): Number of control points per side.
        Creates a grid of num_control_points x num_control_points points.
        - 2: Minimal deformation (affine-like)
        - 3-4: Moderate flexibility (recommended)
        - 5+: More local deformation control
        Must be >= 2. Default: 4

    interpolation (int): OpenCV interpolation flag. Used for image sampling.
        See also: cv2.INTER_*
        Default: cv2.INTER_LINEAR

    mask_interpolation (int): OpenCV interpolation flag. Used for mask sampling.
        See also: cv2.INTER_*
        Default: cv2.INTER_NEAREST

    keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
        - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
          less accurate for large distortions. Recommended for large images or many keypoints.
        - "direct": Uses inverse mapping. More accurate for large distortions but slower.
        Default: "mask"

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

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

Image types:
    uint8, float32

Note:
    - The transformation preserves smoothness and continuity
    - Stronger scale values may create more extreme deformations
    - Higher number of control points allows more local deformations
    - The same deformation is applied consistently to all targets

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> import cv2
    >>>
    >>> # Create sample data
    >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
    >>> mask = np.zeros((100, 100), dtype=np.uint8)
    >>> mask[25:75, 25:75] = 1  # Square mask
    >>> bboxes = np.array([[10, 10, 40, 40]])  # Single box
    >>> bbox_labels = [1]
    >>> keypoints = np.array([[50, 50]])  # Single keypoint at center
    >>> keypoint_labels = [0]
    >>>
    >>> # Set up transform with Compose to handle all targets
    >>> transform = A.Compose([
    ...     A.ThinPlateSpline(scale_range=(0.2, 0.4), 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 to all targets
    >>> result = transform(
    ...     image=image,
    ...     mask=mask,
    ...     bboxes=bboxes,
    ...     bbox_labels=bbox_labels,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Access transformed results
    >>> transformed_image = result['image']
    >>> transformed_mask = result['mask']
    >>> transformed_bboxes = result['bboxes']
    >>> transformed_bbox_labels = result['bbox_labels']
    >>> transformed_keypoints = result['keypoints']
    >>> transformed_keypoint_labels = result['keypoint_labels']

References:
    - "Principal Warps: Thin-Plate Splines and the Decomposition of Deformations"
      by F.L. Bookstein
      https://doi.org/10.1109/34.24792

    - Thin Plate Splines in Computer Vision:
      https://en.wikipedia.org/wiki/Thin_plate_spline

    - Similar implementation in Kornia:
      https://kornia.readthedocs.io/en/latest/augmentation.html#kornia.augmentation.RandomThinPlateSpline

See Also:
    - ElasticTransform: For different type of non-rigid deformation
    - GridDistortion: For grid-based warping
    - OpticalDistortion: For lens-like distortions

c                  @    \ rS rSr% S\S'   \" SS9rS\S'   S\S	'   S
rg)ThinPlateSpline.InitSchemaiz  zHAnnotated[tuple[float, float], AfterValidator(check_range_bounds(0, 1))]scale_rangerf   )ger   num_control_pointsr)   r*   r0   N)r2   r3   r4   r5   r6   r   r   r7   r0   r8   r9   r:   r   z  s    ]]"'1+C-#<<r8   r:   )g?g?r   rb   r   r   c
           
     D   > [         T
U ]  UUUUUUU	S9  Xl        X l        g r   )r=   r>   r   r   )r?   r   r   r'   r(   r*   r<   r,   r.   r/   r@   s             r9   r>   ThinPlateSpline.__init__  s:    < 	'1&?# 	 	
 '"4r8   c                b   US   SS u  p4[         R                  " U R                  5      nU R                  R                  " U R
                  6 S-  nXPR                  R                  SUUR                  5      -   n[         R                  " XW5      u  p[        R                  " [        R                  " U5      [        R                  " U5      5      u  p[        R                  " U
R                  5       UR                  5       /SS9R                  [        R                   5      n[         R"                  " XU/-  UUU	5      nXU/-  nUSS2S4   R%                  X45      R                  [        R                   5      USS2S4   R%                  X45      R                  [        R                   5      S.$ )	r   re   Nrf   
   r   r   )axisr   )rC   generate_control_pointsr   r   r   r   r   normalre   compute_tps_weightsr   r   r   r   flattenr   r   tps_transformreshape)r?   rH   r   r   r   
src_pointsr   
dst_pointsweightsaffinexypointstransformeds                 r9   r   ,ThinPlateSpline.get_params_dependent_on_data  sl    w+778O8OP
 &&(8(89B>"7"7">">#
 

 %88P {{299U+RYYv->?199;		41=DDRZZP !..V_$	
 	v& !A&..v=DDRZZP A&..v=DDRZZP
 	
r8   )r   r   )r   r   r   r   r'   r&   r(   r&   r*   r)   r<   ru   r,   r+   r.   r-   r/   r-   r   r   r}   s   @r9   r   r     s    qf=^.. = ,6"#  ?E *+/09(5((5  (5
	(5
(5$ $=%(5& '(5(
)(56 (7(58 -9(5 (5T-
-
 -
 
	-
 -
r8   r   )/rx   
__future__r   typingr   r   r   r   warningsr   rz   numpyr   albucorer	   pydanticr
   r   r   r   "albumentations.augmentations.utilsr   albumentations.core.bbox_utilsr   r   albumentations.core.pydanticr   r   r   (albumentations.core.transforms_interfacer   r   $albumentations.core.type_definitionsr   r   albumentations.core.utilsr    r   rC   __all__r!   r   r   r   r   r   r0   r8   r9   <module>r     s   8 # 0 0  
  $  ; 
 / &F]] F]R
]
~ ]
@a0n a0HM0 M0`[0^ [0|P
n P
r8   