U
    h                     @  s  d dl mZ d dlZd dlZd dlmZmZmZmZ d dl	Z	d dl
Zd dlmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZmZmZmZ d d
lm Z m!Z! d dl"m#Z#m$Z$ d dl%m&Z& ddl'mZ( ddddddddgZ)dZ*dZ+d)dddddddZ,G dd  d e Z-G d!d de!Z.G d"d de.Z/G d#d de.Z0G d$d de!Z1G d%d de!Z2G d&d de!Z3G d'd de!Z4G d(d de!Z5dS )*    )annotationsN)AnyLiteralTuplecast)FieldValidationInfofield_validatormodel_validator)Self)random_utils)
functional)check_range)NonNegativeFloatRangeTypeOnePlusFloatRangeTypeOnePlusIntRangeTypeSymmetricRangeType)BaseTransformInitSchemaImageOnlyTransform)ScaleFloatTypeScaleIntType)to_tuple   Blur
MotionBlurGaussianBlur	GlassBlurAdvancedBlur
MedianBlurDefocusZoomBlur      ?   r   r   floattuple[int, int])valueinfo	min_valuereturnc                 C  sZ   dt df}t| |}t|f||jf  |D ]&}|dkr.|d dkr.td| q.|S )Nr   infr"   r   "Blur limit must be 0 or odd. Got: )r#   r   r   
field_name
ValueError)r%   r&   r'   Zboundsresultv r/   P/tmp/pip-unpacked-wheel-e8onvpoz/albumentations/augmentations/blur/transforms.pyprocess_blur_limit"   s    
r1   c                   @  s4   e Zd ZU ded< ededdddddZdS )	BlurInitSchemar   
blur_limitr   r$   r%   r&   r(   c                 C  s   t ||ddS )N   r'   r1   clsr%   r&   r/   r/   r0   process_blur0   s    zBlurInitSchema.process_blurN)__name__
__module____qualname____annotations__r	   classmethodr:   r/   r/   r/   r0   r2   -   s   
r2   c                      sl   e Zd ZdZG dd deZdddd	d
 fddZdddddddZddddZddddZ	  Z
S )r   ak  Apply uniform box blur to the input image using a randomly sized square kernel.

    This transform uses OpenCV's cv2.blur function, which performs a simple box filter blur.
    The size of the blur kernel is randomly selected for each application, allowing for
    varying degrees of blur intensity.

    Args:
        blur_limit (tuple[int, int] | int): Controls the range of the blur kernel size.
            - If a single int is provided, the kernel size will be randomly chosen
              between 3 and that value.
            - If a tuple of two ints is provided, it defines the inclusive range
              of possible kernel sizes.
            The kernel size must be odd and greater than or equal to 3.
            Larger kernel sizes produce stronger blur effects.
            Default: (3, 7)

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

    Notes:
        - The blur kernel is always square (same width and height).
        - Only odd kernel sizes are used to ensure the blur has a clear center pixel.
        - Box blur is faster than Gaussian blur but may produce less natural results.
        - This blur method averages all pixels under the kernel area, which can
          reduce noise but also reduce image detail.

    Targets:
        image

    Image types:
        uint8, float32

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.Blur(blur_limit=(3, 7), p=1.0)
        >>> result = transform(image=image)
        >>> blurred_image = result["image"]
    c                   @  s   e Zd ZdS )zBlur.InitSchemaN)r;   r<   r=   r/   r/   r/   r0   
