U
    h<                 *   @  s  d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dlm	Z	m
Z
mZmZmZmZmZmZ d dlmZ d dlZd dlZd dlZd dlmZmZmZmZmZmZmZmZmZmZm Z  d dl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' d dl(m)Z) d d	l*m+Z+ d d
l,m-Z-m.Z.m/Z/m0Z0 d dl1m2  m3  m4Z5 d dl6m2  m7  m4Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z>m?Z? d dl@mAZAmBZB d dlCmDZDmEZEmFZF d dlGmHZH d dlImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZT d dlUmVZVmWZWmXZXmYZYmZZZ d dl[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZi d dljmkZkmlZl ddlmm4Zn dddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@g*ZodAZpdBZqdCZrG dDd deWZsG dEd deXZtG dFd# d#eXZuG dGd' d'eXZvG dHd( d(eXZwG dId) d)eXZxG dJd* d*eXZyG dKd+ d+eXZzG dLd, d,eXZ{G dMd- d-eXZ|G dNd deXZ}G dOd0 d0eXZ~G dPd2 d2eXZG dQd1 d1eXZG dRd deXZG dSd& d&eXZG dTd deXZG dUd/ d/eXZG dVd deXZG dWd deXZG dXd deXZG dYd deXZG dZd  d eXZG d[d! d!eXZG d\d" d"eXZG d]d$ d$eXZG d^d% d%eXZG d_d` d`e0ZG dadb dbe#ZG dcd3 d3eXZG ddd. d.eZZG ded4 d4eXZG dfd5 d5eXZG dgd6 d6eXZG dhd7 d7eXZG did8 d8eXZG djd9 d9eXZG dkd: d:eXZG dld; d;eXZG dmd< d<eWZG dnd= d=eXZG dod> d>eXZG dpd? d?eWZeenjdq  enjdr   eenjdq  eenjdr  dsdtduZG dvd@ d@eXZdS )w    )annotationsN)
LambdaType)AnyCallableDictListSequenceTupleUnioncast)warn)MAX_VALUES_BY_DTYPENUM_MULTI_CHANNEL_DIMENSIONSclip
from_floatget_num_channelsis_grayscale_imageis_rgb_imagemultiply	normalizenormalize_per_imageto_float)AfterValidator	BaseModelFieldValidationInfofield_validatormodel_validator)special)gaussian_filter)	AnnotatedLiteralSelf	TypedDict)random_utils)blur)BlurInitSchemaprocess_blur_limit)check_rangenon_rgb_error)BboxProcessordenormalize_bboxesnormalize_bboxes)KeypointsProcessor)InterpolationTypeNonNegativeFloatRangeTypeOnePlusFloatRangeTypeOnePlusIntRangeTypeProbabilityTypeSymmetricRangeTypeZeroOneRangeTypecheck_0pluscheck_01check_1plusnondecreasing)BaseTransformInitSchemaDualTransformImageOnlyTransformInterpolationNoOp)MAX_RAIN_ANGLEMONO_CHANNEL_DIMENSIONSNUM_RGB_CHANNELSPAIRChromaticAberrationMode	ColorType	ImageModeMorphologyModePlanckianJitterModeRainModeScaleFloatTypeScaleIntTypeSpatterModeTargets)format_argsto_tuple   )
functional	NormalizeRandomGammaRandomGridShuffleHueSaturationValueRGBShift
GaussNoiseCLAHEChannelShuffle	InvertImgToGrayToRGBToSepiaImageCompressionToFloat	FromFloatRandomBrightnessContrast
RandomSnowRandomGravel
RandomRain	RandomFogRandomSunFlareRandomShadowRandomToneCurveLambdaISONoiseSolarizeEqualize	Posterize	DownscaleMultiplicativeNoiseFancyPCAColorJitterSharpenEmbossSuperpixelsRingingOvershootUnsharpMaskPixelDropoutSpatterChromaticAberrationMorphologicalPlanckianJitter   d      c                      s   e Zd ZdZG dd deZejejej	fZ
d"ddd	d
 fddZddddddddZddddddddZddddddZddddZeddd d!Z  ZS )#rR   a  Randomly shuffles the grid's cells on an image, mask, or keypoints,
    effectively rearranging patches within the image.
    This transformation divides the image into a grid and then permutes these grid cells based on a random mapping.

    Args:
        grid (tuple[int, int]): Size of the grid for splitting the image into cells. Each cell is shuffled randomly.
            For example, (3, 3) will divide the image into a 3x3 grid, resulting in 9 cells to be shuffled.
            Default: (3, 3)
        p (float): Probability that the transform will be applied. Should be in the range [0, 1].
            Default: 0.5

    Targets:
        image, mask, keypoints

    Image types:
        uint8, float32

    Note:
        - This transform maintains consistency across all targets. If applied to an image and its corresponding
          mask or keypoints, the same shuffling will be applied to all.
        - The number of cells in the grid should be at least 2 (i.e., grid should be at least (1, 2), (2, 1), or (2, 2))
          for the transform to have any effect.
        - Keypoints are moved along with their corresponding grid cell.
        - This transform could be useful when only micro features are important for the model, and memorizing
          the global structure could be harmful. For example:
          - Identifying the type of cell phone used to take a picture based on micro artifacts generated by
            phone post-processing algorithms, rather than the semantic features of the photo.
            See more at https://ieeexplore.ieee.org/abstract/document/8622031
          - Identifying stress, glucose, hydration levels based on skin images.

    Mathematical Formulation:
        1. The image is divided into a grid of size (m, n) as specified by the 'grid' parameter.
        2. A random permutation P of integers from 0 to (m*n - 1) is generated.
        3. Each cell in the grid is assigned a number from 0 to (m*n - 1) in row-major order.
        4. The cells are then rearranged according to the permutation P.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.array([
        ...     [1, 1, 1, 2, 2, 2],
        ...     [1, 1, 1, 2, 2, 2],
        ...     [1, 1, 1, 2, 2, 2],
        ...     [3, 3, 3, 4, 4, 4],
        ...     [3, 3, 3, 4, 4, 4],
        ...     [3, 3, 3, 4, 4, 4]
        ... ])
        >>> transform = A.RandomGridShuffle(grid=(2, 2), p=1.0)
        >>> result = transform(image=image)
        >>> transformed_image = result['image']
        # The resulting image might look like this (one possible outcome):
        # [[4, 4, 4, 2, 2, 2],
        #  [4, 4, 4, 2, 2, 2],
        #  [4, 4, 4, 2, 2, 2],
        #  [3, 3, 3, 1, 1, 1],
        #  [3, 3, 3, 1, 1, 1],
        #  [3, 3, 3, 1, 1, 1]]

    c                   @  s   e Zd ZU ded< dS )zRandomGridShuffle.InitSchema7Annotated[tuple[int, int], AfterValidator(check_1plus)]gridN__name__
__module____qualname____annotations__ r   r   K/tmp/pip-unpacked-wheel-e8onvpoz/albumentations/augmentations/transforms.py
InitSchema   s   
r   rz   rz         ?Ntuple[int, int]floatbool | None)r~   palways_applyc                   s   t  j||d || _d S Nr   r   )super__init__r~   )selfr~   r   r   	__class__r   r   r      s    zRandomGridShuffle.__init__
np.ndarray	list[int]r   )imgtilesmappingparamsreturnc                 K  s   t |||S N)fmainZswap_tiles_on_image)r   r   r   r   r   r   r   r   apply   s    zRandomGridShuffle.apply)	keypointsr   r   r   r   c                 K  s   t |||S r   )r   Zswap_tiles_on_keypoints)r   r   r   r   r   r   r   r   apply_to_keypoints   s    z$RandomGridShuffle.apply_to_keypointsdict[str, Any]dict[str, np.ndarray]r   datar   c                 C  sL   |d d d }t  }tj|| j|d}t|}tj||d}||dS )Nshape   )random_state)r   r   )r$   get_random_state
fgeometricZsplit_uniform_gridr~   r   Zcreate_shape_groupsZ!shuffle_tiles_within_shape_groups)r   r   r   image_shaper   Zoriginal_tilesZshape_groupsr   r   r   r   get_params_dependent_on_data   s    
z.RandomGridShuffle.get_params_dependent_on_datatuple[str, ...]r   c                 C  s   dS )N)r~   r   r   r   r   r   get_transform_init_args_names   s    z/RandomGridShuffle.get_transform_init_args_nameszdict[str, Callable[..., Any]]c                 C  s   | j | j| j| jdS )N)imagemaskmasksr   )r   apply_to_maskZapply_to_masksr   r   r   r   r   targets   s
    zRandomGridShuffle.targets)r   r   N)r   r   r   __doc__r9   r   rK   IMAGEMASK	KEYPOINTS_targetsr   r   r   r   r   propertyr   __classcell__r   r   r   r   rR      s   <	c                      sb   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ZddddZ  Z	S )rP   a  Applies various normalization techniques to an image. The specific normalization technique can be selected
        with the `normalization` parameter.

    Standard normalization is applied using the formula:
        `img = (img - mean * max_pixel_value) / (std * max_pixel_value)`.
        Other normalization techniques adjust the image based on global or per-channel statistics,
        or scale pixel values to a specified range.

    Args:
        mean (ColorType | None): Mean values for standard normalization.
            For "standard" normalization, the default values are ImageNet mean values: (0.485, 0.456, 0.406).
            For "inception" normalization, use mean values of (0.5, 0.5, 0.5).
        std (ColorType | None): Standard deviation values for standard normalization.
            For "standard" normalization, the default values are ImageNet standard deviation :(0.229, 0.224, 0.225).
            For "inception" normalization, use standard deviation values of (0.5, 0.5, 0.5).
        max_pixel_value (float | None): Maximum possible pixel value, used for scaling in standard normalization.
            Defaults to 255.0.
        normalization (Literal["standard", "image", "image_per_channel", "min_max", "min_max_per_channel", "inception"])
            Specifies the normalization technique to apply. Defaults to "standard".
            - "standard": Applies the formula `(img - mean * max_pixel_value) / (std * max_pixel_value)`.
                The default mean and std are based on ImageNet.
            - "image": Normalizes the whole image based on its global mean and standard deviation.
            - "image_per_channel": Normalizes the image per channel based on each channel's mean and standard deviation.
            - "min_max": Scales the image pixel values to a [0, 1] range based on the global
                minimum and maximum pixel values.
            - "min_max_per_channel": Scales each channel of the image pixel values to a [0, 1]
                range based on the per-channel minimum and maximum pixel values.

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

    Targets:
        image

    Image types:
        uint8, float32

    Note:
        - For "standard" normalization, `mean`, `std`, and `max_pixel_value` must be provided.
        - For other normalization types, these parameters are ignored.
        - For inception normalization, use mean values of (0.5, 0.5, 0.5).
        - For YOLO normalization, use mean values of (0.5, 0.5, 0.5) and std values of (0, 0, 0).
        - This transform is often used as a final step in image preprocessing pipelines to
          prepare images for neural network input.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> # Standard ImageNet normalization
        >>> transform = A.Normalize(
        ...     mean=(0.485, 0.456, 0.406),
        ...     std=(0.229, 0.224, 0.225),
        ...     max_pixel_value=255.0,
        ...     p=1.0
        ... )
        >>> normalized_image = transform(image=image)["image"]
        >>>
        >>> # Min-max normalization
        >>> transform_minmax = A.Normalize(normalization="min_max", p=1.0)
        >>> normalized_image_minmax = transform_minmax(image=image)["image"]

    References:
        - ImageNet mean and std: https://pytorch.org/vision/stable/models.html
        - Inception preprocessing: https://keras.io/api/applications/inceptionv3/
    c                   @  sF   e Zd ZU ded< ded< ded< ded< edd	d
dddZdS )zNormalize.InitSchemaColorType | Nonemeanstdfloat | Nonemax_pixel_valueULiteral[('standard', 'image', 'image_per_channel', 'min_max', 'min_max_per_channel')]normalizationaftermoder"   r   c                 C  s4   | j d ks(| jd ks(| jd kr0| jdkr0td| S )NstandardzKmean, std, and max_pixel_value must be provided for standard normalization.)r   r   r   r   
ValueErrorr   r   r   r   validate_normalization=  s    z+Normalize.InitSchema.validate_normalizationN)r   r   r   r   r   r   r   r   r   r   r   1  s   
r   g
ףp=
?gv/?gCl?gZd;O?gy&1?g?     o@r   N      ?r   r   r   r   r   )r   r   r   r   r   r   c                   s^   t  j||d || _tj|tjd| | _|| _ttj|tjd| | _	|| _
|| _d S )Nr   dtype)r   r   r   nparrayfloat32mean_npr   Z
reciprocaldenominatorr   r   )r   r   r   r   r   r   r   r   r   r   r   H  s    	zNormalize.__init__r   r   r   r   r   c                 K  s&   | j dkrt|| j| jS t|| j S )Nr   )r   r   r   r   r   r   r   r   r   r   r   r   Y  s    
zNormalize.applyr   r   c                 C  s   dS )N)r   r   r   r   r   r   r   r   r   r   b  s    z'Normalize.get_transform_init_args_names)r   r   r   r   Nr   
r   r   r   r   r9   r   r   r   r   r   r   r   r   r   rP      s   B      	c                      st   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ZddddZ	  Z
S )r\   aB  Decrease image quality by applying JPEG or WebP compression.

    This transform simulates the effect of saving an image with lower quality settings,
    which can introduce compression artifacts. It's useful for data augmentation and
    for testing model robustness against varying image qualities.

    Args:
        quality_range (tuple[int, int]): Range for the compression quality.
            The values should be in [1, 100] range, where:
            - 1 is the lowest quality (maximum compression)
            - 100 is the highest quality (minimum compression)
            Default: (99, 100)

        compression_type (Literal["jpeg", "webp"]): Type of compression to apply.
            - "jpeg": JPEG compression
            - "webp": WebP compression
            Default: "jpeg"

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - This transform expects images with 1, 3, or 4 channels.
        - For JPEG compression, alpha channels (4th channel) will be ignored.
        - WebP compression supports transparency (4 channels).
        - The actual file is not saved to disk; the compression is simulated in memory.
        - Lower quality values result in smaller file sizes but may introduce visible artifacts.
        - This transform can be useful for:
          * Data augmentation to improve model robustness
          * Testing how models perform on images of varying quality
          * Simulating images transmitted over low-bandwidth connections

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.ImageCompression(quality_range=(50, 90), compression_type=0, p=1.0)
        >>> result = transform(image=image)
        >>> compressed_image = result["image"]

    References:
        - JPEG compression: https://en.wikipedia.org/wiki/JPEG
        - WebP compression: https://developers.google.com/speed/webp
    c                   @  s^   e Zd ZU ded< edddZded< edddZded< d	ed
< eddddddZdS )zImageCompression.InitSchemaVAnnotated[tuple[int, int], AfterValidator(check_1plus), AfterValidator(nondecreasing)]quality_rangerN   r{   gele
int | Nonequality_lowerquality_upperLiteral[('jpeg', 'webp')]compression_typer   r   r"   r   c                 C  s   | j d k	s| jd k	r| j d k	r,tdtdd | jd k	rDtdtdd | j d k	rT| j n| jd }| jd k	rn| jn| jd }||f| _d | _ d | _d| jd   krtkrn nd| jd   krtksn tdt d| S )	Nzc`quality_lower` is deprecated. Use `quality_range` as tuple (quality_lower, quality_upper) instead.r   
stacklevelzc`quality_upper` is deprecated. Use `quality_range` as tuple (quality_lower, quality_upper) instead.r   rN   z*Quality range values should be within [1, ] range.)r   r   r   DeprecationWarningr   MAX_JPEG_QUALITYr   r   lowerupperr   r   r   validate_ranges  s*    


:z+ImageCompression.InitSchema.validate_rangesN)	r   r   r   r   r   r   r   r   r   r   r   r   r   r     s   
r   Njpegc   r{   r   r   r   r   r   r   )r   r   r   r   r   r   c                   s    t  j||d || _|| _d S r   )r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r     s    	zImageCompression.__init__r   intzLiteral[('.jpg', '.webp')]r   )r   quality
image_typer   r   c                 K  s   t |||S r   )r   Zimage_compression)r   r   r   r   r   r   r   r   r     s    zImageCompression.applyzdict[str, int | str]r   c                 C  sB   | j dkrd}n | j dkr d}ntd| j  tj| j |dS )Nr   z.jpgZwebpz.webpz Unknown image compression type: )r   r   )r   r   randomrandintr   )r   r   r   r   r   
get_params  s    


zImageCompression.get_paramsr   c                 C  s   | j | jdS )Nr   r   r   r   r   r   r   get_transform_init_args  s    z(ImageCompression.get_transform_init_args)NNr   r   Nr   )r   r   r   r   r9   r   r   r   r   r   r   r   r   r   r   r\   f  s   5.      c                	      st   e Zd ZdZG dd deZ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 random snow effect to the input image.

    This transform simulates snowfall by either bleaching out some pixel values or
    adding a snow texture to the image, depending on the chosen method.

    Args:
        snow_point_range (tuple[float, float]): Range for the snow point threshold.
            Both values should be in the (0, 1) range. Default: (0.1, 0.3).
        brightness_coeff (float): Coefficient applied to increase the brightness of pixels
            below the snow_point threshold. Larger values lead to more pronounced snow effects.
            Should be > 0. Default: 2.5.
        method (Literal["bleach", "texture"]): The snow simulation method to use. Options are:
            - "bleach": Uses a simple pixel value thresholding technique.
            - "texture": Applies a more realistic snow texture overlay.
            Default: "texture".
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Note:
        - The "bleach" method increases the brightness of pixels above a certain threshold,
          creating a simple snow effect. This method is faster but may look less realistic.
        - The "texture" method creates a more realistic snow effect through the following steps:
          1. Converts the image to HSV color space for better control over brightness.
          2. Increases overall image brightness to simulate the reflective nature of snow.
          3. Generates a snow texture using Gaussian noise, which is then smoothed with a Gaussian filter.
          4. Applies a depth effect to the snow texture, making it more prominent at the top of the image.
          5. Blends the snow texture with the original image using alpha compositing.
          6. Adds a slight blue tint to simulate the cool color of snow.
          7. Adds random sparkle effects to simulate light reflecting off snow crystals.
          This method produces a more realistic result but is computationally more expensive.

    Mathematical Formulation:
        For the "bleach" method:
        Let L be the lightness channel in HLS color space.
        For each pixel (i, j):
        If L[i, j] > snow_point:
            L[i, j] = L[i, j] * brightness_coeff

        For the "texture" method:
        1. Brightness adjustment: V_new = V * (1 + brightness_coeff * snow_point)
        2. Snow texture generation: T = GaussianFilter(GaussianNoise(μ=0.5, sigma=0.3))
        3. Depth effect: D = LinearGradient(1.0 to 0.2)
        4. Final pixel value: P = (1 - alpha) * original_pixel + alpha * (T * D * 255)
           where alpha is the snow intensity factor derived from snow_point.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Default usage (bleach method)
        >>> transform = A.RandomSnow(p=1.0)
        >>> snowy_image = transform(image=image)["image"]

        # Using texture method with custom parameters
        >>> transform = A.RandomSnow(
        ...     snow_point_range=(0.2, 0.4),
        ...     brightness_coeff=2.0,
        ...     method="texture",
        ...     p=1.0
        ... )
        >>> snowy_image = transform(image=image)["image"]

    References:
        - Bleach method: https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
        - Texture method: Inspired by computer graphics techniques for snow rendering
          and atmospheric scattering simulations.
    c                   @  sp   e Zd ZU ded< edddZded< edddZded< edd	Zd
ed< ded< eddddddZ	dS )zRandomSnow.InitSchemaWAnnotated[tuple[float, float], AfterValidator(check_01), AfterValidator(nondecreasing)]snow_point_ranger   rN   )gtltr   snow_point_lowersnow_point_upperr   r   brightness_coeffLiteral[('bleach', 'texture')]methodr   r   r"   r   c                 C  s   | j d k	s| jd k	r| j d k	r,tdtdd | jd k	rDtdtdd | j d k	rT| j n| jd }| jd k	rn| jn| jd }||f| _d | _ d | _d| jd   k r| jd   krdk sn td| S )Nzl`snow_point_lower` deprecated. Use `snow_point_range` as tuple (snow_point_lower, snow_point_upper) instead.r   r   zk`snow_point_upper` deprecated. Use `snow_point_range` as tuple(snow_point_lower, snow_point_upper) instead.r   rN   zAsnow_point_range values should be increasing within (0, 1) range.)r   r   r   r   r   r   r   r   r   r   r   E  s*    


,z%RandomSnow.InitSchema.validate_rangesN)
r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   7  s   
r   N      @皙?333333?bleachr   r   r   tuple[float, float]r   r   )r   r   r   r   r   r   r   c                   s&   t  j||d || _|| _|| _d S r   )r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   b  s    
zRandomSnow.__init__r   r   )r   
snow_pointr   r   c                 K  sP   t | | jdkr"t||| jS | jdkr<t||| jS td| j d S )Nr  ZtexturezUnknown snow method: )r)   r   r   Zadd_snow_bleachr   Zadd_snow_texturer   )r   r   r  r   r   r   r   r   r  s    

zRandomSnow.applyr   r   c                 C  s   dt j| j iS )Nr  )r   uniformr   r   r   r   r   r   |  s    zRandomSnow.get_paramstuple[str, str]c                 C  s   dS )N)r   r   r   r   r   r   r   r     s    z(RandomSnow.get_transform_init_args_names)NNr   r   r  Nr   r   r   r   r   r9   r   r   r   r   r   r   r   r   r   r   r`     s   J-        
c                      s   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ZdddddddZddddddZ	ddd d!Z
  ZS )#ra   aV  Adds gravel-like artifacts to the input image.

    This transform simulates the appearance of gravel or small stones scattered across
    specific regions of an image. It's particularly useful for augmenting datasets of
    road or terrain images, adding realistic texture variations.

    Args:
        gravel_roi (tuple[float, float, float, float]): Region of interest where gravel
            will be added, specified as (x_min, y_min, x_max, y_max) in relative coordinates
            [0, 1]. Default: (0.1, 0.4, 0.9, 0.9).
        number_of_patches (int): Number of gravel patch regions to generate within the ROI.
            Each patch will contain multiple gravel particles. Default: 2.
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        3

    Note:
        - The gravel effect is created by modifying the saturation channel in the HLS color space.
        - Gravel particles are distributed within randomly generated patches inside the specified ROI.
        - This transform is particularly useful for:
          * Augmenting datasets for road condition analysis
          * Simulating variations in terrain for computer vision tasks
          * Adding realistic texture to synthetic images of outdoor scenes

    Mathematical Formulation:
        For each gravel patch:
        1. A rectangular region is randomly generated within the specified ROI.
        2. Within this region, multiple gravel particles are placed.
        3. For each particle:
           - Random (x, y) coordinates are generated within the patch.
           - A random radius (r) between 1 and 3 pixels is assigned.
           - A random saturation value (sat) between 0 and 255 is assigned.
        4. The saturation channel of the image is modified for each particle:
           image_hls[y-r:y+r, x-r:x+r, 1] = sat

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Default usage
        >>> transform = A.RandomGravel(p=1.0)
        >>> augmented_image = transform(image=image)["image"]

        # Custom ROI and number of patches
        >>> transform = A.RandomGravel(
        ...     gravel_roi=(0.2, 0.2, 0.8, 0.8),
        ...     number_of_patches=5,
        ...     p=1.0
        ... )
        >>> augmented_image = transform(image=image)["image"]

        # Combining with other transforms
        >>> transform = A.Compose([
        ...     A.RandomGravel(p=0.7),
        ...     A.RandomBrightnessContrast(p=0.5),
        ... ])
        >>> augmented_image = transform(image=image)["image"]

    References:
        - Road surface textures: https://en.wikipedia.org/wiki/Road_surface
        - HLS color space: https://en.wikipedia.org/wiki/HSL_and_HSV
    c                   @  s@   e Zd ZU ded< eddZded< eddd	d
ddZdS )zRandomGravel.InitSchema!tuple[float, float, float, float]
gravel_roirN   r   r   number_of_patchesr   r   r"   r   c                 C  sf   | j \}}}}d|  kr,|  k r,dkrPn n d|  krN|  k rNdksbn td| j  d| S )Nr   rN   zInvalid gravel_roi. Got: .)r
  r   )r   Zgravel_lower_xZgravel_lower_yZgravel_upper_xZgravel_upper_yr   r   r   validate_gravel_roi  s    Bz+RandomGravel.InitSchema.validate_gravel_roiN)r   r   r   r   r   r  r   r  r   r   r   r   r     s   
r   r  皙??r  r   Nr   r	  r   r   r   )r
  r  r   r   c                   s   t  || || _|| _d S r   )r   r   r
  r  )r   r
  r  r   r   r   r   r   r     s    zRandomGravel.__init__ztuple[int, int, int, int]r   )rectangular_roir   c           	      C  st   |\}}}}t || ||  }|d }tj|dgtjd}t||||d d df< t||||d d df< |S )N
   r   r   r   rN   )absr   emptyint64r$   r   )	r   r  x_miny_minx_maxy_maxareacountZgravelsr   r   r   generate_gravel_patch  s    z"RandomGravel.generate_gravel_patch	list[Any]r   )r   gravels_infosr   r   c                 K  s   t ||S r   )r   Z
add_gravel)r   r   r  r   r   r   r   r     s    zRandomGravel.applyr   r   r   c                 C  sP  |d d d \}}dd t | j||||gD \}}}}|| }	|| }
g }t| jD ]}t|	d |	d }t|
d |
d }t||| }t||| }|| d }t|D ]}t||| }t||| }tdd	}td
d}|t|| d
t|| |d t|| d
t|| |d |g qqXdt	j
|t	jdiS )Nr   r   c                 s  s   | ]\}}t || V  qd S r   r   ).0ZcoordZdimr   r   r   	<genexpr>  s    z<RandomGravel.get_params_dependent_on_data.<locals>.<genexpr>r     r{   rN   rz   r      r  r   )zipr
  ranger  r   r   appendmaxminr   r   r  )r   r   r   heightwidthr  r  r  r  Z	roi_widthZ
roi_heightZgravels_info_Zpatch_widthZpatch_heightZpatch_xZpatch_yZnum_particlesxyrsatr   r   r   r     s6    
z)RandomGravel.get_params_dependent_on_datar  r   c                 C  s   dS )N)r
  r  r   r   r   r   r   r     s    z*RandomGravel.get_transform_init_args_names)r  r   Nr   )r   r   r   r   r9   r   r   r  r   r   r   r   r   r   r   r   ra     s   G    	*c                      s   e Zd ZdZG dd deZd%dddddddddddd fddZdddddddddZdddddd Zd!d"d#d$Z	  Z
S )&rb   a  Adds rain effects to an image.

    This transform simulates rainfall by overlaying semi-transparent streaks onto the image,
    creating a realistic rain effect. It can be used to augment datasets for computer vision
    tasks that need to perform well in rainy conditions.

    Args:
        slant_range (tuple[int, int]): Range for the rain slant angle in degrees.
            Negative values slant to the left, positive to the right. Default: (-10, 10).
        drop_length (int): Length of the rain drops in pixels. Default: 20.
        drop_width (int): Width of the rain drops in pixels. Default: 1.
        drop_color (tuple[int, int, int]): Color of the rain drops in RGB format. Default: (200, 200, 200).
        blur_value (int): Blur value for simulating rain effect. Rainy views are typically blurry. Default: 7.
        brightness_coefficient (float): Coefficient to adjust the brightness of the image.
            Rainy scenes are usually darker. Should be in the range (0, 1]. Default: 0.7.
        rain_type (Literal["drizzle", "heavy", "torrential", "default"]): Type of rain to simulate.
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        3

    Note:
        - The rain effect is created by drawing semi-transparent lines on the image.
        - The slant of the rain can be controlled to simulate wind effects.
        - Different rain types (drizzle, heavy, torrential) adjust the density and appearance of the rain.
        - The transform also adjusts image brightness and applies a blur to simulate the visual effects of rain.
        - This transform is particularly useful for:
          * Augmenting datasets for autonomous driving in rainy conditions
          * Testing the robustness of computer vision models to weather effects
          * Creating realistic rainy scenes for image editing or film production

    Mathematical Formulation:
        For each raindrop:
        1. Start position (x1, y1) is randomly generated within the image.
        2. End position (x2, y2) is calculated based on drop_length and slant:
           x2 = x1 + drop_length * sin(slant)
           y2 = y1 + drop_length * cos(slant)
        3. A line is drawn from (x1, y1) to (x2, y2) with the specified drop_color and drop_width.
        4. The image is then blurred and its brightness is adjusted.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Default usage
        >>> transform = A.RandomRain(p=1.0)
        >>> rainy_image = transform(image=image)["image"]

        # Custom rain parameters
        >>> transform = A.RandomRain(
        ...     slant_range=(-15, 15),
        ...     drop_length=30,
        ...     drop_width=2,
        ...     drop_color=(180, 180, 180),
        ...     blur_value=5,
        ...     brightness_coefficient=0.8,
        ...     p=1.0
        ... )
        >>> rainy_image = transform(image=image)["image"]

        # Simulating heavy rain
        >>> transform = A.RandomRain(rain_type="heavy", p=1.0)
        >>> heavy_rain_image = transform(image=image)["image"]

    References:
        - Rain visualization techniques: https://developer.nvidia.com/gpugems/gpugems3/part-iv-image-effects/chapter-27-real-time-rain-rendering
        - Weather effects in computer vision: https://www.sciencedirect.com/science/article/pii/S1077314220300692
    c                   @  s   e Zd ZU eddZded< eddZded< ded< edd	Zd
ed< edd	Zd
ed< ded< edd	Z	d
ed< edddZ
ded< ded< eddddddZdS )zRandomRain.InitSchemaN)defaultr   slant_lowerslant_upperz=Annotated[tuple[float, float], AfterValidator(nondecreasing)]slant_rangerN   r  r   drop_length
drop_widthtuple[int, int, int]
drop_color
blur_valuer   r   r   r   brightness_coefficientrG   	rain_typer   r   r"   r   c                 C  s   | j d k	s| jd k	r| j d k	r,tdtdd | jd k	rDtdtdd | j d k	rT| j n| jd }| jd k	rn| jn| jd }||f| _d | _ d | _t | jd   kr| jd   krtksn tdt dt d	| S )
NzX`slant_lower` deprecated. Use `slant_range` as tuple (slant_lower, slant_upper) instead.r   r   zX`slant_upper` deprecated. Use `slant_range` as tuple (slant_lower, slant_upper) instead.r   rN   z1slant_range values should be increasing within [-z, r   )r2  r3  r   r   r4  r>   r   r   r   r   r   r   s  s.    


.z%RandomRain.InitSchema.validate_ranges)r   r   r   r   r2  r   r3  r5  r6  r9  r;  r   r   r   r   r   r   r   h  s   
r   Nir  r|   rN      r?  r?     ffffff?r1  r   r   r   r   r7  r   rG   r   )r2  r3  r4  r5  r6  r8  r9  r;  r<  r   r   c                   s>   t  j||
d || _|| _|| _|| _|| _|| _|	| _d S r   )	r   r   r4  r5  r6  r8  r9  r;  r<  )r   r2  r3  r4  r5  r6  r8  r9  r;  r<  r   r   r   r   r   r     s    zRandomRain.__init__r   zlist[tuple[int, int]]r   )r   slantr5  
rain_dropsr   r   c              
   K  s(   t | t|||| j| j| j| j|S r   )r)   r   Zadd_rainr6  r8  r9  r;  )r   r   rB  r5  rC  r   r   r   r   r     s    zRandomRain.applyr   r   c                 C  s   t tj| j }|d d d \}}|| }| jdkrD|d }d}nB| jdkr`|| d }d}n&| jd	krx|d
 }d}n| j}|d }g }	t|D ]R}
|dk rt||ntdt|| d}tdt|| d}|		||f q|||	dS )Nr   r   Zdrizzlei  r  ZheavyiX     Z
torrentiali  <   r   )r5  rB  rC  )
r   r   r  r4  r<  r5  r&  r   r(  r'  )r   r   r   rB  r*  r+  r  Z	num_dropsr5  rC  r,  r-  r.  r   r   r   r     s(    


*z'RandomRain.get_params_dependent_on_datar   r   c                 C  s   dS )N)r4  r5  r6  r8  r9  r;  r<  r   r   r   r   r   r     s    z(RandomRain.get_transform_init_args_names)NNr=  r|   rN   r>  r@  rA  r1  Nr   r   r   r   r   r9   r   r   r   r   r   r   r   r   r   r   rb     s"   L)           (c                      sz   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dZddddddZddddZ	  Z
S )rc   a
  Simulates fog for the image by adding random fog-like artifacts.

    This transform creates a fog effect by generating semi-transparent overlays
    that mimic the visual characteristics of fog. The fog intensity and distribution
    can be controlled to create various fog-like conditions.

    Args:
        fog_coef_range (tuple[float, float]): Range for fog intensity coefficient. Should be in [0, 1] range.
        alpha_coef (float): Transparency of the fog circles. Should be in [0, 1] range. Default: 0.08.
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The fog effect is created by overlaying semi-transparent circles on the image.
        - Higher fog coefficient values result in denser fog effects.
        - The fog is typically denser in the center of the image and gradually decreases towards the edges.
        - This transform is useful for:
          * Simulating various weather conditions in outdoor scenes
          * Data augmentation for improving model robustness to foggy conditions
          * Creating atmospheric effects in image editing

    Mathematical Formulation:
        For each fog particle:
        1. A position (x, y) is randomly generated within the image.
        2. A circle with random radius is drawn at this position.
        3. The circle's alpha (transparency) is determined by the alpha_coef.
        4. These circles are overlaid on the original image to create the fog effect.

        The final pixel value is calculated as:
        output = (1 - alpha) * original_pixel + alpha * fog_color

        where alpha is influenced by the fog_coef and alpha_coef parameters.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Default usage
        >>> transform = A.RandomFog(p=1.0)
        >>> foggy_image = transform(image=image)["image"]

        # Custom fog intensity range
        >>> transform = A.RandomFog(fog_coef_lower=0.3, fog_coef_upper=0.8, p=1.0)
        >>> foggy_image = transform(image=image)["image"]

        # Adjust fog transparency
        >>> transform = A.RandomFog(fog_coef_lower=0.2, fog_coef_upper=0.5, alpha_coef=0.1, p=1.0)
        >>> foggy_image = transform(image=image)["image"]

    References:
        - Fog: https://en.wikipedia.org/wiki/Fog
        - Atmospheric perspective: https://en.wikipedia.org/wiki/Aerial_perspective
    c                   @  sj   e Zd ZU edddZded< edddZded< ded< edddZd	ed
< eddddddZ	dS )zRandomFog.InitSchemar   rN   r   r   fog_coef_lowerfog_coef_upperr   fog_coef_ranger   
alpha_coefr   r   r"   r   c                 C  s~   | j d k	rtdtdd | jd k	r0tdtdd | j d k	r@| j n| jd }| jd k	rZ| jn| jd }||f| _d | _ d | _| S )Nz=`fog_coef_lower` is deprecated, use `fog_coef_range` instead.r   r   z=`fog_coef_upper` is deprecated, use `fog_coef_range` instead.r   rN   )rG  r   r   rH  rI  r   r   r   r   validate_fog_coefficients1  s    


z.RandomFog.InitSchema.validate_fog_coefficientsN)
r   r   r   r   rG  r   rH  rJ  r   rK  r   r   r   r   r   $  s   
r   N{Gz?r  rN   r   r   r   r  r   )rG  rH  rJ  rI  r   r   c                   s    t  j||d || _|| _d S r   )r   r   rI  rJ  )r   rG  rH  rJ  rI  r   r   r   r   r   r   A  s    	zRandomFog.__init__r   znp.random.RandomStater   )r   particle_positions	intensityr   r   r   c                 K  s   t ||| j||S r   )r   Zadd_fogrJ  )r   r   rN  rO  r   r   r   r   r   r   N  s    zRandomFog.applyr   r   c                 C  s6  t j| j }|d d d }|\}}tdt|d | }g }dd t|D \}	}
|}|}d}d}d	}||kr&||kr&||k r&|| }t|||  | d }t|D ]J}t |	|d  |	|d  }t |
|d  |
|d  }|	||f qt|d|  }t|d|  }|d7 }qj||t
 d
S )Nr   r   rN   rz   c                 s  s   | ]}t |V  qd S r   r   )r!  r-  r   r   r   r"  f  s     z9RandomFog.get_params_dependent_on_data.<locals>.<genexpr>r  r  r   )rN  rO  r   )r   r  rI  r(  r   r   centerr&  r   r'  r$   r   )r   r   r   rO  r   Zimage_heightZimage_widthZfog_region_sizerN  Zcenter_xZcenter_yZcurrent_widthZcurrent_heightZshrink_factorZmax_iterations	iterationr  Zparticles_in_regionr,  r-  r.  r   r   r   r   X  s2    
z&RandomFog.get_params_dependent_on_datar  r   c                 C  s   dS )N)rI  rJ  r   r   r   r   r   r     s    z'RandomFog.get_transform_init_args_names)NNrL  rM  Nr   rF  r   r   r   r   rc     s   ?      
1c                      s   e Zd ZdZG dd deZd&ddddd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 )'rd   u  Simulates a sun flare effect on the image by adding circles of light.

    This transform creates a sun flare effect by overlaying multiple semi-transparent
    circles of varying sizes and intensities along a line originating from a "sun" point.
    It offers two methods: a simple overlay technique and a more complex physics-based approach.

    Args:
        flare_roi (tuple[float, float, float, float]): Region of interest where the sun flare
            can appear. Values are in the range [0, 1] and represent (x_min, y_min, x_max, y_max)
            in relative coordinates. Default: (0, 0, 1, 0.5).
        angle_range (tuple[float, float]): Range of angles (in radians) for the flare direction.
            Values should be in the range [0, 1], where 0 represents 0 radians and 1 represents 2π radians.
            Default: (0, 1).
        num_flare_circles_range (tuple[int, int]): Range for the number of flare circles to generate.
            Default: (6, 10).
        src_radius (int): Radius of the sun circle in pixels. Default: 400.
        src_color (tuple[int, int, int]): Color of the sun in RGB format. Default: (255, 255, 255).
        method (Literal["overlay", "physics_based"]): Method to use for generating the sun flare.
            "overlay" uses a simple alpha blending technique, while "physics_based" simulates
            more realistic optical phenomena. Default: "physics_based".

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        - overlay: Any
        - physics_based: RGB

    Note:
        The transform offers two methods for generating sun flares:

        1. Overlay Method ("overlay"):
           - Creates a simple sun flare effect using basic alpha blending.
           - Steps:
             a. Generate the main sun circle with a radial gradient.
             b. Create smaller flare circles along the flare line.
             c. Blend these elements with the original image using alpha compositing.
           - Characteristics:
             * Faster computation
             * Less realistic appearance
             * Suitable for basic augmentation or when performance is a priority

        2. Physics-based Method ("physics_based"):
           - Simulates more realistic optical phenomena observed in actual lens flares.
           - Steps:
             a. Create a separate flare layer for complex manipulations.
             b. Add the main sun circle and diffraction spikes to simulate light diffraction.
             c. Generate and add multiple flare circles with varying properties.
             d. Apply Gaussian blur to create a soft, glowing effect.
             e. Create and apply a radial gradient mask for natural fading from the center.
             f. Simulate chromatic aberration by applying different blurs to color channels.
             g. Blend the flare with the original image using screen blending mode.
           - Characteristics:
             * More computationally intensive
             * Produces more realistic and visually appealing results
             * Includes effects like diffraction spikes and chromatic aberration
             * Suitable for high-quality augmentation or realistic image synthesis

    Mathematical Formulation:
        For both methods:
        1. Sun position (x_s, y_s) is randomly chosen within the specified ROI.
        2. Flare angle θ is randomly chosen from the angle_range.
        3. For each flare circle i:
           - Position (x_i, y_i) = (x_s + t_i * cos(θ), y_s + t_i * sin(θ))
             where t_i is a random distance along the flare line.
           - Radius r_i is randomly chosen, with larger circles closer to the sun.
           - Alpha (transparency) alpha_i is randomly chosen in the range [0.05, 0.2].
           - Color (R_i, G_i, B_i) is randomly chosen close to src_color.

        Overlay method blending:
        new_pixel = (1 - alpha_i) * original_pixel + alpha_i * flare_color_i

        Physics-based method blending:
        new_pixel = 255 - ((255 - original_pixel) * (255 - flare_pixel) / 255)

        4. Each flare circle is blended with the image using alpha compositing:
           new_pixel = (1 - alpha_i) * original_pixel + alpha_i * flare_color_i

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [1000, 1000, 3], dtype=np.uint8)

        # Default sun flare (overlay method)
        >>> transform = A.RandomSunFlare(p=1.0)
        >>> flared_image = transform(image=image)["image"]

        # Physics-based sun flare with custom parameters

        # Default sun flare
        >>> transform = A.RandomSunFlare(p=1.0)
        >>> flared_image = transform(image=image)["image"]

        # Custom sun flare parameters

        >>> transform = A.RandomSunFlare(
        ...     flare_roi=(0.1, 0, 0.9, 0.3),
        ...     angle_range=(0.25, 0.75),
        ...     num_flare_circles_range=(5, 15),
        ...     src_radius=200,
        ...     src_color=(255, 200, 100),
        ...     method="physics_based",
        ...     p=1.0
        ... )
        >>> flared_image = transform(image=image)["image"]

    References:
        - Lens flare: https://en.wikipedia.org/wiki/Lens_flare
        - Alpha compositing: https://en.wikipedia.org/wiki/Alpha_compositing
        - Diffraction: https://en.wikipedia.org/wiki/Diffraction
        - Chromatic aberration: https://en.wikipedia.org/wiki/Chromatic_aberration
        - Screen blending: https://en.wikipedia.org/wiki/Blend_modes#Screen
    c                   @  s   e Zd ZU ded< edddZded< edddZded< 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ed< ded< ded< e