InitSchema_   s   r@   r5      r!   Nr   r#   bool | Noner3   palways_applyc                   s(   t  j||d ttttf || _d S NrE   rF   )super__init__r   r   intr3   selfr3   rE   rF   	__class__r/   r0   rJ   b   s    zBlur.__init__
np.ndarrayrK   r   imgkernelparamsr(   c                 K  s   t ||S N)fblurZblurrM   rR   rS   rT   r/   r/   r0   applyf   s    z
Blur.applydict[str, Any]r(   c                 C  s*   dt tt| jd | jd d diS )NrS   r   r   r"   )r   choicelistranger3   rM   r/   r/   r0   
get_paramsi   s    zBlur.get_paramstuple[str, ...]c                 C  s   dS )N)r3   r/   r^   r/   r/   r0   get_transform_init_args_namesl   s    z"Blur.get_transform_init_args_names)rA   r!   Nr;   r<   r=   __doc__r2   r@   rJ   rX   r_   ra   __classcell__r/   r/   rN   r0   r   6   s   (c                      sr   e Zd ZdZG dd deZddd	d
dd fddZdd fddZdddddddZddddZ	  Z
S )r   a	  Apply motion blur to the input image using a random-sized kernel.

    This transform simulates the effect of camera or object motion during image capture,
    creating a directional blur. It uses a line-shaped kernel with random orientation
    to achieve this effect.

    Args:
        blur_limit (int | tuple[int, int]): Maximum kernel size for blurring the input image.
            Should be in range [3, inf).
            - If a single int is provided, the kernel size will be randomly chosen
              between 3 and that value.
            - If a tuple of two ints is provided, it defines the inclusive range
              of possible kernel sizes.
            Default: (3, 7)

        allow_shifted (bool): If set to True, allows the motion blur kernel to be
            randomly shifted from the center. If False, the kernel will always be
            centered. Default: True

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The blur kernel is always a straight line, simulating linear motion.
        - The angle of the motion blur is randomly chosen for each application.
        - Larger kernel sizes result in more pronounced motion blur effects.
        - When `allow_shifted` is True, the blur effect can appear more natural and varied,
          as it simulates motion that isn't perfectly centered in the frame.
        - This transform is particularly useful for:
          * Simulating camera shake or motion blur in action scenes
          * Data augmentation for object detection or tracking tasks
          * Creating more challenging inputs for image stabilization algorithms

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.MotionBlur(blur_limit=7, allow_shifted=True, p=0.5)
        >>> result = transform(image=image)
        >>> motion_blurred_image = result["image"]

    References:
        - Motion blur: https://en.wikipedia.org/wiki/Motion_blur
        - OpenCV filter2D (used internally):
          https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04
    c                   @  s6   e Zd ZU ded< ded< eddddd	d
ZdS )zMotionBlur.InitSchemaboolallow_shiftedr   r3   aftermoder   rZ   c                 C  sH   t | jd| _| jrDt| jtrDtdd | jD rDtd| j | S )Nr5   c                 s  s   | ]}|d  dkV  qdS )r"   r   Nr/   ).0xr/   r/   r0   	<genexpr>   s     z5MotionBlur.InitSchema.process_blur.<locals>.<genexpr>z0Blur limit must be odd when centered=True. Got: )r   r3   rf   
isinstancetupleanyr,   r^   r/   r/   r0   r:      s    &z"MotionBlur.InitSchema.process_blurN)r;   r<   r=   r>   r
   r:   r/   r/   r/   r0   r@      s   
r@   rB   TNr!   r   re   rC   r#   )r3   rf   rF   rE   c                   s0   t  j|||d || _ttttf || _d S NrD   )rI   rJ   rf   r   r   rK   r3   )rM   r3   rf   rF   rE   rN   r/   r0   rJ      s    zMotionBlur.__init__r`   rZ   c                   s   t   dS )Nrf   )rf   )rI   ra   r^   rN   r/   r0   ra      s    z(MotionBlur.get_transform_init_args_namesrP   r   rQ   c                 K  s   t j||dS N)rS   fmainZconvolverW   r/   r/   r0   rX      s    zMotionBlur.applyrY   c                   s  t tt| jd | jd d d}|tkr<td| tj||ftj	d}t 
d|d t 
d|d  }}||krt t|d\}}n"t 
d|d t 
d|d  }}ddddd	d
}| jsP|||\}}|||\}}|| d }|| d }	|d d }
||
  |	|
  fdd||fD \}}fdd||fD \}}tj|||f||fddd d|tjt| iS )Nr   r   r"   zksize must be > 2. Got: )ZdtyperK   r$   )v1v2r(   c                 S  s>   t | | d }|d dkr6|| kr.|d8 }n| d8 } | |fS )Nr   r"   )abs)rt   ru   Zlen_vr/   r/   r0   make_odd_val   s    