ddddddZdS )zRandomSunFlare.InitSchemar	  	flare_roir   rN   r   r   angle_lowerangle_upperr  r   num_flare_circles_lowerr   num_flare_circles_upperr   
src_radiustuple[int, ...]	src_colorr   angle_ranger   num_flare_circles_range%Literal[('overlay', 'physics_based')]r   r   r   r"   r   c                 C  sr  | j \}}}}d|  kr,|  k r,dkrPn n d|  krN|  k rNdks`n td| j  | jd k	st| jd k	r| jd k	rtdtdd | jd k	rtdtdd | jd k	r| jn| jd }| jd k	r| jn| jd }||f| _| jd k	s| jd k	rn| jd k	rtdtdd | jd k	r,td	tdd | jd k	r>| jn| j	d }| jd k	rZ| jn| j	d }||f| _	| S )
Nr   rN   zInvalid flare_roi. Got: zX`angle_lower` deprecated. Use `angle_range` as tuple (angle_lower, angle_upper) instead.r   r   zW`angle_upper` deprecated. Use `angle_range` as tuple(angle_lower, angle_upper) instead.z`num_flare_circles_lower` deprecated. Use `num_flare_circles_range` as tuple (num_flare_circles_lower, num_flare_circles_upper) instead.z`num_flare_circles_upper` deprecated. Use `num_flare_circles_range` as tuple (num_flare_circles_lower, num_flare_circles_upper) instead.)
rR  r   rS  rT  r   r   rZ  rU  rV  r[  )r   Zflare_center_lower_xZflare_center_lower_yZflare_center_upper_xZflare_center_upper_yr   r   r   r   r   validate_parameters  sn     
 





z-RandomSunFlare.InitSchema.validate_parametersN)r   r   r   r   r   rS  rT  rU  rV  rW  r   r]  r   r   r   r   r     s    
r   r   r   rN   r   N  r$  r$  r$  r   rN      r  overlayr   r	  r   r   r   rX  r  r   r\  r   r   )rR  rS  rT  rU  rV  rW  rY  rZ  r[  r   r   r   c                   s8   t  j||d || _|	| _|| _|| _|| _|
| _d S r   )r   r   rZ  r[  rW  rY  rR  r   )r   rR  rS  rT  rU  rV  rW  rY  rZ  r[  r   r   r   r   r   r   r   S  s    zRandomSunFlare.__init__r   r  r   )r   flare_centercirclesr   r   c                 K  s\   | j dkr t||| j| j|S | j dkrHt| t||| j| j|S td| j  d S )Nrd  Zphysics_basedzInvalid method: )r   r   Zadd_sun_flare_overlayrW  rY  r)   Zadd_sun_flare_physics_basedr   )r   r   re  rf  r   r   r   r   r   l  s$    

zRandomSunFlare.applyr   r   c                   s|  |d d d \}}t |d |d  }dt j tj| j   | j\}}}}	t|t|| t|t||	 tj| j	 }
t
dt|d }t
dt|d }tt
| jd ddd fd	d
t | |}fdd|D }g }t|
D ]l}tdd}t|}td|}fdd| jD }||t|d t|d ft|dt|f q |fdS )Nr   r   rN   {Gz?皙?r   r  )tr   c                   s$   | t    | t    fS r   )mathcossin)ri  )angleflare_center_xflare_center_yr   r   line  s    z9RandomSunFlare.get_params_dependent_on_data.<locals>.linec                   s   g | ]} |qS r   r   )r!  ri  )rp  r   r   
<listcomp>  s     z?RandomSunFlare.get_params_dependent_on_data.<locals>.<listcomp>皙?c                   s"   g | ]}t t|  d |qS r   )r   r   r(  )r!  c)color_ranger   r   rq    s     r   rz   )rf  re  )rj  sqrtpir   r  rZ  rR  r   r   r[  r(  rY  r&  choicer'  powtuple)r   r   r   r*  r+  Zdiagonalr  r  r  r  Znum_circlesZ	step_sizeZ
max_radiusZt_rangeZpointsrf  r,  alphaZpointZradcolorsr   )rm  ru  rn  ro  rp  r   r     s:    

z+RandomSunFlare.get_params_dependent_on_datar   c                 C  s   | j | j| j| j| jdS )NrR  rZ  r[  rW  rY  r}  r   r   r   r   r     s    z&RandomSunFlare.get_transform_init_args)r^  NNNNr_  r`  ra  rb  rd  Nr   )r   r   r   r   r9   r   r   r   r   r   r   r   r   r   r   rd     s$   wP            *0c                
      s|   e Zd ZdZG dd deZd#d
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 )$re   a  Simulates shadows for the image by reducing the brightness of the image in shadow regions.

    This transform adds realistic shadow effects to images, which can be useful for augmenting
    datasets for outdoor scene analysis, autonomous driving, or any computer vision task where
    shadows may be present.

    Args:
        shadow_roi (tuple[float, float, float, float]): Region of the image where shadows
            will appear (x_min, y_min, x_max, y_max). All values should be in range [0, 1].
            Default: (0, 0.5, 1, 1).
        num_shadows_limit (tuple[int, int]): Lower and upper limits for the possible number of shadows.
            Default: (1, 2).
        shadow_dimension (int): Number of edges in the shadow polygons. Default: 5.
        shadow_intensity_range (tuple[float, float]): Range for the shadow intensity.
            Should be two float values between 0 and 1. Default: (0.5, 0.5).
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - Shadows are created by generating random polygons within the specified ROI and
          reducing the brightness of the image in these areas.
        - The number of shadows, their shapes, and intensities can be randomized for variety.
        - This transform is particularly useful for:
          * Augmenting datasets for outdoor scene understanding
          * Improving robustness of object detection models to shadowed conditions
          * Simulating different lighting conditions in synthetic datasets

    Mathematical Formulation:
        For each shadow:
        1. A polygon with `shadow_dimension` vertices is generated within the shadow ROI.
        2. The shadow intensity a is randomly chosen from `shadow_intensity_range`.
        3. For each pixel (x, y) within the polygon:
           new_pixel_value = original_pixel_value * (1 - a)

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Default usage
        >>> transform = A.RandomShadow(p=1.0)
        >>> shadowed_image = transform(image=image)["image"]

        # Custom shadow parameters
        >>> transform = A.RandomShadow(
        ...     shadow_roi=(0.2, 0.2, 0.8, 0.8),
        ...     num_shadows_limit=(2, 4),
        ...     shadow_dimension=8,
        ...     shadow_intensity_range=(0.3, 0.7),
        ...     p=1.0
        ... )
        >>> shadowed_image = transform(image=image)["image"]

        # Combining with other transforms
        >>> transform = A.Compose([
        ...     A.RandomShadow(p=0.5),
        ...     A.RandomBrightnessContrast(p=0.5),
        ... ])
        >>> augmented_image = transform(image=image)["image"]

    References:
        - Shadow detection and removal: https://www.sciencedirect.com/science/article/pii/S1047320315002035
        - Shadows in computer vision: https://en.wikipedia.org/wiki/Shadow_detection
    c                   @  s`   e Zd ZU ded< ded< ded< ded< edd	Zd
ed< ded< eddddddZdS )zRandomShadow.InitSchemar	  
shadow_roir   num_shadows_limitr   num_shadows_lowernum_shadows_upperrN   r  r   shadow_dimensionr   shadow_intensity_ranger   r   r"   r   c                 C  s  | j d k	rtdtdd | jd k	r0tdtdd | j d k	sD| jd k	r| j d k	rT| j n| jd }| jd k	rn| jn| jd }||f| _d | _ d | _| j\}}}}d|  kr|  krdkrn n d|  kr|  krdksn td| j t| jt	r*d| j  krdksn td| j nZt| jt
r|d| jd   krh| jd   krhdksn td	| j ntd
| S )NzC`num_shadows_lower` is deprecated. Use `num_shadows_limit` instead.r   r   zC`num_shadows_upper` is deprecated. Use `num_shadows_limit` instead.r   rN   zInvalid shadow_roi. Got: zAshadow_intensity_range value should be within [0, 1] range. Got: zQshadow_intensity_range values should be within [0, 1] range and increasing. Got: z?shadow_intensity_range should be an float or a tuple of floats.)r  r   r   r  r  r~  r   
isinstancer  r   rz  	TypeError)r   r  r  Zshadow_lower_xZshadow_lower_yZshadow_upper_xZshadow_upper_yr   r   r   validate_shadows  sF    


B
2
z(RandomShadow.InitSchema.validate_shadowsN)r   r   r   r   r   r  r   r  r   r   r   r   r     s   
r   r   r   rN   rN   rN   r   Nr#  r   r   r   r	  r   r   r   r  r   r   )r~  r  r  r  r  r  r   r   c	           	        s,   t  j||d || _|| _|| _|| _d S r   )r   r   r~  r  r  r  )	r   r~  r  r  r  r  r  r   r   r   r   r   r   J  s
    zRandomShadow.__init__r   zlist[np.ndarray]r   )r   vertices_listintensitiesr   r   c                 K  s   t |||S r   )r   Z
add_shadow)r   r   r  r  r   r   r   r   r   \  s    zRandomShadow.applyr   zdict[str, list[np.ndarray]]r   c                   s   |d d d \}}t | jd | jd }| j\ t| t |  t| t|  fddt|D }tj| jd | jd |d}||dS )	Nr   r   r   rN   c              	     s6   g | ].}t jtj d dtjd dgddqS )r#  sizerN   Zaxis)r   stackr$   r   )r!  r,  r  r  r  r  r   r   rq  q  s   z=RandomShadow.get_params_dependent_on_data.<locals>.<listcomp>r  )r  r  )	r   r   r  r~  r   r&  r$   r  r  )r   r   r   r*  r+  Znum_shadowsr  r  r   r  r   r   e  s     z)RandomShadow.get_params_dependent_on_datar   r   c                 C  s   dS )N)r~  r  r  r   r   r   r   r   r     s    z*RandomShadow.get_transform_init_args_names)r  r  NNr#  r  Nr   rF  r   r   r   r   re     s   IA        "	 c                      st   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ddZddddZ	  Z
S )rf   u  Randomly change the relationship between bright and dark areas of the image by manipulating its tone curve.

    This transform applies a random S-curve to the image's tone curve, adjusting the brightness and contrast
    in a non-linear manner. It can be applied to the entire image or to each channel separately.

    Args:
        scale (float): Standard deviation of the normal distribution used to sample random distances
            to move two control points that modify the image's curve. Values should be in range [0, 1].
            Higher values will result in more dramatic changes to the image. Default: 0.1
        per_channel (bool): If True, the tone curve will be applied to each channel of the input image separately,
            which can lead to color distortion. If False, the same curve is applied to all channels,
            preserving the original color relationships. Default: False
        p (float): Probability of applying the transform. Default: 0.5

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - This transform modifies the image's histogram by applying a smooth, S-shaped curve to it.
        - The S-curve is defined by moving two control points of a quadratic Bézier curve.
        - When per_channel is False, the same curve is applied to all channels, maintaining color balance.
        - When per_channel is True, different curves are applied to each channel, which can create color shifts.
        - This transform can be used to adjust image contrast and brightness in a more natural way than linear
            transforms.
        - The effect can range from subtle contrast adjustments to more dramatic "vintage" or "faded" looks.

    Mathematical Formulation:
        1. Two control points are randomly moved from their default positions (0.25, 0.25) and (0.75, 0.75).
        2. The new positions are sampled from a normal distribution: N(μ, σ²), where μ is the original position
        and alpha is the scale parameter.
        3. These points, along with fixed points at (0, 0) and (1, 1), define a quadratic Bézier curve.
        4. The curve is applied as a lookup table to the image intensities:
           new_intensity = curve(original_intensity)

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)

        # Apply a random tone curve to all channels together
        >>> transform = A.RandomToneCurve(scale=0.1, per_channel=False, p=1.0)
        >>> augmented_image = transform(image=image)['image']

        # Apply random tone curves to each channel separately
        >>> transform = A.RandomToneCurve(scale=0.2, per_channel=True, p=1.0)
        >>> augmented_image = transform(image=image)['image']

    References:
        - "What Else Can Fool Deep Learning? Addressing Color Constancy Errors on Deep Neural Network Performance"
          by Mahmoud Afifi and Michael S. Brown, ICCV 2019.
        - Bézier curve: https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B%C3%A9zier_curves
        - Tone mapping: https://en.wikipedia.org/wiki/Tone_mapping
    c                   @  s*   e Zd ZU edddZded< ded< dS )	zRandomToneCurve.InitSchemar   rN   r   r   scaleboolper_channelN)r   r   r   r   r  r   r   r   r   r   r     s
   
r   r  FNr   r   r  r   )r  r  r   r   c                   s    t  j||d || _|| _d S r   )r   r   r  r  )r   r  r  r   r   r   r   r   r     s    zRandomToneCurve.__init__r   float | np.ndarrayr   )r   low_yhigh_yr   r   c                 K  s   t |||S r   )r   Zmove_tone_curve)r   r   r  r  r   r   r   r   r     s    zRandomToneCurve.applyr   r   c                 C  s   d|kr|d n
|d d }t |}| jrp|dkrpttjd| j|fdddttjd| j|fddddS ttjd| jd	dd}ttjd| jd	dd}||dS )
Nr   imagesr   rN         ?)locr  r  g      ?)r  r  )r  r  )r   r  r   r   r$   normalr  )r   r   r   r   num_channelsr  r  r   r   r   r     s    z,RandomToneCurve.get_params_dependent_on_datar   r   c                 C  s   dS )N)r  r  r   r   r   r   r   r     s    z-RandomToneCurve.get_transform_init_args_names)r  FNr   rF  r   r   r   r   rf     s   <	    	c                      st   e Zd ZdZG dd deZddddd	d
d fddZdddddddddZddddZddddZ	  Z
S )rS   a  Randomly change hue, saturation and value of the input image.

    This transform adjusts the HSV (Hue, Saturation, Value) channels of an input RGB image.
    It allows for independent control over each channel, providing a wide range of color
    and brightness modifications.

    Args:
        hue_shift_limit (float | tuple[float, float]): Range for changing hue.
            If a single float value is provided, the range will be (-hue_shift_limit, hue_shift_limit).
            Values should be in the range [-180, 180]. Default: (-20, 20).

        sat_shift_limit (float | tuple[float, float]): Range for changing saturation.
            If a single float value is provided, the range will be (-sat_shift_limit, sat_shift_limit).
            Values should be in the range [-255, 255]. Default: (-30, 30).

        val_shift_limit (float | tuple[float, float]): Range for changing value (brightness).
            If a single float value is provided, the range will be (-val_shift_limit, val_shift_limit).
            Values should be in the range [-255, 255]. Default: (-20, 20).

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        3

    Note:
        - The transform first converts the input RGB image to the HSV color space.
        - Each channel (Hue, Saturation, Value) is adjusted independently.
        - Hue is circular, so it wraps around at 180 degrees.
        - For float32 images, the shift values are applied as percentages of the full range.
        - This transform is particularly useful for color augmentation and simulating
          different lighting conditions.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.HueSaturationValue(
        ...     hue_shift_limit=20,
        ...     sat_shift_limit=30,
        ...     val_shift_limit=20,
        ...     p=0.7
        ... )
        >>> result = transform(image=image)
        >>> augmented_image = result["image"]

    References:
        - HSV color space: https://en.wikipedia.org/wiki/HSL_and_HSV
    c                   @  s&   e Zd ZU ded< ded< ded< dS )zHueSaturationValue.InitSchemar3   hue_shift_limitsat_shift_limitval_shift_limitNr   r   r   r   r   r   0  s   
r   ir|   irD  Nr   rH   r   r   )r  r  r  r   r   c                   sP   t  j||d ttttf || _ttttf || _ttttf || _d S r   )r   r   r   r	   r   r  r  r  )r   r  r  r  r   r   r   r   r   r   5  s    zHueSaturationValue.__init__r   r   r   )r   	hue_shift	sat_shift	val_shiftr   r   c                 K  s,   t |st|sd}t|t||||S )NzHHueSaturationValue transformation expects 1-channel or 3-channel images.)r   r   r  r   Z	shift_hsv)r   r   r  r  r  r   msgr   r   r   r   B  s    zHueSaturationValue.applydict[str, float]r   c                 C  s$   t j| j t j| j t j| j dS )N)r  r  r  )r   r  r  r  r  r   r   r   r   r   O  s    


zHueSaturationValue.get_paramsr   c                 C  s   dS )N)r  r  r  r   r   r   r   r   r   V  s    z0HueSaturationValue.get_transform_init_args_names)r  r  r  Nr   r  r   r   r   r   rS     s   7     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 )ri   a	  Invert all pixel values above a threshold.

    This transform applies a solarization effect to the input image. Solarization is a phenomenon in
    photography in which the image recorded on a negative or on a photographic print is wholly or
    partially reversed in tone. Dark areas appear light or light areas appear dark.

    In this implementation, all pixel values above a threshold are inverted.

    Args:
        threshold (float | tuple[float, float]): Range for solarizing threshold.
            If threshold is a single int, the range will be [threshold, threshold].
            If it's a tuple of (min, max), the range will be [min, max].
            The threshold should be in the range [0, 255] for uint8 images or [0, 1.0] for float images.
            Default: 128.
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Note:
        - For uint8 images, pixel values above the threshold are inverted as: 255 - pixel_value
        - For float32 images, pixel values above the threshold are inverted as: 1.0 - pixel_value
        - The threshold is applied to each channel independently
        - This transform can create interesting artistic effects or be used for data augmentation

    Raises:
        TypeError: If the input image data type is not supported.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>>
        # Solarize uint8 image with fixed threshold
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.Solarize(threshold=128, p=1.0)
        >>> solarized_image = transform(image=image)['image']
        >>>
        # Solarize uint8 image with random threshold
        >>> transform = A.Solarize(threshold=(100, 200), p=1.0)
        >>> solarized_image = transform(image=image)['image']
        >>>
        # Solarize float32 image
        >>> image = np.random.rand(100, 100, 3).astype(np.float32)
        >>> transform = A.Solarize(threshold=0.5, p=1.0)
        >>> solarized_image = transform(image=image)['image']

    Mathematical Formulation:
        For each pixel value p and threshold t:
        if p > t:
            p_new = max_value - p
        else:
            p_new = p

        Where max_value is 255 for uint8 images and 1.0 for float32 images.

    See Also:
        Invert: For inverting all pixel values regardless of a threshold.
    c                   @  s   e Zd ZU dZded< dS )zSolarize.InitSchema   r  r0   	thresholdN)r   r   r   r  r   r   r   r   r   r     s   
r   r  r   NrH   r   r   )r  r   r   c                   s(   t  j||d ttttf || _d S r   )r   r   r   r	   r   r  )r   r  r   r   r   r   r   r     s    zSolarize.__init__r   r   r   )r   r  r   r   c                 K  s   t ||S r   )r   Zsolarize)r   r   r  r   r   r   r   r     s    zSolarize.applyr  r   c                 C  s   dt j| j iS )Nr  )r   r  r  r   r   r   r   r     s    zSolarize.get_params
tuple[str]c                 C  s   dS )N)r  r   r   r   r   r   r     s    z&Solarize.get_transform_init_args_names)r  r   Nr  r   r   r   r   ri   Z  s   >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 )rk   a  Reduces the number of bits for each color channel in the image.

    This transform applies color posterization, a technique that reduces the number of distinct
    colors used in an image. It works by lowering the number of bits used to represent each
    color channel, effectively creating a "poster-like" effect with fewer color gradations.

    Args:
        num_bits (int | tuple[int, int] | list[int] | list[tuple[int, int]]):
            Defines the number of bits to keep for each color channel. Can be specified in several ways:
            - Single int: Same number of bits for all channels. Range: [0, 8].
            - Tuple of two ints: (min_bits, max_bits) to randomly choose from. Range for each: [0, 8].
            - List of three ints: Specific number of bits for each channel [r_bits, g_bits, b_bits].
            - List of three tuples: Ranges for each channel [(r_min, r_max), (g_min, g_max), (b_min, b_max)].
            Default: 4

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The effect becomes more pronounced as the number of bits is reduced.
        - Using 0 bits for a channel will reduce it to a single color (usually black).
        - Using 8 bits leaves the channel unchanged.
        - This transform can create interesting artistic effects or be used for image compression simulation.
        - Posterization is particularly useful for:
          * Creating stylized or retro-looking images
          * Reducing the color palette for specific artistic effects
          * Simulating the look of older or lower-quality digital images
          * Data augmentation in scenarios where color depth might vary

    Mathematical Background:
        For an 8-bit color channel, posterization to n bits can be expressed as:
        new_value = (old_value >> (8 - n)) << (8 - n)
        This operation keeps the n most significant bits and sets the rest to zero.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Posterize all channels to 3 bits
        >>> transform = A.Posterize(num_bits=3, p=1.0)
        >>> posterized_image = transform(image=image)["image"]

        # Randomly posterize between 2 and 5 bits
        >>> transform = A.Posterize(num_bits=(2, 5), p=1.0)
        >>> posterized_image = transform(image=image)["image"]

        # Different bits for each channel
        >>> transform = A.Posterize(num_bits=[3, 5, 2], p=1.0)
        >>> posterized_image = transform(image=image)["image"]

        # Range of bits for each channel
        >>> transform = A.Posterize(num_bits=[(1, 3), (3, 5), (2, 4)], p=1.0)
        >>> posterized_image = transform(image=image)["image"]

    References:
        - Color Quantization: https://en.wikipedia.org/wiki/Color_quantization
        - Posterization: https://en.wikipedia.org/wiki/Posterization
    c                   @  s2   e Zd ZU ded< ededddddZdS )	zPosterize.InitSchemazmAnnotated[int | tuple[int, int] | list[tuple[int, int]], Field(default=4, description='Number of high bits')]num_bitsr   z'tuple[int, int] | list[tuple[int, int]])r  r   c                 C  sP   t |trt||S t |tr8t|tkr8dd |D S ttttf t|dS )Nc                 S  s   g | ]}t |d qS rs  )rM   r!  ir   r   r   rq    s     z:Posterize.InitSchema.validate_num_bits.<locals>.<listcomp>r   )r  r   rM   r   lenNUM_BITS_ARRAY_LENGTHr   r	   )clsr  r   r   r   validate_num_bits  s
    

z&Posterize.InitSchema.validate_num_bitsN)r   r   r   r   r   classmethodr  r   r   r   r   r     s   
r      Nr   z-int | tuple[int, int] | list[tuple[int, int]]r   r   )r  r   r   c                   s<   t  j||d ttttdf tttdf  f || _d S )Nr   .)r   r   r   r
   r	   r   r   r  )r   r  r   r   r   r   r   r     s    zPosterize.__init__r   r   r   )r   r  r   r   c                 K  s   t ||S r   )r   Z	posterize)r   r   r  r   r   r   r   r     s    zPosterize.applyr   r   c                 C  sH   t | jtkr"ddd | jD iS | j}dtt|d t|d iS )Nr  c                 S  s(   g | ] }t t|d  t|d qS ra  )r   r   r   r  r   r   r   rq    s     z(Posterize.get_params.<locals>.<listcomp>r   rN   )r  r  r  r   r   r   )r   r  r   r   r   r   
  s    zPosterize.get_paramsr  c                 C  s   dS )N)r  r   r   r   r   r   r     s    z'Posterize.get_transform_init_args_names)r  Nr   r  r   r   r   r   rk     s   D   	c                      s   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ZddddddZe	ddddZ
ddd d!Z  ZS )#rj   a  Equalize the image histogram.

    This transform applies histogram equalization to the input image. Histogram equalization
    is a method in image processing of contrast adjustment using the image's histogram.

    Args:
        mode (Literal['cv', 'pil']): Use OpenCV or Pillow equalization method.
            Default: 'cv'
        by_channels (bool): If True, use equalization by channels separately,
            else convert image to YCbCr representation and use equalization by `Y` channel.
            Default: True
        mask (np.ndarray, callable): If given, only the pixels selected by
            the mask are included in the analysis. Can be:
            - A 1-channel or 3-channel numpy array of the same size as the input image.
            - A callable (function) that generates a mask. The function should accept 'image'
              as its first argument, and can accept additional arguments specified in mask_params.
            Default: None
        mask_params (list[str]): Additional parameters to pass to the mask function.
            These parameters will be taken from the data dict passed to __call__.
            Default: ()
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Note:
        - When mode='cv', OpenCV's equalizeHist() function is used.
        - When mode='pil', Pillow's equalize() function is used.
        - The 'by_channels' parameter determines whether equalization is applied to each color channel
          independently (True) or to the luminance channel only (False).
        - If a mask is provided as a numpy array, it should have the same height and width as the input image.
        - If a mask is provided as a function, it allows for dynamic mask generation based on the input image
          and additional parameters. This is useful for scenarios where the mask depends on the image content
          or external data (e.g., bounding boxes, segmentation masks).

    Mask Function:
        When mask is a callable, it should have the following signature:
        mask_func(image, *args) -> np.ndarray

        - image: The input image (numpy array)
        - *args: Additional arguments as specified in mask_params

        The function should return a numpy array of the same height and width as the input image,
        where non-zero pixels indicate areas to be equalized.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>>
        >>> # Using a static mask
        >>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
        >>> transform = A.Equalize(mask=mask, p=1.0)
        >>> result = transform(image=image)
        >>>
        >>> # Using a dynamic mask function
        >>> def mask_func(image, bboxes):
        ...     mask = np.ones_like(image[:, :, 0], dtype=np.uint8)
        ...     for bbox in bboxes:
        ...         x1, y1, x2, y2 = map(int, bbox)
        ...         mask[y1:y2, x1:x2] = 0  # Exclude areas inside bounding boxes
        ...     return mask
        >>>
        >>> transform = A.Equalize(mask=mask_func, mask_params=['bboxes'], p=1.0)
        >>> bboxes = [(10, 10, 50, 50), (60, 60, 90, 90)]  # Example bounding boxes
        >>> result = transform(image=image, bboxes=bboxes)

    References:
        - OpenCV equalizeHist: https://docs.opencv.org/3.4/d6/dc7/group__imgproc__hist.html#ga7e54091f0c937d49bf84152a16f76d6e
        - Pillow ImageOps.equalize: https://pillow.readthedocs.io/en/stable/reference/ImageOps.html#PIL.ImageOps.equalize
        - Histogram Equalization: https://en.wikipedia.org/wiki/Histogram_equalization
    c                   @  s.   e Zd ZU ded< ded< ded< ded< d	S )