z+MotionBlur.get_params.<locals>.make_odd_valr!   c                 3  s   | ]}t |  V  qd S rU   rK   rj   i)dxr/   r0   rl      s     z(MotionBlur.get_params.<locals>.<genexpr>c                 3  s   | ]}t |  V  qd S rU   rx   ry   )dyr/   r0   rl      s     )Z	thicknessrS   )randomr[   r\   r]   r3   TWOr,   npzerosZuint8randintsamplerf   cv2lineastypefloat32sum)rM   ksizerS   x1Zx2y1y2rw   ZxcZyccenterr/   )r{   r|   r0   r_      s*    &""	zMotionBlur.get_params)rB   TNr!   )r;   r<   r=   rc   r   r@   rJ   ra   rX   r_   rd   r/   r/   rN   r0   r   p   s   7    c                      s@   e Zd ZdZddddd fd	d
ZdddddddZ  ZS )r   a8  Apply median blur to the input image.

    This transform uses a median filter to blur the input image. Median filtering is particularly
    effective at removing salt-and-pepper noise while preserving edges, making it a popular choice
    for noise reduction in image processing.

    Args:
        blur_limit (int | tuple[int, int]): Maximum aperture linear size for blurring the input image.
            Must be odd and in the range [3, inf).
            - If a single int is provided, the kernel size will be randomly chosen
              between 3 and that value.
            - If a tuple of two ints is provided, it defines the inclusive range
              of possible kernel sizes.
            Default: (3, 7)

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The kernel size (aperture linear size) must always be odd and greater than 1.
        - Unlike mean blur or Gaussian blur, median blur uses the median of all pixels under
          the kernel area, making it more robust to outliers.
        - This transform is particularly useful for:
          * Removing salt-and-pepper noise
          * Preserving edges while smoothing images
          * Pre-processing images for edge detection algorithms
        - For color images, the median is calculated independently for each channel.
        - Larger kernel sizes result in stronger blurring effects but may also remove
          fine details from the image.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.MedianBlur(blur_limit=(3, 7), p=0.5)
        >>> result = transform(image=image)
        >>> blurred_image = result["image"]

    References:
        - Median filter: https://en.wikipedia.org/wiki/Median_filter
        - OpenCV medianBlur: https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#ga564869aa33e58769b4469101aac458f9
    rB   r!   Nr   r#   rC   rD   c                   s   t  j|||d d S rp   )rI   rJ   rL   rN   r/   r0   rJ   !  s    zMedianBlur.__init__rP   rK   r   rQ   c                 K  s   t ||S rU   )rV   Zmedian_blurrW   r/   r/   r0   rX   $  s    zMedianBlur.apply)rB   r!   N)r;   r<   r=   rc   rJ   rX   rd   r/   r/   rN   r0   r      s   3c                      sp   e Zd ZdZG dd deZddd	d
dd fddZddddddddZddddZddddZ	  Z
S )r   a	  Apply Gaussian blur to the input image using a randomly sized kernel.

    This transform blurs the input image using a Gaussian filter with a random kernel size
    and sigma value. Gaussian blur is a widely used image processing technique that reduces
    image noise and detail, creating a smoothing effect.

    Args:
        blur_limit (tuple[int, int] | int): Controls the range of the Gaussian kernel size.
            - If a single int is provided, the kernel size will be randomly chosen
              between 0 and that value.
            - If a tuple of two ints is provided, it defines the inclusive range
              of possible kernel sizes.
            Must be zero or odd and in range [0, inf). If set to 0, it will be computed
            from sigma as `round(sigma * (3 if img.dtype == np.uint8 else 4) * 2 + 1) + 1`.
            Larger kernel sizes produce stronger blur effects.
            Default: (3, 7)

        sigma_limit (tuple[float, float] | float): Range for the Gaussian kernel standard
            deviation (sigma). Must be in range [0, inf).
            - If a single float is provided, sigma will be randomly chosen
              between 0 and that value.
            - If a tuple of two floats is provided, it defines the inclusive range
              of possible sigma values.
            If set to 0, sigma will be computed as `sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`.
            Larger sigma values produce stronger blur effects.
            Default: 0

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The relationship between kernel size and sigma affects the blur strength:
          larger kernel sizes allow for stronger blurring effects.
        - When both blur_limit and sigma_limit are set to ranges starting from 0,
          the blur_limit minimum is automatically set to 3 to ensure a valid kernel size.
        - For uint8 images, the computation might be faster than for floating-point images.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.GaussianBlur(blur_limit=(3, 7), sigma_limit=(0.1, 2), p=1)
        >>> result = transform(image=image)
        >>> blurred_image = result["image"]
    c                   @  sL   e Zd ZU ded< ededddddd	Zed