zEqualize.InitSchemarD   r   r  by_channels&np.ndarray | Callable[..., Any] | Noner   Sequence[str]mask_paramsNr   r   r   r   r   r   a  s   
r   cvTNr   r   rD   r  r  r  r   r   )r   r  r   r  r   r   c                   s,   t  j||d || _|| _|| _|| _d S r   )r   r   r   r  r   r  )r   r   r  r   r  r   r   r   r   r   r   g  s
    	zEqualize.__init__r   r   )r   r   r   r   c                 K  s   t j|| j| j|dS )N)r   r  r   )r   equalizer   r  )r   r   r   r   r   r   r   r   w  s    zEqualize.applyr   r   c                 C  s`   t | jsd| jiS d|d i}| jD ](}||krBtd| d|| ||< q&d| jf |iS )Nr   r   zRequired parameter 'z'' for mask function is missing in data.)callabler   r  KeyError)r   r   r   r  keyr   r   r   r   z  s    


z%Equalize.get_params_dependent_on_dataz	list[str]r   c                 C  s   dt | jS )Nr   )r   )listr  r   r   r   r   targets_as_params  s    zEqualize.targets_as_paramsr   c                 C  s   dS )N)r   r  r   r  r   r   r   r   r   r     s    z&Equalize.get_transform_init_args_names)r  TNr   Nr   )r   r   r   r   r9   r   r   r   r   r   r  r   r   r   r   r   r   rj     s   L      c                      sp   e Zd ZdZG dd deZ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 )rT   aT  Randomly shift values for each channel of the input RGB image.

    Args:
        r_shift_limit ((int, int) or int): range for changing values for the red channel. If r_shift_limit is a
            single int, the range will be (-r_shift_limit, r_shift_limit). Default: (-20, 20).
        g_shift_limit ((int, int) or int): range for changing values for the green channel. If g_shift_limit is a
            single int, the range will be (-g_shift_limit, g_shift_limit). Default: (-20, 20).
        b_shift_limit ((int, int) or int): range for changing values for the blue channel. If b_shift_limit is a
            single int, the range will be (-b_shift_limit, b_shift_limit). Default: (-20, 20).
        p (float): probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Note:
        - For uint8 images, the shift values represent absolute pixel values in the range [0, 255].
          For example, a shift of 20 for a uint8 image would add 20 to the corresponding channel.
        - For float32 images, the shift values represent fractions of the full value range [0, 1].
          For example, a shift of 0.1 for a float32 image would add 0.1 to the corresponding channel.
        - The shift values are applied independently to each channel.
        - After applying the shift, values are clipped to the valid range for the image dtype:
          [0, 255] for uint8 and [0, 1] for float32.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>>
        # Shift RGB channels for uint8 image
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.RGBShift(r_shift_limit=30, g_shift_limit=30, b_shift_limit=30, p=1.0)
        >>> shifted_image = transform(image=image)['image']
        >>>
        # Shift RGB channels for float32 image
        >>> image = np.random.rand(100, 100, 3).astype(np.float32)
        >>> transform = A.RGBShift(r_shift_limit=0.1, g_shift_limit=0.1, b_shift_limit=0.1, p=1.0)
        >>> shifted_image = transform(image=image)['image']

    c                   @  s&   e Zd ZU ded< ded< ded< dS )zRGBShift.InitSchemar3   r_shift_limitg_shift_limitb_shift_limitNr   r   r   r   r   r     s   
r   r  Nr   rH   r   r   )r  r  r  r   r   c                   sP   t  j||d ttttf || _ttttf || _ttttf || _d S r   )r   r   r   r	   r   r  r  r  )r   r  r  r  r   r   r   r   r   r     s    zRGBShift.__init__r   r   )r   shiftr   r   c                 K  s   t | t||S r   )r)   albucoreZ
add_vector)r   r   r  r   r   r   r   r     s    zRGBShift.applyr   r   c                 C  s,   dt tj| j tj| j tj| j giS )Nr  )r   r   r   r  r  r  r  r   r   r   r   r     s     


zRGBShift.get_paramsr   c                 C  s   dS )N)r  r  r  r   r   r   r   r   r     s    z&RGBShift.get_transform_init_args_names)r  r  r  Nr   r  r   r   r   r   rT     s   *     c                      sr   e Zd ZdZG dd deZd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_   u  Randomly changes the brightness and contrast of the input image.

    This transform adjusts the brightness and contrast of an image simultaneously, allowing for
    a wide range of lighting and contrast variations. It's particularly useful for data augmentation
    in computer vision tasks, helping models become more robust to different lighting conditions.

    Args:
        brightness_limit (float | tuple[float, float]): Factor range for changing brightness.
            If a single float value is provided, the range will be (-brightness_limit, brightness_limit).
            Values should typically be in the range [-1.0, 1.0], where 0 means no change,
            1.0 means maximum brightness, and -1.0 means minimum brightness.
            Default: (-0.2, 0.2).

        contrast_limit (float | tuple[float, float]): Factor range for changing contrast.
            If a single float value is provided, the range will be (-contrast_limit, contrast_limit).
            Values should typically be in the range [-1.0, 1.0], where 0 means no change,
            1.0 means maximum increase in contrast, and -1.0 means maximum decrease in contrast.
            Default: (-0.2, 0.2).

        brightness_by_max (bool): If True, adjusts brightness by scaling pixel values up to the
            maximum value of the image's dtype. If False, uses the mean pixel value for adjustment.
            Default: True.

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The order of operation is: contrast adjustment, then brightness adjustment.
        - For uint8 images, the output is clipped to [0, 255] range.
        - For float32 images, the output may exceed the [0, 1] range.
        - The `brightness_by_max` parameter affects how brightness is adjusted:
          * If True, brightness adjustment is more pronounced and can lead to more saturated results.
          * If False, brightness adjustment is more subtle and preserves the overall lighting better.
        - This transform is useful for:
          * Simulating different lighting conditions
          * Enhancing low-light or overexposed images
          * Data augmentation to improve model robustness

    Mathematical Formulation:
        Let a be the contrast adjustment factor and β be the brightness adjustment factor.
        For each pixel value x:
        1. Contrast adjustment: x' = clip((x - mean) * (1 + a) + mean)
        2. Brightness adjustment:
           If brightness_by_max is True:  x'' = clip(x' * (1 + β))
           If brightness_by_max is False: x'' = clip(x' + β * max_value)
        Where clip() ensures values stay within the valid range for the image dtype.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Default usage
        >>> transform = A.RandomBrightnessContrast(p=1.0)
        >>> augmented_image = transform(image=image)["image"]

        # Custom brightness and contrast limits
        >>> transform = A.RandomBrightnessContrast(
        ...     brightness_limit=0.3,
        ...     contrast_limit=0.3,
        ...     p=1.0
        ... )
        >>> augmented_image = transform(image=image)["image"]

        # Adjust brightness based on mean value
        >>> transform = A.RandomBrightnessContrast(
        ...     brightness_limit=0.2,
        ...     contrast_limit=0.2,
        ...     brightness_by_max=False,
        ...     p=1.0
        ... )
        >>> augmented_image = transform(image=image)["image"]

    References:
        - Brightness: https://en.wikipedia.org/wiki/Brightness
        - Contrast: https://en.wikipedia.org/wiki/Contrast_(vision)
    c                   @  s&   e Zd ZU ded< ded< ded< dS )z#RandomBrightnessContrast.InitSchemar3   brightness_limitcontrast_limitr  brightness_by_maxNr   r   r   r   r   r   5	  s   
r   gɿrh  TNr   rH   r  r   r   )r  r  r  r   r   c                   sB   t  j||d ttttf || _ttttf || _|| _d S r   )r   r   r   r	   r   r  r  r  )r   r  r  r  r   r   r   r   r   r   :	  s    z!RandomBrightnessContrast.__init__r   r   )r   r{  betar   r   c                 K  s   t |||| jS r   )r   Zbrightness_contrast_adjustr  )r   r   r{  r  r   r   r   r   r   G	  s    zRandomBrightnessContrast.applyr  r   c                 C  s"   dt j| j  dt j| j  dS )Nr           )r{  r  )r   r  r  r  r   r   r   r   r   J	  s    z#RandomBrightnessContrast.get_paramstuple[str, str, str]c                 C  s   dS )N)r  r  r  r   r   r   r   r   r   P	  s    z6RandomBrightnessContrast.get_transform_init_args_names)r  r  TNr   r  r   r   r   r   r_     s   V     c                      sv   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ZddddddZddddZ	  Z
S ) rU   a	  Apply Gaussian noise to the input image.

    Args:
        var_limit (tuple[float, float] | float): Variance range for noise. If var_limit is a single float value,
            the range will be (0, var_limit). Default: (10.0, 50.0).
        mean (float): Mean of the noise. Default: 0.
        per_channel (bool): If True, noise will be sampled for each channel independently.
            Otherwise, the noise will be sampled once for all channels. Default: True.
        noise_scale_factor (float): Scaling factor for noise generation. Value should be in the range (0, 1].
            When set to 1, noise is sampled for each pixel independently. If less, noise is sampled for a smaller size
            and resized to fit the shape of the image. Smaller values make the transform faster. Default: 1.0.
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Returns:
        numpy.ndarray: Image with applied Gaussian noise.

    Note:
        - The noise is generated in the same range as the input image.
        - For uint8 input images, the noise is generated in the range [0, 255].
        - For float32 input images, the noise is generated in the range [0, 1].
        - The resulting image is clipped to keep its values in the input range.
        - Setting per_channel=False is faster but applies the same noise to all channels.
        - The noise_scale_factor parameter allows for a trade-off between transform speed and noise granularity.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (224, 224, 3), dtype=np.uint8)
        >>>
        >>> # Apply Gaussian noise with default parameters
        >>> transform = A.GaussNoise(p=1.0)
        >>> noisy_image = transform(image=image)['image']
        >>>
        >>> # Apply Gaussian noise with custom variance range and mean
        >>> transform = A.GaussNoise(var_limit=(50.0, 100.0), mean=10, p=1.0)
        >>> noisy_image = transform(image=image)['image']
        >>>
        >>> # Apply the same noise to all channels
        >>> transform = A.GaussNoise(per_channel=False, p=1.0)
        >>> noisy_image = transform(image=image)['image']
        >>>
        >>> # Apply noise with reduced granularity for faster processing
        >>> transform = A.GaussNoise(noise_scale_factor=0.5, p=1.0)
        >>> noisy_image = transform(image=image)['image']

    c                   @  s:   e Zd ZU ded< ded< ded< eddd	Zded
< dS )zGaussNoise.InitSchemar/   	var_limitr   r   r  r  r   rN   r:  noise_scale_factorN)r   r   r   r   r   r  r   r   r   r   r   	  s   
r   g      $@g      I@r   TrN   Nr   rH   r   r  r   )r  r   r  r  r   r   c                   s:   t  j||d ttttf || _|| _|| _|| _d S r   )	r   r   r   r	   r   r  r   r  r  )r   r  r   r  r  r   r   r   r   r   r   	  s
    	zGaussNoise.__init__r   r   )r   gaussr   r   c                 K  s   t ||S r   )r   Z	add_noise)r   r   r  r   r   r   r   r   	  s    zGaussNoise.applyr   r  r   c                 C  s   d|kr|d n
|d d }t j| j }t|}| jrp|j}| jdkrZt	| j
||}qt|| j
|| j}nT|jd d }| jdkrt	| j
||}nt|| j
|| j}|jtkrt|d}d|iS )Nr   r  r   rN   r   r  )r   r  r  rj  rv  r  r   r  r$   r  r   r   Zgenerate_approx_gaussian_noisendimr?   r   expand_dims)r   r   r   r   varsigmaZtarget_shaper  r   r   r   r   	  s    



z'GaussNoise.get_params_dependent_on_datar   r   c                 C  s   dS )N)r  r  r   r  r   r   r   r   r   r   	  s    z(GaussNoise.get_transform_init_args_names)r  r   TrN   Nr   rF  r   r   r   r   rU   T	  s   8      c                      sv   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dZddddddZddddZ	  Z
S )rh   u8  Applies camera sensor noise to the input image, simulating high ISO settings.

    This transform adds random noise to an image, mimicking the effect of using high ISO settings
    in digital photography. It simulates two main components of ISO noise:
    1. Color noise: random shifts in color hue
    2. Luminance noise: random variations in pixel intensity

    Args:
        color_shift (tuple[float, float]): Range for changing color hue.
            Values should be in the range [0, 1], where 1 represents a full 360° hue rotation.
            Default: (0.01, 0.05)

        intensity (tuple[float, float]): Range for the noise intensity.
            Higher values increase the strength of both color and luminance noise.
            Default: (0.1, 0.5)

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        3

    Note:
        - This transform only works with RGB images. It will raise a TypeError if applied to
          non-RGB images.
        - The color shift is applied in the HSV color space, affecting the hue channel.
        - Luminance noise is added to all channels independently.
        - This transform can be useful for data augmentation in low-light scenarios or when
          training models to be robust against noisy inputs.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.ISONoise(color_shift=(0.01, 0.05), intensity=(0.1, 0.5), p=0.5)
        >>> result = transform(image=image)
        >>> noisy_image = result["image"]

    References:
        - ISO noise in digital photography:
          https://en.wikipedia.org/wiki/Image_noise#In_digital_cameras
    c                   @  s   e Zd ZU ded< ded< dS )zISONoise.InitSchemar   color_shiftZAnnotated[tuple[float, float], AfterValidator(check_0plus), AfterValidator(nondecreasing)]rO  Nr   r   r   r   r   r   	  s   
r   rg  rr  r  r   Nr   r  r   r   )r  rO  r   r   c                   s    t  j||d || _|| _d S r   )r   r   rO  r  )r   r  rO  r   r   r   r   r   r   	  s    zISONoise.__init__r   r   r   )r   r  rO  random_seedr   r   c                 K  s    t | t|||tj|S r   )r)   r   Z	iso_noiser   r   ZRandomState)r   r   r  rO  r  r   r   r   r   r    
  s    zISONoise.applyr   r   c                 C  s    t j| j t j| j t dS )N)r  rO  r  )r   r  r  rO  r$   Zget_random_seed)r   r   r   r   r   r   r   
  s    

z%ISONoise.get_params_dependent_on_datar  r   c                 C  s   dS )N)rO  r  r   r   r   r   r   r   
  s    z&ISONoise.get_transform_init_args_names)r  r  Nr   rF  r   r   r   r   rh   	  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 )rV   a	  Apply Contrast Limited Adaptive Histogram Equalization (CLAHE) to the input image.

    CLAHE is an advanced method of improving the contrast in an image. Unlike regular histogram
    equalization, which operates on the entire image, CLAHE operates on small regions (tiles)
    in the image. This results in a more balanced equalization, preventing over-amplification
    of contrast in areas with initially low contrast.

    Args:
        clip_limit (tuple[float, float] | float): Controls the contrast enhancement limit.
            - If a single float is provided, the range will be (1, clip_limit).
            - If a tuple of two floats is provided, it defines the range for random selection.
            Higher values allow for more contrast enhancement, but may also increase noise.
            Default: (1, 4)

        tile_grid_size (tuple[int, int]): Defines the number of tiles in the row and column directions.
            Format is (rows, columns). Smaller tile sizes can lead to more localized enhancements,
            while larger sizes give results closer to global histogram equalization.
            Default: (8, 8)

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

    Notes:
        - Supports only RGB or grayscale images.
        - For color images, CLAHE is applied to the L channel in the LAB color space.
        - The clip limit determines the maximum slope of the cumulative histogram. A lower
          clip limit will result in more contrast limiting.
        - Tile grid size affects the adaptiveness of the method. More tiles increase local
          adaptiveness but can lead to an unnatural look if set too high.

    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.CLAHE(clip_limit=(1, 4), tile_grid_size=(8, 8), p=1.0)
        >>> result = transform(image=image)
        >>> clahe_image = result["image"]

    References:
        - https://docs.opencv.org/master/d5/daf/tutorial_py_histogram_equalization.html
        - Zuiderveld, Karel. "Contrast Limited Adaptive Histogram Equalization."
          Graphic Gems IV. Academic Press Professional, Inc., 1994.
    c                   @  s   e Zd ZU ded< ded< dS )zCLAHE.InitSchemar0   
clip_limitr}   tile_grid_sizeNr   r   r   r   r   r   H
  s   
r         @   r  Nr   rH   r   r   r   )r  r  r   r   c                   s.   t  j||d ttttf || _|| _d S r   )r   r   r   r	   r   r  r  )r   r  r  r   r   r   r   r   r   L
  s    zCLAHE.__init__r   r   )r   r  r   r   c                 K  s,   t |st|sd}t|t||| jS )Nz;CLAHE transformation expects 1-channel or 3-channel images.)r   r   r  r   Zclaher  )r   r   r  r   r  r   r   r   r   W
  s    zCLAHE.applyr  r   c                 C  s   dt j| j iS )Nr  )r   r  r  r   r   r   r   r   ^
  s    zCLAHE.get_paramsr  c                 C  s   dS )N)r  r  r   r   r   r   r   r   a
  s    z#CLAHE.get_transform_init_args_names)r  r  Nr   r  r   r   r   r   rV   
  s   1    c                   @  sD   e Zd ZdZdddddddZdddd	d
dZddddZdS )rW   zRandomly rearrange channels of the image.

    Args:
        p: probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    r   rX  r   )r   channels_shuffledr   r   c                 K  s   t ||S r   )r   Zchannel_shuffle)r   r   r  r   r   r   r   r   s
  s    zChannelShuffle.applyr   r   c                 C  s&   t t|d d }t|}d|iS )Nr   r   r  )r  r&  r$   shuffle)r   r   r   Zch_arrr   r   r   r   v
  s    
z+ChannelShuffle.get_params_dependent_on_data	tuple[()]r   c                 C  s   dS Nr   r   r   r   r   r   r   {
  s    z,ChannelShuffle.get_transform_init_args_namesN)r   r   r   r   r   r   r   r   r   r   r   rW   e
  s   c                   @  s0   e Zd ZdZddddddZddd	d
ZdS )rX   a>  Invert the input image by subtracting pixel values from max values of the image types,
    i.e., 255 for uint8 and 1.0 for float32.

    Args:
        p: probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    r   r   r   c                 K  s
   t |S r   )r   invertr   r   r   r   r   
  s    zInvertImg.applyr  r   c                 C  s   dS r  r   r   r   r   r   r   
  s    z'InvertImg.get_transform_init_args_namesN)r   r   r   r   r   r   r   r   r   r   rX   
  s   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 )rQ   a  Applies random gamma correction to the input image.

    Gamma correction, or simply gamma, is a nonlinear operation used to encode and decode luminance
    or tristimulus values in imaging systems. This transform can adjust the brightness of an image
    while preserving the relative differences between darker and lighter areas, making it useful
    for simulating different lighting conditions or correcting for display characteristics.

    Args:
        gamma_limit (float | tuple[float, float]): If gamma_limit is a single float value, the range
            will be (1, gamma_limit). If it's a tuple of two floats, they will serve as
            the lower and upper bounds for gamma adjustment. Values are in terms of percentage change,
            e.g., (80, 120) means the gamma will be between 80% and 120% of the original.
            Default: (80, 120).
        eps: A small value added to the gamma to avoid division by zero or log of zero errors.
            Default: 1e-7.
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The gamma correction is applied using the formula: output = input^gamma
        - Gamma values > 1 will make the image darker, while values < 1 will make it brighter
        - This transform is particularly useful for:
          * Simulating different lighting conditions
          * Correcting for non-linear display characteristics
          * Enhancing contrast in certain regions of the image
          * Data augmentation in computer vision tasks

    Mathematical Formulation:
        Let I be the input image and G (gamma) be the correction factor.
        The gamma correction is applied as follows:
        1. Normalize the image to [0, 1] range: I_norm = I / 255 (for uint8 images)
        2. Apply gamma correction: I_corrected = I_norm ^ (1 / G)
        3. Scale back to original range: output = I_corrected * 255 (for uint8 images)

        The actual gamma value used is calculated as:
        G = 1 + (random_value / 100), where random_value is sampled from gamma_limit range.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Default usage
        >>> transform = A.RandomGamma(p=1.0)
        >>> augmented_image = transform(image=image)["image"]

        # Custom gamma range
        >>> transform = A.RandomGamma(gamma_limit=(50, 150), p=1.0)
        >>> augmented_image = transform(image=image)["image"]

        # Applying with other transforms
        >>> transform = A.Compose([
        ...     A.RandomGamma(gamma_limit=(80, 120), p=0.5),
        ...     A.RandomBrightnessContrast(p=0.5),
        ... ])
        >>> augmented_image = transform(image=image)["image"]

    References:
        - Gamma correction: https://en.wikipedia.org/wiki/Gamma_correction
        - Power law (Gamma) encoding: https://www.cambridgeincolour.com/tutorials/gamma-correction.htm
    c                   @  s   e Zd ZU ded< dS )zRandomGamma.InitSchemar0   gamma_limitNr   r   r   r   r   r   
  s   
r   P   x   Nr   rH   r   r   )r  r   r   c                   s&   t  || ttttf || _d S r   )r   r   r   r	   r   r  )r   r  r   r   r   r   r   r   
  s    zRandomGamma.__init__r   r   )r   gammar   r   c                 K  s   t j||dS )N)r  )r   Zgamma_transform)r   r   r  r   r   r   r   r   
  s    zRandomGamma.applyr  r   c                 C  s    dt | jd | jd d iS )Nr  r   rN   g      Y@)r   r  r  r   r   r   r   r   
  s    zRandomGamma.get_paramsr   c                 C  s   dS )N)r  r   r   r   r   r   r   
  s    z)RandomGamma.get_transform_init_args_names)r  Nr   r  r   r   r   r   rQ   
  s   F   	c                      s^   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ZddddZ  Z	S )rY   a
  Convert an image to grayscale and optionally replicate the grayscale channel.

    This transform first converts a color image to a single-channel grayscale image using various methods,
    then replicates the grayscale channel if num_output_channels is greater than 1.

    Args:
        num_output_channels (int): The number of channels in the output image. If greater than 1,
            the grayscale channel will be replicated. Default: 3.
        method (Literal["weighted_average", "from_lab", "desaturation", "average", "max", "pca"]):
            The method used for grayscale conversion:
            - "weighted_average": Uses a weighted sum of RGB channels (0.299R + 0.587G + 0.114B).
              Works only with 3-channel images. Provides realistic results based on human perception.
            - "from_lab": Extracts the L channel from the LAB color space.
              Works only with 3-channel images. Gives perceptually uniform results.
            - "desaturation": Averages the maximum and minimum values across channels.
              Works with any number of channels. Fast but may not preserve perceived brightness well.
            - "average": Simple average of all channels.
              Works with any number of channels. Fast but may not give realistic results.
            - "max": Takes the maximum value across all channels.
              Works with any number of channels. Tends to produce brighter results.
            - "pca": Applies Principal Component Analysis to reduce channels.
              Works with any number of channels. Can preserve more information but is computationally intensive.
        p (float): Probability of applying the transform. Default: 0.5.

    Raises:
        TypeError: If the input image doesn't have 3 channels for methods that require it.

    Note:
        - The transform first converts the input image to single-channel grayscale, then replicates
          this channel if num_output_channels > 1.
        - "weighted_average" and "from_lab" are typically used in image processing and computer vision
          applications where accurate representation of human perception is important.
        - "desaturation" and "average" are often used in simple image manipulation tools or when
          computational speed is a priority.
        - "max" method can be useful in scenarios where preserving bright features is important,
          such as in some medical imaging applications.
        - "pca" might be used in advanced image analysis tasks or when dealing with hyperspectral images.

    Image types:
        uint8, float32

    Returns:
        np.ndarray: Grayscale image with the specified number of channels.
    c                   @  s,   e Zd ZU eddddZded< ded< d	S )
zToGray.InitSchemarz   zThe number of output channels.rN   )r1  descriptionr   r   num_output_channelsRLiteral[('weighted_average', 'from_lab', 'desaturation', 'average', 'max', 'pca')]r   Nr   r   r   r   r  r   r   r   r   r   r   #  s   
r   rz   weighted_averageNr   r   r  r   r   )r  r   r   r   c                   s    t  j||d || _|| _d S r   )r   r   r  r   )r   r  r   r   r   r   r   r   r   '  s    zToGray.__init__r   r   r   c                 K  sR   t |rtjddd |S t|}|tkr@| jdkr@d}t|t|| j	| jS )NzThe image is already gray.r   r   >   pcadesaturationaverager(  z/ToGray transformation expects 3-channel images.)
r   warningsr   r   r@   r   r  r   Zto_grayr  )r   r   r   r  r  r   r   r   r   2  s    zToGray.applyr   r   c                 C  s   dS )N)r  r   r   r   r   r   r   r   ?  s    z$ToGray.get_transform_init_args_names)rz   r  Nr   r   r   r   r   r   rY   
  s   -    c                      s\   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ZddddZ  Z	S )rZ   aK  Convert an input image from grayscale to RGB format.

    Args:
        num_output_channels (int): The number of channels in the output image. Default: 3.
        p (float): Probability of applying the transform. Default: 1.0.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        1

    Note:
        - For single-channel (grayscale) images, the channel is replicated to create an RGB image.
        - If the input is already a 3-channel RGB image, it is returned unchanged.
        - This transform does not change the data type of the image (e.g., uint8 remains uint8).

    Raises:
        TypeError: If the input image has more than 1 channel.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>>
        >>> # Convert a grayscale image to RGB
        >>> transform = A.Compose([A.ToRGB(p=1.0)])
        >>> grayscale_image = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
        >>> rgb_image = transform(image=grayscale_image)['image']
        >>> assert rgb_image.shape == (100, 100, 3)
    c                   @  s    e Zd ZU eddZded< dS )zToRGB.InitSchemarN   r  r   r  Nr  r   r   r   r   r   f  s   
r   rz   r   Nr   r   r   )r  r   r   c                   s   t  j||d || _d S r   )r   r   r  )r   r  r   r   r   r   r   r   i  s    zToRGB.__init__r   r   r   c                 K  sD   t |r tjddd t|S t|s4d}t|tj|| j	dS )NzThe image is already an RGB.r   r   zVToRGB transformation expects 2-dim images or 3-dim with the last dimension equal to 1.r  )
r   r  r   r   Zascontiguousarrayr   r  r   Zgrayscale_to_multichannelr  )r   r   r   r  r   r   r   r   n  s    
zToRGB.applyr  r   c                 C  s   dS )Nr  r   r   r   r   r   r   x  s    z#ToRGB.get_transform_init_args_names)rz   r   Nr   r   r   r   r   rZ   C  s
   "
c                      sJ   e Zd ZdZdddd fddZd	d
d	dddZddddZ  ZS )r[   a  Apply a sepia filter to the input image.

    This transform converts a color image to a sepia tone, giving it a warm, brownish tint
    that is reminiscent of old photographs. The sepia effect is achieved by applying a
    specific color transformation matrix to the RGB channels of the input image.

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        3

    Note:
        - This transform only works with RGB images (3 channels).
        - The sepia effect is created using a fixed color transformation matrix:
          [[0.393, 0.769, 0.189],
           [0.349, 0.686, 0.168],
           [0.272, 0.534, 0.131]]
        - The output image will have the same data type as the input image.
        - For float32 images, ensure the input values are in the range [0, 1].

    Raises:
        TypeError: If the input image is not a 3-channel RGB image.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>>
        # Apply sepia effect to a uint8 image
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.ToSepia(p=1.0)
        >>> sepia_image = transform(image=image)['image']
        >>> assert sepia_image.shape == image.shape
        >>> assert sepia_image.dtype == np.uint8
        >>>
        # Apply sepia effect to a float32 image
        >>> image = np.random.rand(100, 100, 3).astype(np.float32)
        >>> transform = A.ToSepia(p=1.0)
        >>> sepia_image = transform(image=image)['image']
        >>> assert sepia_image.shape == image.shape
        >>> assert sepia_image.dtype == np.float32
        >>> assert 0 <= sepia_image.min() <= sepia_image.max() <= 1.0

    Mathematical Formulation:
        Given an input pixel [R, G, B], the sepia tone is calculated as:
        R_sepia = 0.393*R + 0.769*G + 0.189*B
        G_sepia = 0.349*R + 0.686*G + 0.168*B
        B_sepia = 0.272*R + 0.534*G + 0.131*B

        The output values are then clipped to the valid range for the image's data type.

    See Also:
        ToGray: For converting images to grayscale instead of sepia.
    r   Nr   r   r   c                   s6   t  || tdddgdddgddd	gg| _d S )
Ngx&?gS㥛?gx&1?gtV?gʡE?g/$?g rh?gJ+?gS㥛?)r   r   r   r   sepia_transformation_matrix)r   r   r   r   r   r   r     s    zToSepia.__init__r   r   r   c                 K  s   t | t|| jS r   )r)   r   Zlinear_transformation_rgbr  r   r   r   r   r     s    zToSepia.applyr  r   c                 C  s   dS r  r   r   r   r   r   r     s    z%ToSepia.get_transform_init_args_names)r   N)r   r   r   r   r   r   r   r   r   r   r   r   r[   |  s   =c                      s\   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ZddddZ  Z	S )r]   aS	  Convert the input image to a floating-point representation.

    This transform divides pixel values by `max_value` to get a float32 output array
    where all values lie in the range [0, 1.0]. It's useful for normalizing image data
    before feeding it into neural networks or other algorithms that expect float input.

    Args:
        max_value (float | None): The maximum possible input value. If None, the transform
            will try to infer the maximum value by inspecting the data type of the input image:
            - uint8: 255
            - uint16: 65535
            - uint32: 4294967295
            - float32: 1.0
            Default: None.
        p (float): Probability of applying the transform. Default: 1.0.

    Targets:
        image

    Image types:
        uint8, uint16, uint32, float32

    Returns:
        np.ndarray: Image in floating point representation, with values in range [0, 1.0].

    Note:
        - If the input image is already float32 with values in [0, 1], it will be returned unchanged.
        - For integer types (uint8, uint16, uint32), the function will scale the values to [0, 1] range.
        - The output will always be float32, regardless of the input type.
        - This transform is often used as a preprocessing step before applying other transformations
          or feeding the image into a neural network.

    Raises:
        TypeError: If the input image data type is not supported.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>>
        # Convert uint8 image to float
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.ToFloat(max_value=None)
        >>> float_image = transform(image=image)['image']
        >>> assert float_image.dtype == np.float32
        >>> assert 0 <= float_image.min() <= float_image.max() <= 1.0
        >>>
        # Convert uint16 image to float with custom max_value
        >>> image = np.random.randint(0, 4096, (100, 100, 3), dtype=np.uint16)
        >>> transform = A.ToFloat(max_value=4095)
        >>> float_image = transform(image=image)['image']
        >>> assert float_image.dtype == np.float32
        >>> assert 0 <= float_image.min() <= float_image.max() <= 1.0

    See Also:
        FromFloat: The inverse operation, converting from float back to the original data type.
    c                   @  s   e Zd ZU ded< dS )zToFloat.InitSchemar   	max_valueNr   r   r   r   r   r     s   
r   Nr   r   r   r   )r  r   r   c                   s   t  || || _d S r   )r   r   r  )r   r  r   r   r   r   r   r     s    zToFloat.__init__r   r   r   c                 K  s   t || jS r   )r   r  r   r   r   r   r   	  s    zToFloat.applyr  r   c                 C  s   dS )N)r  r   r   r   r   r   r     s    z%ToFloat.get_transform_init_args_names)Nr   Nr   r   r   r   r   r]     s
   9c                      s^   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ZddddZ  Z	S )r^   aB  Convert an image from floating point representation to the specified data type.

    This transform is designed to convert images from a normalized floating-point representation
    (typically with values in the range [0, 1]) to other data types, scaling the values appropriately.

    Args:
        dtype (str): The desired output data type. Supported types include 'uint8', 'uint16',
                     'uint32'. Default: 'uint8'.
        max_value (float | None): The maximum value for the output dtype. If None, the transform
                                  will attempt to infer the maximum value based on the dtype.
                                  Default: None.
        p (float): Probability of applying the transform. Default: 1.0.

    Targets:
        image

    Image types:
        float32, float64

    Note:
        - This is the inverse transform for ToFloat.
        - Input images are expected to be in floating point format with values in the range [0, 1].
        - For integer output types (uint8, uint16, uint32), the function will scale the values
          to the appropriate range (e.g., 0-255 for uint8).
        - For float output types (float32, float64), the values will remain in the [0, 1] range.
        - The transform uses the `from_float` function internally, which ensures output values
          are within the valid range for the specified dtype.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> transform = A.FromFloat(dtype='uint8', max_value=None, p=1.0)
        >>> image = np.random.rand(100, 100, 3).astype(np.float32)  # Float image in [0, 1] range
        >>> result = transform(image=image)
        >>> uint8_image = result['image']
        >>> assert uint8_image.dtype == np.uint8
        >>> assert uint8_image.min() >= 0 and uint8_image.max() <= 255

    c                   @  s   e Zd ZU ded< ded< dS )zFromFloat.InitSchema2Literal[('uint8', 'uint16', 'float32', 'float64')]r   r   r  Nr   r   r   r   r   r   9  s   
r   uint8Nr   r  r   r   r   )r   r  r   r   c                   s&   t  j||d t|| _|| _d S r   )r   r   r   r   r  )r   r   r  r   r   r   r   r   r   =  s    zFromFloat.__init__r   r   r   c                 K  s   t || j| jS r   )r   r   r  r   r   r   r   r   H  s    zFromFloat.applyr   r   c                 C  s   | j j| jdS )N)r   r  )r   namer  r   r   r   r   r   K  s    z!FromFloat.get_transform_init_args)r  NNr   )
r   r   r   r   r9   r   r   r   r   r   r   r   r   r   r^     s   (    c                   @  s   e Zd ZU ded< ded< dS )InterpolationDictr   upscale	downscaleNr   r   r   r   r   r  O  s   
r  c                   @  s   e Zd ZU ded< ded< dS )InterpolationPydanticr.   r  r  Nr   r   r   r   r   r  T  s   
r  c                	      s   e Zd ZdZG dd deZddddeejejdddf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 )rl   a	  Decrease image quality by downscaling and upscaling back.

    This transform simulates the effect of a low-resolution image by first downscaling
    the image to a lower resolution and then upscaling it back to its original size.
    This process introduces loss of detail and can be used to simulate low-quality
    images or to test the robustness of models to different image resolutions.

    Args:
        scale_range (tuple[float, float]): Range for the downscaling factor.
            Should be two float values between 0 and 1, where the first value is less than or equal to the second.
            The actual downscaling factor will be randomly chosen from this range for each image.
            Lower values result in more aggressive downscaling.
            Default: (0.25, 0.25)

        interpolation_pair (InterpolationDict): A dictionary specifying the interpolation methods to use for
            downscaling and upscaling. Should contain two keys:
            - 'downscale': Interpolation method for downscaling
            - 'upscale': Interpolation method for upscaling
            Values should be OpenCV interpolation flags (e.g., cv2.INTER_NEAREST, cv2.INTER_LINEAR, etc.)
            Default: {'downscale': cv2.INTER_NEAREST, 'upscale': cv2.INTER_NEAREST}

        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 actual downscaling factor is randomly chosen for each image from the range
          specified in scale_range.
        - Using different interpolation methods for downscaling and upscaling can produce
          various effects. For example, using INTER_NEAREST for both can create a pixelated look,
          while using INTER_LINEAR or INTER_CUBIC can produce smoother results.
        - This transform can be useful for data augmentation, especially when training models
          that need to be robust to variations in image quality or resolution.

    Example:
        >>> import albumentations as A
        >>> import cv2
        >>> transform = A.Downscale(
        ...     scale_range=(0.5, 0.75),
        ...     interpolation_pair={'downscale': cv2.INTER_NEAREST, 'upscale': cv2.INTER_LINEAR},
        ...     p=0.5
        ... )
        >>> transformed = transform(image=image)
        >>> downscaled_image = transformed['image']
    c                   @  s\   e Zd ZU ded< ded< edd dZded< d	ed
< ded< eddddddZdS )zDownscale.InitSchemar   	scale_min	scale_maxc                   C  s   t tjtjdS )N)r  r  )r<   cv2INTER_NEARESTr   r   r   r   <lambda>      zDownscale.InitSchema.<lambda>)default_factory.int | Interpolation | InterpolationDict | Noneinterpolationr  interpolation_pairr   scale_ranger   r   r"   r   c                 C  s   | j d k	r<| jd k	r<tdtdd | j | jf| _d | _ d | _| jd k	rtdtdd t| jtrptf | j| _	nBt| jt
rt| j| jd| _	n"t| jtrt| jj| jjd| _	d | _| S )Nz@scale_min and scale_max are deprecated. Use scale_range instead.r   r   zPDownscale.interpolation is deprecated. Use Downscale.interpolation_pair instead.r  r  )r  r  r   r   r  r  r  dictr  r  r   r<   r  r  r   r   r   r   validate_params  s:    

z$Downscale.InitSchema.validate_paramsN)r   r   r   r   r   r  r   r  r   r   r   r   r     s   
r   N)r  r  r  r   r   r  r  r  r   r   )r  r  r  r  r  r   r   c                   s    t  j||d || _|| _d S r   )r   r   r  r  )r   r  r  r  r  r  r   r   r   r   r   r     s    zDownscale.__init__r   r   )r   r  r   r   c                 K  s   t j||| jd | jd dS )Nr  r  )r  Zdown_interpolationZup_interpolation)r   r  r  )r   r   r  r   r   r   r   r     s    zDownscale.applyr   r   c                 C  s   dt j| j iS )Nr  )r   r  r  r   r   r   r   r     s    zDownscale.get_paramsr  c                 C  s   dS )N)r  r  r   r   r   r   r   r     s    z'Downscale.get_transform_init_args_names)r   r   r   r   r9   r   r  r  r  r   r   r   r   r   r   r   r   r   rl   Y  s   31 c                	      s   e Zd ZdZd#dddddddd fd	d
ZddddddZddddddZddddddZddddddZe	ddddZ
ddddZd dd!d"Z  ZS )$rg   a`  A flexible transformation class for using user-defined transformation functions per targets.
    Function signature must include **kwargs to accept optional arguments like interpolation method, image size, etc:

    Args:
        image: Image transformation function.
        mask: Mask transformation function.
        keypoint: Keypoint transformation function.
        bbox: BBox transformation function.
        p: probability of applying the transform. Default: 1.0.

    Targets:
        image, mask, bboxes, keypoints

    Image types:
        uint8, float32

    Number of channels:
        Any

    Nr   zCallable[..., Any] | Nonez
str | Noner   r   )r   r   r   bboxesr  r   r   c           
        sz   t  j||d || _dd dD | _||||d D ]<\}}	|	d k	r8t|	trj|	jdkrjtj	ddd	 |	| j|< q8d S )
Nr   c                 S  s   i | ]}|t jqS r   )r   Znoop)r!  target_namer   r   r   
<dictcomp>  s     z#Lambda.__init__.<locals>.<dictcomp>)r   r   r   r  Zglobal_label)r   r   r   r  z<lambda>zaUsing lambda is incompatible with multiprocessing. Consider using regular functions or partial().r   r   )
r   r   r  custom_apply_fnsitemsr  r   r   r  r   )
r   r   r   r   r  r  r   r   r	  Zcustom_apply_fnr   r   r   r     s"    
zLambda.__init__r   r   r   c                 K  s   | j d }||f|S )Nr   r  )r   r   r   fnr   r   r   r     s    
zLambda.apply)r   r   r   c                 K  s   | j d }||f|S )Nr   r  )r   r   r   r  r   r   r   r     s    
zLambda.apply_to_mask)r  r   r   c                 K  sJ   d}t |tjs$d}tj|tjd}| jd }||f|}|sF| S |S )NTFr   r  r  r   Zndarrayr   r   r  tolist)r   r  r   
is_ndarrayr  resultr   r   r   apply_to_bboxes  s    
zLambda.apply_to_bboxes)r   r   r   c                 K  sJ   d}t |tjs$d}tj|tjd}| jd }||f|}|sF| S |S )NTFr   r   r  )r   r   r   r  r  r  r   r   r   r   (  s    
zLambda.apply_to_keypointsr  r   c                 C  s   dS )NFr   )r  r   r   r   is_serializable6  s    zLambda.is_serializabler   c                 C  s&   | j d krd}t||  | j dS )NzTo make a Lambda transform serializable you should provide the `name` argument, e.g. `Lambda(name='my_transform', image=<some func>, ...)`.)Z__class_fullname__r   )r  r   Zget_class_fullnamer   r  r   r   r   to_dict_private:  s
    
zLambda.to_dict_privatestrc                 C  s@   d| j i}|| j  ||   | jj dt| dS )Nr  ())r  updater  r  Zget_base_init_argsr   r   rL   )r   stater   r   r   __repr__C  s    
zLambda.__repr__)NNNNNNr   )r   r   r   r   r   r   r   r  r   r  r  r  r  r   r   r   r   r   rg     s"            	c                      st   e Zd ZdZG dd deZddd	d	d
dd fddZdddddddZddddddZddddZ	  Z
S )rm   aU  Apply multiplicative noise to the input image.

    This transform multiplies each pixel in the image by a random value or array of values,
    effectively creating a noise pattern that scales with the image intensity.

    Args:
        multiplier (tuple[float, float]): The range for the random multiplier.
            Defines the range from which the multiplier is sampled.
            Default: (0.9, 1.1)

        per_channel (bool): If True, use a different random multiplier for each channel.
            If False, use the same multiplier for all channels.
            Setting this to False is slightly faster.
            Default: False

        elementwise (bool): If True, generates a unique multiplier for each pixel.
            If False, generates a single multiplier (or one per channel if per_channel=True).
            Default: False

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - When elementwise=False and per_channel=False, a single multiplier is applied to the entire image.
        - When elementwise=False and per_channel=True, each channel gets a different multiplier.
        - When elementwise=True and per_channel=False, each pixel gets the same multiplier across all channels.
        - When elementwise=True and per_channel=True, each pixel in each channel gets a unique multiplier.
        - Setting per_channel=False is slightly faster, especially for larger images.
        - This transform can be used to simulate various lighting conditions or to create noise that
          scales with image intensity.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.MultiplicativeNoise(multiplier=(0.9, 1.1), per_channel=True, p=1.0)
        >>> result = transform(image=image)
        >>> noisy_image = result["image"]

    References:
        - Multiplicative noise: https://en.wikipedia.org/wiki/Multiplicative_noise
    c                   @  s&   e Zd ZU ded< ded< ded< dS )zMultiplicativeNoise.InitSchemar  
multiplierr  r  elementwiseNr   r   r   r   r   r   ~  s   
r   r  g?FNr   rH   r  r   r   )r  r  r  r   r   c                   s4   t  j||d ttttf || _|| _|| _d S r   )r   r   r   r	   r   r  r  r  )r   r  r  r  r   r   r   r   r   r     s    zMultiplicativeNoise.__init__r   r  r   )r   r  kwargsr   c                 K  s
   t ||S r   )r   )r   r   r  r   r   r   r   r     s    zMultiplicativeNoise.applyr   r   c                 C  s   d|kr|d n
|d d }t |}| jrJ| jr6|jn|jd d d
}n| jrV|fnd}t| jd | jd |tj	}| js|dkrtj
||dd}| js| jr|ddd}|j|jkr| }d	|iS )Nr   r  r   r   rN   )rN   r  r  r  )rN   )r   r  r  r   r$   r  r  astyper   r   repeatZreshapesqueeze)r   r   r   r   r  r   r  r   r   r   r     s     "z0MultiplicativeNoise.get_params_dependent_on_datar  r   c                 C  s   dS )N)r  r  r  r   r   r   r   r   r     s    z1MultiplicativeNoise.get_transform_init_args_names)r  FFNr   rF  r   r   r   r   rm   J  s   3     c                      sp   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ddZddddZ	  Z
S )rn   ar  Apply Fancy PCA augmentation to the input image.

    This augmentation technique applies PCA (Principal Component Analysis) to the image's color channels,
    then adds multiples of the principal components to the image, with magnitudes proportional to the
    corresponding eigenvalues times a random variable drawn from a Gaussian with mean 0 and standard
    deviation 'alpha'.

    Args:
        alpha (tuple[float, float] | float): Standard deviation of the Gaussian distribution used to generate
            random noise for each principal component. If a single float is provided, it will be used for
            all channels. If a tuple of two floats (min, max) is provided, the standard deviation will be
            uniformly sampled from this range for each run. Default: 0.1.
        always_apply (bool): If True, the transform will always be applied. Default: False.
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        any

    Note:
        - This augmentation is particularly effective for RGB images but can work with any number of channels.
        - For grayscale images, it applies a simplified version of the augmentation.
        - The transform preserves the mean of the image while adjusting the color/intensity variation.
        - This implementation is based on the paper by Krizhevsky et al. and is similar to the one used
          in the original AlexNet paper.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.FancyPCA(alpha=0.1, p=1.0)
        >>> result = transform(image=image)
        >>> augmented_image = result["image"]

    References:
        - Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). ImageNet classification with deep
          convolutional neural networks. In Advances in neural information processing systems (pp. 1097-1105).
        - https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf

    c                   @  s    e Zd ZU eddZded< dS )zFancyPCA.InitSchemar   r  r   r{  N)r   r   r   r   r{  r   r   r   r   r   r     s   
r   r  r   Nr   r   )r{  r   r   c                   s   t  j||d || _d S r   )r   r   r{  )r   r{  r   r   r   r   r   r     s    zFancyPCA.__init__r   r   )r   alpha_vectorr   r   c                 K  s   t ||S r   )r   Z	fancy_pca)r   r   r$  r   r   r   r   r     s    zFancyPCA.applyr   r   c                 C  s@   |d }t |tkr|d nd}td| j|tj}d|iS )Nr   r  rN   r   r$  )r  r   r$   r  r{  r!  r   r   )r   r   r   r   r  r$  r   r   r   r     s    z%FancyPCA.get_params_dependent_on_datar  r   c                 C  s   dS )N)r{  r   r   r   r   r   r     s    z&FancyPCA.get_transform_init_args_names)r  r   NrF  r   r   r   r   rn     s   .c                	      sz   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Zdd
d
d
d
ddddddZddddZ	  Z
S )ro   a  Randomly changes the brightness, contrast, saturation, and hue of an image.

    This transform is similar to torchvision's ColorJitter but with some differences due to the use of OpenCV
    instead of Pillow. The main differences are:
    1. OpenCV and Pillow use different formulas to convert images to HSV format.
    2. This implementation uses value saturation instead of uint8 overflow as in Pillow.

    These differences may result in slightly different output compared to torchvision's ColorJitter.

    Args:
        brightness (tuple[float, float] | float): How much to jitter brightness.
            If float:
                The brightness factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness].
            If tuple:
                The brightness factor is sampled from the range specified.
            Should be non-negative numbers.
            Default: (0.8, 1.2)

        contrast (tuple[float, float] | float): How much to jitter contrast.
            If float:
                The contrast factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast].
            If tuple:
                The contrast factor is sampled from the range specified.
            Should be non-negative numbers.
            Default: (0.8, 1.2)

        saturation (tuple[float, float] | float): How much to jitter saturation.
            If float:
                The saturation factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation].
            If tuple:
                The saturation factor is sampled from the range specified.
            Should be non-negative numbers.
            Default: (0.8, 1.2)

        hue (float or tuple of float (min, max)): How much to jitter hue.
            If float:
                The hue factor is chosen uniformly from [-hue, hue]. Should have 0 <= hue <= 0.5.
            If tuple:
                The hue factor is sampled from the range specified. Values should be in range [-0.5, 0.5].
            Default: (-0.5, 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 order of application for these color transformations is random for each image.
        - The ranges for brightness, contrast, and saturation are applied as multiplicative factors.
        - The range for hue is applied as an additive factor.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1, p=1.0)
        >>> result = transform(image=image)
        >>> jittered_image = result['image']

    References:
        - https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.ColorJitter
        - https://docs.opencv.org/3.4/de/d25/imgproc_color_conversions.html
    c                   @  sR   e Zd ZU ded< ded< ded< ded< eddddeddddd	d
ZdS )zColorJitter.InitSchemarH   
brightnesscontrast
saturationhuer   r  valueinfor   c                 C  s   |j dkrd}d}d}n|j dkr6dtdf}d}d}t|tjr|dk r\td	|j  d
|| }|rrt|d}||| f}n*t|trt|t	krt
|f||j f  ttttf |S )Nr(  g      r   r   F)r%  r&  r'  infrN   TzIf z- is a single number, it must be non negative.)
field_namer   r  numbersNumberr   r(  rz  r  rA   r(   r   r	   )r  r*  r+  boundsZbiasr   leftr   r   r   check_rangesC  s$    


z#ColorJitter.InitSchema.check_rangesN)r   r   r   r   r   r  r3  r   r   r   r   r   =  s   
r   g?333333?r,  Nr   rH   r   r   )r%  r&  r'  r(  r   r   c                   sz   t  j||d ttttf || _ttttf || _ttttf || _ttttf || _t	j
t	jt	jt	jg| _d S r   )r   r   r   r	   r   r%  r&  r'  r(  r   Zadjust_brightness_torchvisionZadjust_contrast_torchvisionZadjust_saturation_torchvisionZadjust_hue_torchvision
transforms)r   r%  r&  r'  r(  r   r   r   r   r   r   [  s    	zColorJitter.__init__r   r   c                 C  sV   t j| j }t j| j }t j| j }t j| j }ddddg}t|}|||||dS )Nr   rN   r   rz   )r%  r&  r'  r(  order)r   r  r%  r&  r'  r(  r$   r  )r   r%  r&  r'  r(  r7  r   r   r   r   r  s    
zColorJitter.get_paramsr   r   r   )r   r%  r&  r'  r(  r7  r   r   c                 K  sJ   t |st|sd}t|||||g}	|D ]}
| j|
 ||	|
 }q,|S )NzAColorJitter transformation expects 1-channel or 3-channel images.)r   r   r  r6  )r   r   r%  r&  r'  r(  r7  r   r  Zcolor_transformsr  r   r   r   r     s    