dddddZdS )zGaussianBlur.InitSchemar   sigma_limitr3   r   r   r$   r4   c                 C  s   t ||ddS )Nr   r6   r7   r8   r/   r/   r0   r:   c  s    z$GaussianBlur.InitSchema.process_blurrg   rh   r   rZ   c                 C  s   t | jttfr`| jd dkr`t | jttfr`| jd dkr`dtd| jd f| _tjddd t | jtr| jD ](}|dkrr|d dkrrtd| j qr| S )Nr   r5   r   zkblur_limit and sigma_limit minimum value can not be both equal to 0. blur_limit minimum value changed to 3.r"   
stacklevelr*   )	rm   r3   rn   r\   r   maxwarningswarnr,   )rM   r.   r/   r/   r0   validate_limitsh  s$    
z'GaussianBlur.InitSchema.validate_limitsN)	r;   r<   r=   r>   r	   r?   r:   r
   r   r/   r/   r/   r0   r@   `  s   
r@   rA   r   Nr!   r   r   rC   r#   )r3   r   rF   rE   c                   s:   t  || ttttf || _ttttf || _d S rU   )rI   rJ   r   r   rK   r3   r#   r   )rM   r3   r   rF   rE   rN   r/   r0   rJ   ~  s    zGaussianBlur.__init__rP   rK   r   )rR   r   sigmarT   r(   c                 K  s   t j|||dS )N)r   )rV   Zgaussian_blur)rM   rR   r   r   rT   r/   r/   r0   rX     s    zGaussianBlur.applyzdict[str, float]rZ   c                 C  sX   t | jd | jd d }|dkrF|d dkrF|d | jd d  }|t j| j dS )Nr   r   r"   )r   r   )r}   	randranger3   uniformr   )rM   r   r/   r/   r0   r_     s    zGaussianBlur.get_paramstuple[str, str]c                 C  s   dS )N)r3   r   r/   r^   r/   r/   r0   ra     s    z*GaussianBlur.get_transform_init_args_names)rA   r   Nr!   rb   r/   r/   rN   r0   r   (  s   7     c                      sx   e Zd ZdZG dd deZdd
ddddd
d fddZddddddddZddddddZddddZ	  Z
S ) r   a	  Apply a glass blur effect to the input image.

    This transform simulates the effect of looking through textured glass by locally
    shuffling pixels in the image. It creates a distorted, frosted glass-like appearance.

    Args:
        sigma (float): Standard deviation for the Gaussian kernel used in the process.
            Higher values increase the blur effect. Must be non-negative.
            Default: 0.7

        max_delta (int): Maximum distance in pixels for shuffling.
            Determines how far pixels can be moved. Larger values create more distortion.
            Must be a positive integer.
            Default: 4

        iterations (int): Number of times to apply the glass blur effect.
            More iterations create a stronger effect but increase computation time.
            Must be a positive integer.
            Default: 2

        mode (Literal["fast", "exact"]): Mode of computation. Options are:
            - "fast": Uses a faster but potentially less accurate method.
            - "exact": Uses a slower but more precise method.
            Default: "fast"

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - This transform is particularly effective for creating a 'looking through
          glass' effect or simulating the view through a frosted window.
        - The 'fast' mode is recommended for most use cases as it provides a good
          balance between effect quality and computation speed.
        - Increasing 'iterations' will strengthen the effect but also increase the
          processing time linearly.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.GlassBlur(sigma=0.7, max_delta=4, iterations=3, mode="fast", p=1)
        >>> result = transform(image=image)
        >>> glass_blurred_image = result["image"]

    References:
        - This implementation is based on the technique described in:
          "ImageNet-trained CNNs are biased towards texture; increasing shape bias improves accuracy and robustness"
          https://arxiv.org/abs/1903.12261
        - Original implementation:
          https://github.com/hendrycks/robustness/blob/master/ImageNet-C/create_c/make_imagenet_c.py
    c                   @  sL   e Zd ZU eddZded< eddZded< eddZded< d	ed
< dS )zGlassBlur.InitSchemar   )ger#   r   r   rK   	max_delta
iterationsLiteral[('fast', 'exact')]ri   N)r;   r<   r=   r   r   r>   r   r   r/   r/   r/   r0   r@     s   
r@   ffffff?   r"   fastNr!   r#   rK   r   rC   )r   r   r   ri   rF   rE   c                   s,   t  j||d || _|| _|| _|| _d S rG   )rI   rJ   r   r   r   ri   )rM   r   r   r   ri   rF   rE   rN   r/   r0   rJ     s
    	zGlassBlur.__init__rP   r   )rR   argsdxyrT   r(   c                O  s   t || j| j| j|| jS rU   )rV   Z
glass_blurr   r   r   ri   )rM   rR   r   r   rT   r/   r/   r0   rX     s    zGlassBlur.applyrY   dict[str, np.ndarray])rT   datar(   c           	      C  sb   |d d d \}}|| j d  }|| j d  }t|| }tj| j  | j || jdfd}d|iS )Nshaper"   )sizer   )r   rK   r   r   r   )	rM   rT   r   heightwidthZwidth_pixelsZheight_pixelsZtotal_pixelsr   r/   r/   r0   get_params_dependent_on_data  s    z&GlassBlur.get_params_dependent_on_dataztuple[str, str, str, str]rZ   c                 C  s   dS )N)r   r   r   ri   r/   r^   r/   r/   r0   ra     s    z'GlassBlur.get_transform_init_args_names)r   r   r"   r   Nr!   )r;   r<   r=   rc   r   r@   rJ   rX   r   ra   rd   r/   r/   rN   r0   r     s   =      c                      sz   e Zd ZdZG dd deZdddddddddddd
 fddZdddddddZddddZddddZ	  Z
S ) r   u  Applies a Generalized Gaussian blur to the input image with randomized parameters for advanced data augmentation.

    This transform creates a custom blur kernel based on the Generalized Gaussian distribution,
    which allows for a wide range of blur effects beyond standard Gaussian blur. It then applies
    this kernel to the input image through convolution. The transform also incorporates noise
    into the kernel, resulting in a unique combination of blurring and noise injection.

    Key features of this augmentation:

    1. Generalized Gaussian Kernel: Uses a generalized normal distribution to create kernels
       that can range from box-like blurs to very peaked blurs, controlled by the beta parameter.

    2. Anisotropic Blurring: Allows for different blur strengths in horizontal and vertical
       directions (controlled by sigma_x and sigma_y), and rotation of the kernel.

    3. Kernel Noise: Adds multiplicative noise to the kernel before applying it to the image,
       creating more diverse and realistic blur effects.

    Implementation Details:
        The kernel is generated using a 2D Generalized Gaussian function. The process involves:
        1. Creating a 2D grid based on the kernel size
        2. Applying rotation to this grid
        3. Calculating the kernel values using the Generalized Gaussian formula
        4. Adding multiplicative noise to the kernel
        5. Normalizing the kernel

        The resulting kernel is then applied to the image using convolution.

    Args:
        blur_limit (tuple[int, int] | int, optional): Controls the size of the blur kernel. If a single int
            is provided, the kernel size will be randomly chosen between 3 and that value.
            Must be odd and ≥ 3. Larger values create stronger blur effects.
            Default: (3, 7)

        sigma_x_limit (tuple[float, float] | float): Controls the spread of the blur in the x direction.
            Higher values increase blur strength.
            If a single float is provided, the range will be (0, limit).
            Default: (0.2, 1.0)

        sigma_y_limit (tuple[float, float] | float): Controls the spread of the blur in the y direction.
            Higher values increase blur strength.
            If a single float is provided, the range will be (0, limit).
            Default: (0.2, 1.0)

        rotate_limit (tuple[int, int] | int): Range of angles (in degrees) for rotating the kernel.
            This rotation allows for diagonal blur directions. If limit is a single int, an angle is picked
            from (-rotate_limit, rotate_limit).
            Default: (-90, 90)

        beta_limit (tuple[float, float] | float): Shape parameter of the Generalized Gaussian distribution.
            - beta = 1 gives a standard Gaussian distribution
            - beta < 1 creates heavier tails, resulting in more uniform, box-like blur
            - beta > 1 creates lighter tails, resulting in more peaked, focused blur
            Default: (0.5, 8.0)

        noise_limit (tuple[float, float] | float): Controls the strength of multiplicative noise
            applied to the kernel. Values around 1.0 keep the original kernel mostly intact,
            while values further from 1.0 introduce more variation.
            Default: (0.75, 1.25)

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

    Notes:
        - This transform is particularly useful for simulating complex, real-world blur effects
          that go beyond simple Gaussian blur.
        - The combination of blur and noise can help in creating more robust models by simulating
          a wider range of image degradations.
        - Extreme values, especially for beta and noise, may result in unrealistic effects and
          should be used cautiously.

    Reference:
        This transform is inspired by techniques described in:
        "Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data"
        https://arxiv.org/abs/2107.10833

    Targets:
        image

    Image types:
        uint8, float32
    c                   @  sj   e Zd ZU ded< ded< ded< ded< ded< ededd	d
ddZeddddddZdS )zAdvancedBlur.InitSchemar   sigma_x_limitsigma_y_limit
beta_limitnoise_limitr   rotate_limitr   ztuple[float, float])r%   r(   c                 C  s:   t |dd}|d d  k r(|d k s6n d}t||S )Nr   )low      ?r   z&beta_limit is expected to include 1.0.)r   r,   )r9   r%   r-   msgr/   r/   r0   check_beta_limitV  s
    z(AdvancedBlur.InitSchema.check_beta_limitrg   rh   r   rZ   c                 C  sL   t | jttfrH| jd dkrHt | jttfrH| jd dkrHd}t|| S )Nr   zHsigma_x_limit and sigma_y_limit minimum value cannot be both equal to 0.)rm   r   rn   r\   r   r,   )rM   r   r/   r/   r0   r   _  s    z'AdvancedBlur.InitSchema.validate_limitsN)	r;   r<   r=   r>   r	   r?   r   r
   r   r/   r/   r/   r0   r@   O  s   
r@   rA   g?r   NiZ   r!   g       @g?g?r!   r   r   zScaleFloatType | NonerC   r#   )
r3   r   r   sigmaX_limitsigmaY_limitr   r   r   rF   rE   c                   s   t  j|
|	d |d k	r,tjdtdd |}|d k	rHtjdtdd |}ttttf || _ttt	t	f || _
ttt	t	f || _ttttf || _ttt	t	f || _ttt	t	f || _d S )NrH   z6sigmaX_limit is deprecated; use sigma_x_limit instead.r"   r   z6sigmaY_limit is deprecated; use sigma_y_limit instead.)rI   rJ   r   r   DeprecationWarningr   r   rK   r3   r#   r   r   r   r   r   )rM   r3   r   r   r   r   r   r   r   rF   rE   rN   r/   r0   rJ   k  s    zAdvancedBlur.__init__rP   r   rQ   c                 K  s   t j||dS rq   rr   rW   r/   r/   r0   rX     s    zAdvancedBlur.applyr   rZ   c                 C  s  t | jd | jd d d}t j| j }t j| j }tt j| j }t   t	k rft | j
d dnt d| j
d }tj| jd||fi}t| d d |d d }tjt||dd}t|d dgd|d gg}	tt|t| gt|t|gg}
t|
t|	|
j}tj|}tdttt||| d| }||9 }|tjt| }d	|iS )
Nr   r   r"   r   r   )Zaxisg      rS   )r}   r   r3   r   r   r   r   Zdeg2radr   HALFr   r   r   arangestackZmeshgridarraycossindotTZlinalginvexppowerr   r   r   )rM   r   Zsigma_xZsigma_yZanglebetaZnoise_matrixZaxZgridZd_matrixZu_matrixZsigma_matrixZinverse_sigmarS   r/   r/   r0   r_     s"    .0*zAdvancedBlur.get_paramsz#tuple[str, str, str, str, str, str]c                 C  s   dS )N)r3   r   r   r   r   r   r/   r^   r/   r/   r0   ra     s    z*AdvancedBlur.get_transform_init_args_names)
rA   r   r   NNr   r   r   Nr!   rb   r/   r/   rN   r0   r     s    R          &!c                      sp   e Zd ZdZG dd deZddd	d
dd fddZddddddddZddddZddddZ	  Z
S )r   ac  Apply defocus blur to the input image.

    This transform simulates the effect of an out-of-focus camera by applying a defocus blur
    to the image. It uses a combination of disc kernels and Gaussian blur to create a realistic
    defocus effect.

    Args:
        radius (tuple[int, int] | int): Range for the radius of the defocus blur.
            If a single int is provided, the range will be [1, radius].
            Larger values create a stronger blur effect.
            Default: (3, 10)

        alias_blur (tuple[float, float] | float): Range for the standard deviation of the Gaussian blur
            applied after the main defocus blur. This helps to reduce aliasing artifacts.
            If a single float is provided, the range will be (0, alias_blur).
            Larger values create a smoother, more aliased effect.
            Default: (0.1, 0.5)

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

    Targets:
        image

    Image types:
        uint8, float32

    Note:
        - The defocus effect is created using a disc kernel, which simulates the shape of a camera's aperture.
        - The additional Gaussian blur (alias_blur) helps to soften the edges of the disc kernel, creating a
          more natural-looking defocus effect.
        - Larger radius values will create a stronger, more noticeable defocus effect.
        - The alias_blur parameter can be used to fine-tune the appearance of the defocus, with larger values
          creating a smoother, potentially more realistic effect.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.Defocus(radius=(4, 8), alias_blur=(0.2, 0.4), always_apply=True)
        >>> result = transform(image=image)
        >>> defocused_image = result['image']

    References:
        - https://en.wikipedia.org/wiki/Defocus_aberration
        - https://www.researchgate.net/publication/261311609_Realistic_Defocus_Blur_for_Multiplane_Computer-Generated_Holography
    c                   @  s   e Zd ZU ded< ded< dS )zDefocus.InitSchemar   radiusr   
alias_blurNr;   r<   r=   r>   r/   r/   r/   r0   r@     s   
r@   r5   
   g?r!   Nr!   r   r   rC   r#   )r   r   rF   rE   c                   s:   t  || ttttf || _ttttf || _d S rU   )rI   rJ   r   r   rK   r   r#   r   )rM   r   r   rF   rE   rN   r/   r0   rJ     s    zDefocus.__init__rP   rK   r   )rR   r   r   rT   r(   c                 K  s   t |||S rU   )rV   Zdefocus)rM   rR   r   r   rT   r/   r/   r0   rX     s    zDefocus.applyrY   rZ   c                 C  s   t j| j t j| j dS N)r   r   )r}   r   r   r   r   r^   r/   r/   r0   r_     s    

zDefocus.get_paramsr   c                 C  s   dS r   r/   r^   r/   r/   r0   ra     s    z%Defocus.get_transform_init_args_names)r   r   Nr!   r;   r<   r=   rc   r   r@   rJ   rX   r_   ra   rd   r/   r/   rN   r0   r     s   0    c                      sn   e Zd ZdZG dd deZdddd	d
d fddZdddddddZddddZddddZ	  Z
S )r    a  Apply zoom blur transform.

    Args:
        max_factor ((float, float) or float): range for max factor for blurring.
            If max_factor is a single float, the range will be (1, limit). Default: (1, 1.31).
            All max_factor values should be larger than 1.
        step_factor ((float, float) or float): If single float will be used as step parameter for np.arange.
            If tuple of float step_factor will be in range `[step_factor[0], step_factor[1])`. Default: (0.01, 0.03).
            All step_factor values should be positive.
        p (float): probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        unit8, float32

    Reference:
        https://arxiv.org/abs/1903.12261
    c                   @  s   e Zd ZU ded< ded< dS )zZoomBlur.InitSchemar   
max_factorr   step_factorNr   r/   r/   r/   r0   r@     s   
r@   r   g(\?g{Gz?gQ?Nr!   r   rC   r#   )r   r   rF   rE   c                   s:   t  || ttttf || _ttttf || _d S rU   )rI   rJ   r   r   r#   r   r   )rM   r   r   rF   rE   rN   r/   r0   rJ     s    zZoomBlur.__init__rP   r   )rR   zoom_factorsrT   r(   c                 K  s   t ||S rU   )rV   Z	zoom_blur)rM   rR   r   rT   r/   r/   r0   rX   *  s    zZoomBlur.applyrY   rZ   c                 C  s4   t j| j }td| t j| j }dtd||iS )Nr   r   r   )r}   r   r   r   r   r   r   )rM   r   r   r/   r/   r0   r_   -  s    zZoomBlur.get_paramsr   c                 C  s   dS )N)r   r   r/   r^   r/   r/   r0   ra   2  s    z&ZoomBlur.get_transform_init_args_names)r   r   Nr!   r   r/   r/   rN   r0   r      s       )r   )6
__future__r   r}   r   typingr   r   r   r   r   Znumpyr   Zpydanticr   r   r	   r
   Ztyping_extensionsr   Zalbumentationsr   Zalbumentations.augmentationsr   rs   Z"albumentations.augmentations.utilsr   Zalbumentations.core.pydanticr   r   r   r   Z(albumentations.core.transforms_interfacer   r   Zalbumentations.core.typesr   r   Zalbumentations.core.utilsr    rV   __all__r   r~   r1   r2   r   r   r   r   r   r   r   r    r/   r/   r/   r0   <module>   s:   	:};oe =M