zColorJitter.applytuple[str, str, str, str]c                 C  s   dS )N)r%  r&  r'  r(  r   r   r   r   r   r     s    z)ColorJitter.get_transform_init_args_names)r4  r4  r4  r,  Nr   r   r   r   r   r9   r   r   r   r   r   r   r   r   r   r   ro     s   E       c                      s   e Zd ZdZG dd deZdddd	d
d fddZeddddddZddddZ	dddddddZ
ddddZ  ZS )rp   am  Sharpen the input image and overlays the result with the original image.

    This transform applies a sharpening filter to the input image and then blends
    the sharpened image with the original using a specified alpha value.

    Args:
        alpha (tuple[float, float]): Range to choose the visibility of the sharpened image.
            At 0, only the original image is visible, at 1.0 only its sharpened version is visible.
            Values should be in the range [0, 1].
            Default: (0.2, 0.5).

        lightness (tuple of float): Range to choose the lightness of the sharpened image.
            Larger values will create images with higher contrast.
            Values should be greater than 0.
            Default: (0.5, 1.0).

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The sharpening effect is achieved using a 3x3 sharpening kernel.
        - The kernel is dynamically generated based on the 'alpha' and 'lightness' parameters.
        - Higher 'alpha' values will result in a more pronounced sharpening effect.
        - Higher 'lightness' values will increase the contrast of the sharpened areas.
        - This transform can be useful for:
          * Enhancing edge details in images
          * Improving the perceived quality of slightly blurred images
          * Creating a more crisp appearance in photographs

    Mathematical Formulation:
        The sharpening kernel K is defined as:

        K = (1 - alpha) * I + alpha * L

        where:
        - alpha is the alpha value (from the 'alpha' parameter)
        - I is the identity kernel [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
        - L is the Laplacian kernel [[-1, -1, -1], [-1, 8+l, -1], [-1, -1, -1]]
          (l is the lightness value from the 'lightness' parameter)

        The sharpened image S is obtained by convolving the input image I with the kernel K:

        S = I * K

        The final output O is a blend of the original and sharpened images:

        O = (1 - alpha) * I + alpha * S

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Apply sharpening with default parameters
        >>> transform = A.Sharpen(p=1.0)
        >>> sharpened_image = transform(image=image)['image']

        # Apply sharpening with custom parameters
        >>> transform = A.Sharpen(alpha=(0.4, 0.7), lightness=(0.8, 1.2), p=1.0)
        >>> sharpened_image = transform(image=image)['image']

    References:
        - Image sharpening: https://en.wikipedia.org/wiki/Unsharp_masking
        - Laplacian operator: https://en.wikipedia.org/wiki/Laplace_operator
        - "Digital Image Processing" by Rafael C. Gonzalez and Richard E. Woods, 4th Edition
    c                   @  s   e Zd ZU ded< ded< dS )zSharpen.InitSchema8Annotated[tuple[float, float], AfterValidator(check_01)]r{  ;Annotated[tuple[float, float], AfterValidator(check_0plus)]	lightnessNr   r   r   r   r   r     s   
r   rh  r   r   r   Nr   r  r   r   )r{  r<  r   r   c                   s    t  j||d || _|| _d S r   )r   r   r{  r<  )r   r{  r<  r   r   r   r   r   r     s    zSharpen.__init__r   )alpha_samplelightness_sampler   c                 C  sh   t jdddgdddgdddggt jd}t jdddgdd| dgdddggt jd}d|  | | |  S )Nr   rN   r   r  r  r   r   r   )r?  r@  matrix_nochangematrix_effectr   r   r   Z__generate_sharpening_matrix  s    (z$Sharpen.__generate_sharpening_matrixr   r   c                 C  s.   t j| j }t j| j }| j||d}d|iS )N)r?  r@  sharpening_matrix)r   r  r{  r<  $_Sharpen__generate_sharpening_matrix)r   r{  r<  rD  r   r   r   r     s    zSharpen.get_paramsr   )r   rD  r   r   c                 K  s   t ||S r   r   convolve)r   r   rD  r   r   r   r   r     s    zSharpen.applyr  c                 C  s   dS )N)r{  r<  r   r   r   r   r   r     s    z%Sharpen.get_transform_init_args_names)r=  r>  Nr   )r   r   r   r   r9   r   r   staticmethodrE  r   r   r   r   r   r   r   r   rp     s   K    	c                      s   e Zd ZdZG dd deZdddd	d
d fddZeddddddZddddZ	dddddddZ
ddddZ  ZS )rq   a  Apply embossing effect to the input image.

    This transform creates an emboss effect by highlighting edges and creating a 3D-like texture
    in the image. It works by applying a specific convolution kernel to the image that emphasizes
    differences in adjacent pixel values.

    Args:
        alpha (tuple[float, float]): Range to choose the visibility of the embossed image.
            At 0, only the original image is visible, at 1.0 only its embossed version is visible.
            Values should be in the range [0, 1].
            Alpha will be randomly selected from this range for each image.
            Default: (0.2, 0.5)

        strength (tuple[float, float]): Range to choose the strength of the embossing effect.
            Higher values create a more pronounced 3D effect.
            Values should be non-negative.
            Strength will be randomly selected from this range for each image.
            Default: (0.2, 0.7)

        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 emboss effect is created using a 3x3 convolution kernel.
        - The 'alpha' parameter controls the blend between the original image and the embossed version.
          A higher alpha value will result in a more pronounced emboss effect.
        - The 'strength' parameter affects the intensity of the embossing. Higher strength values
          will create more contrast in the embossed areas, resulting in a stronger 3D-like effect.
        - This transform can be useful for creating artistic effects or for data augmentation
          in tasks where edge information is important.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> transform = A.Emboss(alpha=(0.2, 0.5), strength=(0.2, 0.7), p=0.5)
        >>> result = transform(image=image)
        >>> embossed_image = result['image']

    References:
        - https://en.wikipedia.org/wiki/Image_embossing
        - https://www.researchgate.net/publication/303412455_Application_of_Emboss_Filtering_in_Image_Processing
    c                   @  s   e Zd ZU ded< ded< dS )zEmboss.InitSchemar:  r{  r;  strengthNr   r   r   r   r   r   >  s   
r   r=  rh  rA  Nr   r  r   r   )r{  rI  r   r   c                   s    t  j||d || _|| _d S r   )r   r   r{  rI  )r   r{  rI  r   r   r   r   r   r   B  s    zEmboss.__init__r   )r?  strength_sampler   c                 C  s|   t jdddgdddgdddggt jd}t jd| d| dgd| dd| gdd| d| ggt jd}d|  | | |  S )Nr   rN   r   r  rA  )r?  rK  rB  rC  r   r   r   Z__generate_emboss_matrixM  s    (zEmboss.__generate_emboss_matrixr   r   c                 C  s.   t j| j }t j| j }| j||d}d|iS )N)r?  rK  emboss_matrix)r   r  r{  rI  _Emboss__generate_emboss_matrix)r   r{  rI  rL  r   r   r   r   Z  s    zEmboss.get_paramsr   )r   rL  r   r   c                 K  s   t ||S r   rF  )r   r   rL  r   r   r   r   r   `  s    zEmboss.applyr  c                 C  s   dS )N)r{  rI  r   r   r   r   r   r   c  s    z$Emboss.get_transform_init_args_names)r=  rJ  Nr   )r   r   r   r   r9   r   r   rH  rM  r   r   r   r   r   r   r   r   rq     s   2    c                      s   e Zd ZdZG dd deZdddejddfd	d
ddddd fddZddddZ	ddddZ
ddddddddZ  ZS )rr   a  Transform images partially/completely to their superpixel representation.

    This implementation uses skimage's version of the SLIC (Simple Linear Iterative Clustering) algorithm.

    Args:
        p_replace (tuple[float, float] | float): Defines for any segment the probability that the pixels within that
            segment are replaced by their average color (otherwise, the pixels are not changed).


            * A probability of ``0.0`` would mean, that the pixels in no
                segment are replaced by their average color (image is not
                changed at all).
            * A probability of ``0.5`` would mean, that around half of all
                segments are replaced by their average color.
            * A probability of ``1.0`` would mean, that all segments are
                replaced by their average color (resulting in a voronoi
                image).

            Behavior based on chosen data types for this parameter:
            * If a ``float``, then that ``float`` will always be used.
            * If ``tuple`` ``(a, b)``, then a random probability will be
            sampled from the interval ``[a, b]`` per image.
            Default: (0.1, 0.3)

        n_segments (tuple[int, int] | int): Rough target number of how many superpixels to generate.
            The algorithm may deviate from this number.
            Lower value will lead to coarser superpixels.
            Higher values are computationally more intensive and will hence lead to a slowdown.
            If tuple ``(a, b)``, then a value from the discrete interval ``[a..b]`` will be sampled per image.
            Default: (15, 120)

        max_size (int | None): Maximum image size at which the augmentation is performed.
            If the width or height of an image exceeds this value, it will be
            downscaled before the augmentation so that the longest side matches `max_size`.
            This is done to speed up the process. The final output image has the same size as the input image.
            Note that in case `p_replace` is below ``1.0``,
            the down-/upscaling will affect the not-replaced pixels too.
            Use ``None`` to apply no down-/upscaling.
            Default: 128

        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.

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - This transform can significantly change the visual appearance of the image.
        - The transform makes use of a superpixel algorithm, which tends to be slow.
        If performance is a concern, consider using `max_size` to limit the image size.
        - The effect of this transform can vary greatly depending on the `p_replace` and `n_segments` parameters.
        - When `p_replace` is high, the image can become highly abstracted, resembling a voronoi diagram.
        - The transform preserves the original image type (uint8 or float32).

    Mathematical Formulation:
        1. The image is segmented into approximately `n_segments` superpixels using the SLIC algorithm.
        2. For each superpixel:
        - With probability `p_replace`, all pixels in the superpixel are replaced with their mean color.
        - With probability `1 - p_replace`, the superpixel is left unchanged.
        3. If the image was resized due to `max_size`, it is resized back to its original dimensions.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)

        # Apply superpixels with default parameters
        >>> transform = A.Superpixels(p=1.0)
        >>> augmented_image = transform(image=image)['image']

        # Apply superpixels with custom parameters
        >>> transform = A.Superpixels(
        ...     p_replace=(0.5, 0.7),
        ...     n_segments=(50, 100),
        ...     max_size=None,
        ...     interpolation=cv2.INTER_NEAREST,
        ...     p=1.0
        ... )
        >>> augmented_image = transform(image=image)['image']

    References:
        - SLIC Superpixels: https://scikit-image.org/docs/dev/api/skimage.segmentation.html#skimage.segmentation.slic
        - "SLIC Superpixels Compared to State-of-the-art Superpixel Methods" by Radhakrishna Achanta, et al.
    c                   @  s8   e Zd ZU ded< ded< eddZded< d	ed
< dS )zSuperpixels.InitSchemar4   	p_replacer1   
n_segmentsrN   r  r   max_sizer.   r  N)r   r   r   r   r   rP  r   r   r   r   r     s   
r   )r   r  )r{   r{   r  Nr   rH   rI   r   r   r   r   )rN  rO  rP  r  r   r   c                   sH   t  j||d ttttf || _ttttf || _|| _|| _	d S r   )
r   r   r   r	   r   rN  r   rO  rP  r  )r   rN  rO  rP  r  r   r   r   r   r   r     s
    	zSuperpixels.__init__r   r   c                 C  s   dS )N)rN  rO  rP  r  r   r   r   r   r   r     s    z)Superpixels.get_transform_init_args_namesr   c                 C  s,   t j| j }t j| j }t ||k |dS )N)replace_samplesrO  )r   r   rO  r  rN  r$   )r   rO  r   r   r   r   r     s    zSuperpixels.get_paramsr   zSequence[bool]r   )r   rQ  rO  r   r   c                 K  s   t |||| j| jS r   )r   ZsuperpixelsrP  r  )r   r   rQ  rO  r   r   r   r   r     s    zSuperpixels.apply)r   r   r   r   r9   r   r  INTER_LINEARr   r   r   r   r   r   r   r   r   rr   g  s   ^c                      s   e Zd ZdZG dd deZdejd ejd fddfd	d
ddd fddZddddZ	dddddddZ
ddddZ  ZS )rs   u  Create ringing or overshoot artifacts by convolving the image with a 2D sinc filter.

    This transform simulates the ringing artifacts that can occur in digital image processing,
    particularly after sharpening or edge enhancement operations. It creates oscillations
    or overshoots near sharp transitions in the image.

    Args:
        blur_limit (tuple[int, int] | int): Maximum kernel size for the sinc filter.
            Must be an odd number in the range [3, inf).
            If a single int is provided, the kernel size will be randomly chosen
            from the range (3, blur_limit). If a tuple (min, max) is provided,
            the kernel size will be randomly chosen from the range (min, max).
            Default: (7, 15).
        cutoff (tuple[float, float]): Range to choose the cutoff frequency in radians.
            Values should be in the range (0, π). A lower cutoff frequency will
            result in more pronounced ringing effects.
            Default: (π/4, π/2).
        p (float): Probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - Ringing artifacts are oscillations of the image intensity function in the neighborhood
          of sharp transitions, such as edges or object boundaries.
        - This transform uses a 2D sinc filter (also known as a 2D cardinal sine function)
          to introduce these artifacts.
        - The severity of the ringing effect is controlled by both the kernel size (blur_limit)
          and the cutoff frequency.
        - Larger kernel sizes and lower cutoff frequencies will generally produce more
          noticeable ringing effects.
        - This transform can be useful for:
          * Simulating imperfections in image processing or transmission systems
          * Testing the robustness of computer vision models to ringing artifacts
          * Creating artistic effects that emphasize edges and transitions in images

    Mathematical Formulation:
        The 2D sinc filter kernel is defined as:

        K(x, y) = cutoff * J₁(cutoff * √(x² + y²)) / (2π * √(x² + y²))

        where:
        - J₁ is the Bessel function of the first kind of order 1
        - cutoff is the chosen cutoff frequency
        - x and y are the distances from the kernel center

        The filtered image I' is obtained by convolving the input image I with the kernel K:

        I'(x, y) = ∑∑ I(x-u, y-v) * K(u, v)

        The convolution operation introduces the ringing artifacts near sharp transitions.

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)

        # Apply ringing effect with default parameters
        >>> transform = A.RingingOvershoot(p=1.0)
        >>> ringing_image = transform(image=image)['image']

        # Apply ringing effect with custom parameters
        >>> transform = A.RingingOvershoot(
        ...     blur_limit=(9, 17),
        ...     cutoff=(np.pi/6, np.pi/3),
        ...     p=1.0
        ... )
        >>> ringing_image = transform(image=image)['image']

    References:
        - Ringing artifacts: https://en.wikipedia.org/wiki/Ringing_artifacts
        - Sinc filter: https://en.wikipedia.org/wiki/Sinc_filter
        - "The Importance of Ringing Artifacts in Image Processing" by Jae S. Lim, 1981
        - "Digital Image Processing" by Rafael C. Gonzalez and Richard E. Woods, 4th Edition
    c                   @  s<   e Zd ZU ded< ded< ededddddd	Zd
S )zRingingOvershoot.InitSchemarI   
blur_limitz-Annotated[tuple[float, float], nondecreasing]cutoffr  r   )vr+  r   c                 C  s"   dt jf}t|f||jf  |S Nr   )r   rw  r(   r.  )r  rU  r+  r1  r   r   r   check_cutoffD  s    
z(RingingOvershoot.InitSchema.check_cutoffN)r   r   r   r   r   r  rW  r   r   r   r   r   @  s
   
r   )r@     r  r   Nr   rI   r  r   r   )rS  rT  r   r   c                   s.   t  j||d ttttf || _|| _d S r   )r   r   r   r	   r   rS  rT  )r   rS  rT  r   r   r   r   r   r   K  s    zRingingOvershoot.__init__r   r   c              	     s   t | jd | jd d dd dkr8td t j| j  tjddd  t fddg}W 5 Q R X  d d	tj	  |d d d d f< |
tjt| }d
|iS )Nr   rN   r   zKernel size must be odd. Got: ignore)divideinvalidc              
     st    t  t| d d  d |d d  d    dtj t| d d  d |d d  d    S )NrN   r   )r   Zj1r   rv  rw  )r-  r.  rT  ksizer   r   r  `  s   66z-RingingOvershoot.get_params.<locals>.<lambda>r  kernel)r   	randrangerS  r   r  rT  r   ZerrstateZfromfunctionrw  r!  r   sum)r   r^  r   r\  r   r   V  s    *zRingingOvershoot.get_paramsr   r   r   r   r^  r   r   c                 K  s   t ||S r   rF  r   r   r^  r   r   r   r   r   l  s    zRingingOvershoot.applyr  c                 C  s   dS )N)rS  rT  r   r   r   r   r   r   o  s    z.RingingOvershoot.get_transform_init_args_names)r   r   r   r   r&   r   r   rw  r   r   r   r   r   r   r   r   r   rs     s   Rc                      sv   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ZdddddddddZddddZ	  Z
S )rt   a  Sharpen the input image using Unsharp Masking processing and overlays the result with the original image.

    Unsharp masking is a technique that enhances edge contrast in an image, creating the illusion of increased
        sharpness.
    This transform applies Gaussian blur to create a blurred version of the image, then uses this to create a mask
    which is combined with the original image to enhance edges and fine details.

    Args:
        blur_limit (tuple[int, int] | int): maximum Gaussian kernel size for blurring the input image.
            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`.
            If set single value `blur_limit` will be in range (0, blur_limit).
            Default: (3, 7).
        sigma_limit (tuple[float, float] | float): Gaussian kernel standard deviation. Must be in range [0, inf).
            If set single value `sigma_limit` will be in range (0, sigma_limit).
            If set to 0 sigma will be computed as `sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`. Default: 0.
        alpha (tuple[float, float]): range to choose the visibility of the sharpened image.
            At 0, only the original image is visible, at 1.0 only its sharpened version is visible.
            Default: (0.2, 0.5).
        threshold (int): Value to limit sharpening only for areas with high pixel difference between original image
            and it's smoothed version. Higher threshold means less sharpening on flat areas.
            Must be in range [0, 255]. Default: 10.
        p (float): probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Note:
        - The algorithm creates a mask M = (I - G) * alpha, where I is the original image and G is the Gaussian
            blurred version.
        - The final image is computed as: output = I + M if |I - G| > threshold, else I.
        - Higher alpha values increase the strength of the sharpening effect.
        - Higher threshold values limit the sharpening effect to areas with more significant edges or details.
        - The blur_limit and sigma_limit parameters control the Gaussian blur used to create the mask.

    References:
        - https://en.wikipedia.org/wiki/Unsharp_masking
        - https://arxiv.org/pdf/2107.10833.pdf

    Examples:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>>
        # Apply UnsharpMask with default parameters
        >>> transform = A.UnsharpMask(p=1.0)
        >>> sharpened_image = transform(image=image)['image']
        >>>
        # Apply UnsharpMask with custom parameters
        >>> transform = A.UnsharpMask(
        ...     blur_limit=(3, 7),
        ...     sigma_limit=(0.1, 0.5),
        ...     alpha=(0.2, 0.7),
        ...     threshold=15,
        ...     p=1.0
        ... )
        >>> sharpened_image = transform(image=image)['image']
    c                   @  sX   e Zd ZU ded< ded< edddZded	< d
ed< eded
dddddZdS )zUnsharpMask.InitSchemar/   sigma_limitr4   r{  r   r$  r   r   r  rI   rS  r   r   r)  c                 C  s   t ||ddS )Nrz   )Z	min_value)r'   )r  r*  r+  r   r   r   process_blur  s    z#UnsharpMask.InitSchema.process_blurN)	r   r   r   r   r   r  r   r  rd  r   r   r   r   r     s   
r   rz   r@  r  r=  r  Nr   rI   rH   r   r   r   )rS  rc  r{  r  r   r   c                   sV   t  j||d ttttf || _ttttf || _ttttf || _|| _	d S r   )
r   r   r   r	   r   rS  r   rc  r{  r  )r   rS  rc  r{  r  r   r   r   r   r   r     s
    	zUnsharpMask.__init__r   r   c                 C  s6   t | jd | jd d dt j| j t j| j dS )Nr   rN   r   )r]  r  r{  )r   r_  rS  r  rc  r{  r   r   r   r   r     s    

zUnsharpMask.get_paramsr   r   )r   r]  r  r{  r   r   c                 K  s   t j||||| jdS )N)r  r{  r  )r   Zunsharp_maskr  )r   r   r]  r  r{  r   r   r   r   r     s    zUnsharpMask.applyr   c                 C  s   dS )N)rS  rc  r{  r  r   r   r   r   r   r     s    z)UnsharpMask.get_transform_init_args_names)re  r  r=  r  Nr   r9  r   r   r   r   rt   s  s   >      c                      s   e Zd ZdZG dd deZejejej	ej
f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dZdddddddZdddddddZd d d d!d"d#Zd$d%d&d'Z  ZS ))ru   a
  Drops random pixels from the image.

    This transform randomly sets pixels in the image to a specified value, effectively "dropping out" those pixels.
    It can be applied to both the image and its corresponding mask.

    Args:
        dropout_prob (float): Probability of dropping out each pixel. Should be in the range [0, 1].
            Default: 0.01

        per_channel (bool): If True, the dropout mask will be generated independently for each channel.
            If False, the same dropout mask will be applied to all channels.
            Default: False

        drop_value (float | Sequence[float] | None): Value to assign to the dropped pixels.
            If None, the value will be randomly sampled for each application:
                - For uint8 images: Random integer in [0, 255]
                - For float32 images: Random float in [0, 1]
            If a single number, that value will be used for all dropped pixels.
            If a sequence, it should contain one value per channel.
            Default: 0

        mask_drop_value (float | Sequence[float] | None): Value to assign to dropped pixels in the mask.
            If None, the mask will remain unchanged.
            If a single number, that value will be used for all dropped pixels in the mask.
            If a sequence, it should contain one value per channel of the mask.
            Note: Only applicable when per_channel=False.
            Default: None

        always_apply (bool): If True, the transform will always be applied.
            Default: False

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

    Targets:
        image, mask, bboxes, keypoints

    Image types:
        uint8, float32

    Note:
        - When applied to bounding boxes, this transform may cause some boxes to have zero area
          if all pixels within the box are dropped. Such boxes will be removed.
        - When applied to keypoints, keypoints that fall on dropped pixels will be removed if
          the keypoint processor is configured to remove invisible keypoints.
        - The 'per_channel' option is not supported for mask dropout. If you need to drop pixels
          in a multi-channel mask independently, consider applying this transform multiple times
          with per_channel=False.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
        >>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
        >>> transform = A.PixelDropout(dropout_prob=0.1, per_channel=True, p=1.0)
        >>> result = transform(image=image, mask=mask)
        >>> dropped_image, dropped_mask = result['image'], result['mask']
    c                   @  sF   e Zd ZU ded< ded< ded< ded< edd	d
dddZdS )zPixelDropout.InitSchemar2   dropout_probr  r  ScaleFloatType | None
drop_valuemask_drop_valuer   r   r"   r   c                 C  s    | j d k	r| jrd}t|| S )Nz7PixelDropout supports mask only with per_channel=False.)ri  r  r   r  r   r   r   validate_mask_drop_value  s    z0PixelDropout.InitSchema.validate_mask_drop_valueN)r   r   r   r   r   rj  r   r   r   r   r     s   
r   rg  Fr   Nr   r   r  rg  r   )rf  r  rh  ri  r   r   c                   s,   t  j||d || _|| _|| _|| _d S r   )r   r   rf  r  rh  ri  )r   rf  r  rh  ri  r   r   r   r   r   r   %  s
    	zPixelDropout.__init__r   zfloat | Sequence[float]r   )r   	drop_maskrh  r   r   c                 K  s   t |||S r   )r   pixel_dropout)r   r   rk  rh  r   r   r   r   r   4  s    zPixelDropout.apply)r   rk  r   r   c                 K  s2   | j d kr|S |jtkr"t|}t||| j S r   )ri  r  r?   r   r#  r   rl  )r   r   rk  r   r   r   r   r   =  s
    


zPixelDropout.apply_to_maskznp.ndarray | None)r  rk  r   r   c                 K  sl   |d ks| j r|S tt| d}|d kr.|S |d d d }t||}t||||jj|jj	}t
||S )Nr  r   r   )r  r   r*   get_processorr+   fdropoutZmask_dropout_bboxesr   Zmin_areaZmin_visibilityr,   )r   r  rk  r   	processorr   Zdenormalized_bboxesr  r   r   r   r  F  s    
zPixelDropout.apply_to_bboxes)r   rk  r   r   c                 K  sB   |d ks| j r|S tt| d}|d ks2|jjs6|S t||S )Nr   )r  r   r-   rm  r   Zremove_invisiblern  Zmask_dropout_keypoints)r   r   rk  r   ro  r   r   r   r   \  s    zPixelDropout.apply_to_keypointsr   r   c           	      C  s
  d|kr|d n
|d d }| j r(|jn|jd d }t }|jddg|| jd| j gd}|j|jkrvt|d	}| j	d krt
|rdnt|jd	 }|jtjkr|dtt|j ||j}n4|jtjkr|dd||j}ntd
|j n| j	}||dS )Nr   r  r   r   TFrN   )r   r  zUnsupported dtype: )rk  rh  )r  r   r$   r   rx  rf  r  r   r  rh  r   r   r   r  r   r   r   r  r!  r   )	r   r   r   r   r   Zrndrk  Z
drop_shaperh  r   r   r   r   g  s     
z)PixelDropout.get_params_dependent_on_datar8  r   c                 C  s   dS )N)rf  r  rh  ri  r   r   r   r   r   r     s    z*PixelDropout.get_transform_init_args_names)rg  Fr   NNr   )r   r   r   r   r9   r   rK   r   r   BBOXESr   r   r   r   r   r  r   r   r   r   r   r   r   r   ru     s    ;      		c                      s   e Zd ZdZG dd deZd!dddddddddd	 fddZddddddddddZddddddZdddd Z	  Z
S )"rv   ai  Apply spatter transform. It simulates corruption which can occlude a lens in the form of rain or mud.

    Args:
        mean (tuple[float, float] | float): Mean value of normal distribution for generating liquid layer.
            If single float mean will be sampled from `(0, mean)`
            If tuple of float mean will be sampled from range `(mean[0], mean[1])`.
            If you want constant value use (mean, mean).
            Default (0.65, 0.65)
        std (tuple[float, float] | float): Standard deviation value of normal distribution for generating liquid layer.
            If single float the number will be sampled from `(0, std)`.
            If tuple of float std will be sampled from range `(std[0], std[1])`.
            If you want constant value use (std, std).
            Default: (0.3, 0.3).
        gauss_sigma (tuple[float, float] | floats): Sigma value for gaussian filtering of liquid layer.
            If single float the number will be sampled from `(0, gauss_sigma)`.
            If tuple of float gauss_sigma will be sampled from range `(gauss_sigma[0], gauss_sigma[1])`.
            If you want constant value use (gauss_sigma, gauss_sigma).
            Default: (2, 3).
        cutout_threshold (tuple[float, float] | floats): Threshold for filtering liqued layer
            (determines number of drops). If single float it will used as cutout_threshold.
            If single float the number will be sampled from `(0, cutout_threshold)`.
            If tuple of float cutout_threshold will be sampled from range `(cutout_threshold[0], cutout_threshold[1])`.
            If you want constant value use `(cutout_threshold, cutout_threshold)`.
            Default: (0.68, 0.68).
        intensity (tuple[float, float] | floats): Intensity of corruption.
            If single float the number will be sampled from `(0, intensity)`.
            If tuple of float intensity will be sampled from range `(intensity[0], intensity[1])`.
            If you want constant value use `(intensity, intensity)`.
            Default: (0.6, 0.6).
        mode (str, or list[str]): Type of corruption. Currently, supported options are 'rain' and 'mud'.
             If list is provided type of corruption will be sampled list. Default: ("rain").
        color (list of (r, g, b) or dict or None): Corruption elements color.
            If list uses provided list as color for specified mode.
            If dict uses provided color for specified mode. Color for each specified mode should be provided in dict.
            If None uses default colors (rain: (238, 238, 175), mud: (20, 42, 63)).
        p (float): probability of applying the transform. Default: 0.5.

    Targets:
        image

    Image types:
        uint8, float32

    Reference:
        https://arxiv.org/abs/1903.12261
        https://github.com/hendrycks/robustness/blob/master/ImageNet-C/create_c/make_imagenet_c.py

    c                   @  s   e Zd ZU dZded< dZded< dZded< d	Zded
< dZded< e	dddZ
ded< dZded< ededddddZeddddddZdS )zSpatter.InitSchema?rr  r4   r   r  r  r   r   r   r/   gauss_sigma(\?rw  cutout_threshold333333?rz  rO  rainz#Type of corruption ('rain', 'mud').)r1  r  #SpatterMode | Sequence[SpatterMode]r   N/Sequence[int] | dict[str, Sequence[int]] | NonecolorzSequence[SpatterMode])r   r   c                 C  s   t |tr|gS |S r   )r  r  )r  r   r   r   r   
check_mode  s    
zSpatter.InitSchema.check_moder   r   r"   r   c                 C  s   | j d kr$dddgdddgd| _ nt| j ttfrpt| jdkrpt| j tkr\d}t|| jd	 | j i| _ ntt| j tri }| jD ]N}|| j krtd
| dt| j | tkrtd
| d| j | ||< qnd}t|| S )N      r|   *   ?   )r{  mudrN   z6Color must be a list of three integers for RGB format.r   zColor for mode z is not specified.z must be in RGB format.zHColor must be a list of RGB values or a dict mapping mode to RGB values.)	r~  r  r  rz  r  r   r@   r   r  )r   r  r  r   r   r   r   check_color  s$    


zSpatter.InitSchema.check_color)r   r   r   r   r   r   ru  rx  rO  r   r   r~  r   r  r  r   r  r   r   r   r   r     s   
r   rq  rs  rt  rv  ry  r{  Nr   rH   r|  r}  r   r   )	r   r   ru  rx  rO  r   r~  r   r   c
           
        s   t  j|	|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t f || _d S r   )r   r   r   r	   r   r   r   ru  rx  rO  r   r   r  r   r   r~  )
r   r   r   ru  rx  rO  r   r~  r   r   r   r   r   r     s    zSpatter.__init__r   rJ   r   )r   non_mudr  dropsr   r   r   c                 K  s   t | t|||||S r   )r)   r   Zspatter)r   r   r  r  r  r   r   r   r   r   r     s    	zSpatter.applyr   c                 C  s  |d d d \}}t j| j }t j| j }t j| j }t j| j }t | j}	t j| j }
t	
| j|	 d }tj||f||d}t||dd}d|||k < |	dkrt|d	 t	j}d	t|d
d }t|tjd}t|ddtj\}}tt|dt	j}t|}t	
dddgdddgdddgg}t||}t|dt	j}|| }|dt	j|dd 9 }|d d d d d f | |
 }d }d }nZt	||kdd}t|t	j|dd}d||d| k < |dt	jf }|| }d| }d }||||	dS )Nr   r   r   )r  r  r  Znearest)r  r   r   r{  r$  2      r#  r|   rz   r  rN   ra  r  r5  .)r  r  r  r   ) r   r  r   r   rx  ru  rx  r   rO  r   r   r~  r$   r  r   r   r  r  ZCannyZdistanceTransformZDIST_L2r  ZTHRESH_TRUNCr%   r   r  rG  r!  r   r(  whereZnewaxis)r   r   r   r*  r+  r   r   rx  r  r   rO  r~  Zliquid_layerdistr,  Zkermr  r  r  r   r   r   r     sL    

"z$Spatter.get_params_dependent_on_dataz(tuple[str, str, str, str, str, str, str]r   c                 C  s   dS )N)r   r   ru  rO  rx  r   r~  r   r   r   r   r   r   4  s    z%Spatter.get_transform_init_args_names)	rq  rs  rt  rv  ry  r{  NNr   rF  r   r   r   r   rv     s   1,         $2c                      s   e Zd ZdZG dd deZdddejddfd	d	d
dddd fddZddddddddddZ	ddddZ
eddddddZeddddddZddd d!Z  ZS )"rw   a)  Add lateral chromatic aberration by distorting the red and blue channels of the input image.

    Chromatic aberration is an optical effect that occurs when a lens fails to focus all colors to the same point.
    This transform simulates this effect by applying different radial distortions to the red and blue channels
    of the image, while leaving the green channel unchanged.

    Args:
        primary_distortion_limit (tuple[float, float] | float): Range of the primary radial distortion coefficient.
            If a single float value is provided, the range
            will be (-primary_distortion_limit, primary_distortion_limit).
            This parameter controls the distortion in the center of the image:
            - Positive values result in pincushion distortion (edges bend inward)
            - Negative values result in barrel distortion (edges bend outward)
            Default: (-0.02, 0.02).

        secondary_distortion_limit (tuple[float, float] | float): Range of the secondary radial distortion coefficient.
            If a single float value is provided, the range
            will be (-secondary_distortion_limit, secondary_distortion_limit).
            This parameter controls the distortion in the corners of the image:
            - Positive values enhance pincushion distortion
            - Negative values enhance barrel distortion
            Default: (-0.05, 0.05).

        mode (Literal["green_purple", "red_blue", "random"]): Type of color fringing to apply. Options are:
            - 'green_purple': Distorts red and blue channels in opposite directions, creating green-purple fringing.
            - 'red_blue': Distorts red and blue channels in the same direction, creating red-blue fringing.
            - 'random': Randomly chooses between 'green_purple' and 'red_blue' modes for each application.
            Default: 'green_purple'.

        interpolation (InterpolationType): Flag specifying 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.

        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:
        3

    Note:
        - This transform only affects RGB images. Grayscale images will raise an error.
        - The strength of the effect depends on both primary and secondary distortion limits.
        - Higher absolute values for distortion limits will result in more pronounced chromatic aberration.
        - The 'green_purple' mode tends to produce more noticeable effects than 'red_blue'.

    Example:
        >>> import albumentations as A
        >>> import cv2
        >>> transform = A.ChromaticAberration(
        ...     primary_distortion_limit=0.05,
        ...     secondary_distortion_limit=0.1,
        ...     mode='green_purple',
        ...     interpolation=cv2.INTER_LINEAR,
        ...     p=1.0
        ... )
        >>> transformed = transform(image=image)
        >>> aberrated_image = transformed['image']

    References:
        - https://en.wikipedia.org/wiki/Chromatic_aberration
        - https://www.researchgate.net/publication/320691320_Chromatic_Aberration_in_Digital_Images
    c                   @  s.   e Zd ZU ded< ded< ded< ded< dS )	zChromaticAberration.InitSchemar3   primary_distortion_limitsecondary_distortion_limitrB   r   r.   r  Nr   r   r   r   r   r   ~  s   
r   )g{Gzg{Gz?)grr  green_purpleNr   rH   rB   r.   r   r   )r  r  r   r  r   r   c                   sH   t  j||d ttttf || _ttttf || _|| _|| _d S r   )	r   r   r   r	   r   r  r  r   r  )r   r  r  r   r  r   r   r   r   r   r     s
    	zChromaticAberration.__init__r   r   )r   primary_distortion_redsecondary_distortion_redprimary_distortion_bluesecondary_distortion_bluer   r   c                 K  s   t | t|||||| jS r   )r)   r   Zchromatic_aberrationr  )r   r   r  r  r  r  r   r   r   r   r     s    	zChromaticAberration.applyr  r   c                 C  s   t j| j }t j| j }t j| j }t j| j }| ||}| ||}| jdkrj| ||}| ||}| jdkr| ||}| ||}||||dS )Nr  Zred_blue)r  r  r  r  )r   r  r  r  _match_signr   _unmatch_sign)r   r  r  r  r  r   r   r   r     s"    

zChromaticAberration.get_params)abr   c                 C  s8   | d  k r|k s.n | d  kr*|kr4n n| S |S rV  r   r  r  r   r   r   r    s    .zChromaticAberration._match_signc                 C  s*   | dk r|dk s | dkr&|dkr&| S |S rV  r   r  r   r   r   r    s     z!ChromaticAberration._unmatch_signr8  c                 C  s   dS )N)r  r  r   r  r   r   r   r   r   r     s    z1ChromaticAberration.get_transform_init_args_names)r   r   r   r   r9   r   r  rR  r   r   r   rH  r  r  r   r   r   r   r   r   rw   8  s    Ec                      s   e Zd ZdZejejejejf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dddZdddddddZddddZddd d!Z  ZS )#rx   a  Apply a morphological operation (dilation or erosion) to an image,
    with particular value for enhancing document scans.

    Morphological operations modify the structure of the image.
    Dilation expands the white (foreground) regions in a binary or grayscale image, while erosion shrinks them.
    These operations are beneficial in document processing, for example:
    - Dilation helps in closing up gaps within text or making thin lines thicker,
        enhancing legibility for OCR (Optical Character Recognition).
    - Erosion can remove small white noise and detach connected objects,
        making the structure of larger objects more pronounced.

    Args:
        scale (int or tuple/list of int): Specifies the size of the structuring element (kernel) used for the operation.
            - If an integer is provided, a square kernel of that size will be used.
            - If a tuple or list is provided, it should contain two integers representing the minimum
                and maximum sizes for the dilation kernel.
        operation (str, optional): The morphological operation to apply. Options are 'dilation' or 'erosion'.
            Default is 'dilation'.
        p (float, optional): The probability of applying this transformation. Default is 0.5.

    Targets:
        image, mask, keypoints, bboxes

    Image types:
        uint8, float32

    Reference:
        https://github.com/facebookresearch/nougat

    Example:
        >>> import albumentations as A
        >>> transform = A.Compose([
        >>>     A.Morphological(scale=(2, 3), operation='dilation', p=0.5)
        >>> ])
        >>> image = transform(image=image)["image"]
    c                   @  s   e Zd ZU ded< ded< dS )zMorphological.InitSchemar1   r  rE   	operationNr   r   r   r   r   r     s   
r   r   rz   dilationNr   rI   rE   r   r   )r  r  r   r   c                   s.   t  j||d ttttf || _|| _d S r   )r   r   r   r	   r   r  r  )r   r  r  r   r   r   r   r   r     s    zMorphological.__init__r   r   r   ra  c                 K  s   t ||| jS r   )r   Z
morphologyr  rb  r   r   r   r     s    zMorphological.apply)r  r^  r   r   c                 K  s.   |d }t ||}t||| j|}t||S )Nr   )r+   r   Zbboxes_morphologyr  r,   )r   r  r^  r   r   Zdenormalized_boxesr  r   r   r   r    s    
zMorphological.apply_to_bboxes)r   r^  r   r   c                 K  s   |S r   r   )r   r   r^  r   r   r   r   r     s    z Morphological.apply_to_keypointsr  r   c                 C  s   dt t j| jiS )Nr^  )r  ZgetStructuringElementZMORPH_ELLIPSEr  r   r   r   r   r     s     zMorphological.get_paramsr   c                 C  s   dS )N)r  r  r   r   r   r   r   r     s    z+Morphological.get_transform_init_args_names)r  r  Nr   )r   r   r   r   rK   r   r   r   rp  r   r9   r   r   r   r  r   r   r   r   r   r   r   r   rx     s   %    		blackbodyciedip  r  )MAX_TEMPMIN_BLACKBODY_TEMPMIN_CIED_TEMP
WHITE_TEMPSAMPLING_TEMP_PROBc                      sr   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ZddddZddddZ	  Z
S )ry   aM  Applies Planckian Jitter to the input image, simulating color temperature variations in illumination.

    This transform adjusts the color of an image to mimic the effect of different color temperatures
    of light sources, based on Planck's law of black body radiation. It can simulate the appearance
    of an image under various lighting conditions, from warm (reddish) to cool (bluish) color casts.

    PlanckianJitter vs. ColorJitter:
    PlanckianJitter is fundamentally different from ColorJitter in its approach and use cases:
    1. Physics-based: PlanckianJitter is grounded in the physics of light, simulating real-world
       color temperature changes. ColorJitter applies arbitrary color adjustments.
    2. Natural effects: This transform produces color shifts that correspond to natural lighting
       variations, making it ideal for outdoor scene simulation or color constancy problems.
    3. Single parameter: Color changes are controlled by a single, physically meaningful parameter
       (color temperature), unlike ColorJitter's multiple abstract parameters.
    4. Correlated changes: Color shifts are correlated across channels in a way that mimics natural
       light, whereas ColorJitter can make independent channel adjustments.

    When to use PlanckianJitter:
    - Simulating different times of day or lighting conditions in outdoor scenes
    - Augmenting data for computer vision tasks that need to be robust to natural lighting changes
    - Preparing synthetic data to better match real-world lighting variations
    - Color constancy research or applications
    - When you need physically plausible color variations rather than arbitrary color changes

    The logic behind PlanckianJitter:
    As the color temperature increases:
    1. Lower temperatures (around 3000K) produce warm, reddish tones, simulating sunset or incandescent lighting.
    2. Mid-range temperatures (around 5500K) correspond to daylight.
    3. Higher temperatures (above 7000K) result in cool, bluish tones, similar to overcast sky or shade.
    This progression mimics the natural variation of sunlight throughout the day and in different weather conditions.

    Args:
        mode (Literal["blackbody", "cied"]): The mode of the transformation.
            - "blackbody": Simulates blackbody radiation color changes.
            - "cied": Uses the CIE D illuminant series for color temperature simulation.
            Default: "blackbody"

        temperature_range (tuple[int, int] | None): The range of color temperatures (in Kelvin) to sample from.
            - For "blackbody" mode: Should be within [3000K, 15000K]. Default: (3000, 15000)
            - For "cied" mode: Should be within [4000K, 15000K]. Default: (4000, 15000)
            If None, the default ranges will be used based on the selected mode.
            Higher temperatures produce cooler (bluish) images, lower temperatures produce warmer (reddish) images.

        sampling_method (Literal["uniform", "gaussian"]): Method to sample the temperature.
            - "uniform": Samples uniformly across the specified range.
            - "gaussian": Samples from a Gaussian distribution centered at 6500K (approximate daylight).
            Default: "uniform"

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

    Targets:
        image

    Image types:
        uint8, float32

    Number of channels:
        Any

    Note:
        - The transform preserves the overall brightness of the image while shifting its color.
        - The "blackbody" mode provides a wider range of color shifts, especially in the lower (warmer) temperatures.
        - The "cied" mode is based on standard illuminants and may provide more realistic daylight variations.
        - The Gaussian sampling method tends to produce more subtle variations, as it's centered around daylight.
        - Unlike ColorJitter, this transform ensures that color changes are physically plausible and correlated
          across channels, maintaining the natural appearance of the scene under different lighting conditions.

    Example:
        >>> import numpy as np
        >>> import albumentations as A
        >>> image = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8)
        >>> transform = A.PlanckianJitter(mode="blackbody",
        ...                               temperature_range=(3000, 9000),
        ...                               sampling_method="uniform",
        ...                               p=1.0)
        >>> result = transform(image=image)
        >>> jittered_image = result["image"]

    References:
        - Planck's law: https://en.wikipedia.org/wiki/Planck%27s_law
        - CIE Standard Illuminants: https://en.wikipedia.org/wiki/Standard_illuminant
        - Color temperature: https://en.wikipedia.org/wiki/Color_temperature
        - Implementation inspired by: https://github.com/TheZino/PlanckianJitter
    c                   @  s>   e Zd ZU ded< ded< ded< eddd	d
ddZdS )zPlanckianJitter.InitSchemarF   r   z@Annotated[tuple[int, int], AfterValidator(nondecreasing)] | Nonetemperature_limit Literal[('uniform', 'gaussian')]sampling_methodr   r   r"   r   c                 C  s   t td }| jd krR| jdkr4t td |f| _q| jdkrt td |f| _n| jdkrt| jtd k s|t| j|krtd| jdkrt| jtd k st| j|krtd| jd td	   kr| jd
 ksn td| S )Nr  r  r  r  r  zATemperature limits for blackbody should be in [3000, 15000] rangez<Temperature limits for CIED should be in [4000, 15000] ranger   r  rN   z9White temperature should be within the temperature limits)r   PLANKIAN_JITTER_CONSTr  r   r)  r(  r   )r   Zmax_tempr   r   r   validate_temperature  s*    




&z/PlanckianJitter.InitSchema.validate_temperatureN)r   r   r   r   r   r  r   r   r   r   r     s
   
r   r  Nr  r   rF   ztuple[int, int] | Noner  r   r   None)r   r  r  r   r   r   c                   s4   t  j||d || _ttttf || _|| _d S r   )r   r   r   r   r	   r   r  r  )r   r   r  r  r   r   r   r   r   r     s    zPlanckianJitter.__init__r   r   r   )r   temperaturer   r   c                 K  s"   t |stdtj||| jdS )Nz8PlanckianJitter transformation expects 3-channel images.r   )r   r  r   Zplanckian_jitterr   )r   r   r  r   r   r   r   r     s    zPlanckianJitter.applyr   r   c              
   C  s   t d }t d }| jdkrNt |k r:t| jd |}qt|| jd }n| jdkrt |k rttdt|| jd  d }|| }qttdt| jd | d }|| }ntd| j t	|| jd | jd }d	t
|iS )
Nr  r  r  r   rN   Zgaussianrz   zUnknown sampling method: r  )r  r  r   r  r  r   r  r  r   r   r   )r   Zsampling_prob_boundaryZsampling_temp_boundaryr  r  r   r   r   r     s>    



zPlanckianJitter.get_paramsr   c                 C  s   dS )N)r   r  r  r   r   r   r   r   r     s    z-PlanckianJitter.get_transform_init_args_names)r  Nr  Nr   r  r   r   r   r   ry   )  s   U!     ,)
__future__r   rj  r/  r   r  typesr   typingr   r   r   r   r   r	   r
   r   r   r  r  Znumpyr   r   r   r   r   r   r   r   r   r   r   r   Zpydanticr   r   r   r   r   r   Zscipyr   Zscipy.ndimager   Ztyping_extensionsr    r!   r"   r#   Z/albumentations.augmentations.dropout.functionalZaugmentationsZdropoutrO   rn  Z1albumentations.augmentations.geometric.functionalZ	geometricr   Zalbumentationsr$   Z,albumentations.augmentations.blur.functionalr%   Z,albumentations.augmentations.blur.transformsr&   r'   Z"albumentations.augmentations.utilsr(   r)   Zalbumentations.core.bbox_utilsr*   r+   r,   Z#albumentations.core.keypoints_utilsr-   Zalbumentations.core.pydanticr.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   Z(albumentations.core.transforms_interfacer9   r:   r;   r<   r=   Zalbumentations.core.typesr>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   Zalbumentations.core.utilsrL   rM    r   __all__r  r   ZTWENTYrR   rP   r\   r`   ra   rb   rc   rd   re   rf   rS   ri   rk   rj   rT   r_   rU   rh   rV   rW   rX   rQ   rY   rZ   r[   r]   r^   r  r  rl   rg   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   r(  ZPLANCKIAN_COEFFSkeysr)  r  ry   r   r   r   r   <module>   s  (4 4@-lx    J *  6 MkbPjzPvlVO]N9LH? ojC #r\  g , 4 P	