o
    i er                    @   s@  d Z ddlZddlm  mZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ d
ZdZdd ZeddG dd dejZeddG dd dejZeddg dG dd dejZeddG dd dejZdZd Zd!Zed"d#g dG d$d% d%ejZ ed&d'g dG d(d) d)ejZ!dNd*d+Z"	,	-	.		dOd/d0Z#dNd1d2Z$ed3d4g dG d5d6 d6ejZ%ed7d8g dG d9d: d:ejZ&dNd;d<Z'ed=d>g dG d?d@ d@ejZ(edAg dG dBdC dCejZ)edDdEg dG dFdG dGejZ*edHdIg dG dJdK dKejZ+dNdLdMZ,dS )Pz!Keras image preprocessing layers.    N)keras_export)backend)
base_layer)base_preprocessing_layer)preprocessing_utils)image_utils)tf_utilsc                 C   s4   | dvrt d|  d|dvrt d| dd S )N>   wrapnearestreflectconstantzUnknown `fill_mode` zA. Only `reflect`, `wrap`, `constant` and `nearest` are supported.>   r   bilinearzUnknown `interpolation` z.. Only `nearest` and `bilinear` are supported.)NotImplementedError)	fill_modeinterpolation r   a/var/www/myenv/lib/python3.10/site-packages/keras/src/layers/preprocessing/image_preprocessing.py!check_fill_mode_and_interpolation    s   

r   zkeras.layers.Resizingz0keras.layers.experimental.preprocessing.Resizingc                       sB   e Zd ZdZ		d fdd	Zdd Zdd	 Z fd
dZ  ZS )Resizinga  A preprocessing layer which resizes images.

    This layer resizes an image input to a target height and width. The input
    should be a 4D (batched) or 3D (unbatched) tensor in `"channels_last"`
    format. Input pixel values can be of any range
    (e.g. `[0., 1.)` or `[0, 255]`) and of integer or floating point dtype.
    By default, the layer will output floats.

    This layer can be called on tf.RaggedTensor batches of input images of
    distinct sizes, and will resize the outputs to dense tensors of uniform
    size.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Args:
        height: Integer, the height of the output shape.
        width: Integer, the width of the output shape.
        interpolation: String, the interpolation method.
            Supports `"bilinear"`, `"nearest"`, `"bicubic"`, `"area"`,
            `"lanczos3"`, `"lanczos5"`, `"gaussian"`, `"mitchellcubic"`.
            Defaults to `"bilinear"`.
        crop_to_aspect_ratio: If True, resize the images without aspect
            ratio distortion. When the original aspect ratio differs
            from the target aspect ratio, the output image will be
            cropped so as to return the
            largest possible window in the image (of size `(height, width)`)
            that matches the target aspect ratio. By default
            (`crop_to_aspect_ratio=False`), aspect ratio may not be preserved.
    r   Fc                    sL   || _ || _|| _|| _t|| _t jdi | t	j
dd d S )Nr   Tr   )heightwidthr   crop_to_aspect_ratior   get_interpolation_interpolation_methodsuper__init__r   keras_kpl_gaugeget_cellset)selfr   r   r   r   kwargs	__class__r   r   r   P   s   zResizing.__init__c                    s   j dkr	j}ntj}t |d jjgjrJ fdd}t	 rEt
}| jdd   }t||}tj| |d}n| }n
tjj jd}t|jS )Nr   dtypec                    s$   t  r	|  } tj| jdS )N)sizer   )r   	is_ragged	to_tensorr   smart_resizer   )xinputsr!   r'   r   r   resize_to_aspecto   s
   
z'Resizing.call.<locals>.resize_to_aspect)fn_output_signature)r'   method)r   compute_dtypetffloat32convert_inputsr   r   r   r   r(   TensorShapeshape
TensorSpecmap_fnimageresizer   cast)r!   r-   input_dtyper.   size_as_shaper7   specoutputsr   r,   r   callb   s&   



zResizing.callc                 C   ,   t | }| j|t< | j|t< t |S Nr3   r6   as_listr   H_AXISr   W_AXISr!   input_shaper   r   r   compute_output_shape      


zResizing.compute_output_shapec                    s<   | j | j| j| jd}t  }tt| t|  S )N)r   r   r   r   )	r   r   r   r   r   
get_configdictlistitemsr!   configbase_configr#   r   r   rL      s   
zResizing.get_config)r   F	__name__
__module____qualname____doc__r   rA   rJ   rL   __classcell__r   r   r#   r   r   -   s    ##r   zkeras.layers.CenterCropz2keras.layers.experimental.preprocessing.CenterCropc                       s<   e Zd ZdZ fddZdd Zdd Z fdd	Z  ZS )

CenterCropa  A preprocessing layer which crops images.

    This layers crops the central portion of the images to a target size. If an
    image is smaller than the target size, it will be resized and cropped
    so as to return the largest possible window in the image that matches
    the target aspect ratio.

    Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
    of integer or floating point dtype.
    By default, the layer will output floats.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., target_height, target_width, channels)`.

    If the input height/width is even and the target height/width is odd (or
    inversely), the input image is left-padded by 1 pixel.

    Args:
        height: Integer, the height of the output shape.
        width: Integer, the width of the output shape.
    c                    s<   || _ || _t jdi |ddi tjdd d S )NautocastFrY   Tr   )r   r   r   r   r   r   r   r    )r!   r   r   r"   r#   r   r   r      s   zCenterCrop.__init__c                    sr   t jt}|t j  |t j  fdd}fdd}tt	 dkdkf||S )Nc                     s<   t  d t j} t d t j}t j| |jjS )N   )r3   r<   int32r:   crop_to_bounding_boxr   r   )h_startw_starth_diffr-   r!   w_diffr   r   center_crop   s
   z$CenterCrop.call.<locals>.center_cropc                     "   t  jjg} t| jS rC   r   r*   r   r   r3   r<   r2   r@   r-   r!   r   r   upsize      zCenterCrop.call.<locals>.upsizer   
r5   r2   r3   r7   rF   r   rG   r   cond
reduce_all)r!   r-   rI   rc   rh   r   r`   r   rA      s   
zCenterCrop.callc                 C   rB   rC   rD   rH   r   r   r   rJ      rK   zCenterCrop.compute_output_shapec                    4   | j | jd}t  }tt| t|  S )N)r   r   )r   r   r   rL   rM   rN   rO   rP   r#   r   r   rL      
   
zCenterCrop.get_configrS   r   r   r#   r   rY      s    rY   zkeras.layers.RandomCropz2keras.layers.experimental.preprocessing.RandomCrop)v1c                       @   e Zd ZdZd fdd	ZdddZdd	 Z fd
dZ  ZS )
RandomCropao  A preprocessing layer which randomly crops images during training.

    During training, this layer will randomly choose a location to crop images
    down to a target size. The layer will crop all the images in the same batch
    to the same cropping location.

    At inference time, and during training if an input image is smaller than the
    target size, the input will be resized and cropped so as to return the
    largest possible window in the image that matches the target aspect ratio.
    If you need to apply random cropping at inference time, set `training` to
    True when calling the layer.

    Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
    of integer or floating point dtype. By default, the layer will output
    floats.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., target_height, target_width, channels)`.

    Args:
        height: Integer, the height of the output shape.
        width: Integer, the width of the output shape.
        seed: Integer. Used to create a random seed.
    Nc                    sF   t jdd t jdi |d|dd || _|| _|| _d S )Nrq   TF)rZ   seedforce_generatorr   )	r   r   r   r    r   r   r   r   rr   )r!   r   r   rr   r"   r#   r   r   r     s   


zRandomCrop.__init__Tc                    sx   t jdtt j  t j  fdd}fdd}tt	| dkdkf||S )Nr%   c                     sT   j } jdgd| j| }|d  d  }|d d  }tj||jjS )Nr[   r      )	r&   _random_generatorrandom_uniformmaxr3   r:   r]   r   r   )r&   randsr^   r_   ra   rI   r-   r!   rb   r   r   random_crop   s   z$RandomCrop.call.<locals>.random_cropc                     rd   rC   re   rf   rg   r   r   r;   +  ri   zRandomCrop.call.<locals>.resizer   rj   )r!   r-   trainingrz   r;   r   ry   r   rA     s   
zRandomCrop.callc                 C   rB   rC   rD   rH   r   r   r   rJ   8  rK   zRandomCrop.compute_output_shapec                    8   | j | j| jd}t  }tt| t|  S )N)r   r   rr   )r   r   rr   r   rL   rM   rN   rO   rP   r#   r   r   rL   >     
zRandomCrop.get_configrC   TrS   r   r   r#   r   rq      s    !
rq   zkeras.layers.Rescalingz1keras.layers.experimental.preprocessing.Rescalingc                       s>   e Zd ZdZd fdd	Zdd Zdd Z fd	d
Z  ZS )	Rescalinga  A preprocessing layer which rescales input values to a new range.

    This layer rescales every value of an input (often an image) by multiplying
    by `scale` and adding `offset`.

    For instance:

    1. To rescale an input in the `[0, 255]` range
    to be in the `[0, 1]` range, you would pass `scale=1./255`.

    2. To rescale an input in the `[0, 255]` range to be in the `[-1, 1]` range,
    you would pass `scale=1./127.5, offset=-1`.

    The rescaling is applied both during training and inference. Inputs can be
    of integer or floating point dtype, and by default the layer will output
    floats.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Input shape:
        Arbitrary.

    Output shape:
        Same as input.

    Args:
        scale: Float, the scale to apply to the inputs.
        offset: Float, the offset to apply to the inputs.
            c                    s4   || _ || _t jdi | tjdd d S )Nr   Tr   )scaleoffsetr   r   r   r   r   r    )r!   r   r   r"   r#   r   r   r   l  s   zRescaling.__init__c                 C   sB   | j }t||d}t| j|}t| j|}t||| | S Nr%   )r2   r5   r3   r<   r   r   )r!   r-   r&   r   r   r   r   r   rA   r  s
   zRescaling.callc                 C      |S rC   r   rH   r   r   r   rJ   y     zRescaling.compute_output_shapec                    rm   )N)r   r   )r   r   r   rL   rM   rN   rO   rP   r#   r   r   rL   |  rn   zRescaling.get_config)r   rS   r   r   r#   r   r   H  s    r   
horizontalverticalhorizontal_and_verticalzkeras.layers.RandomFlipz2keras.layers.experimental.preprocessing.RandomFlipc                       sD   e Zd ZdZedf fdd	ZdddZdd	 Z fd
dZ  Z	S )
RandomFlipa  A preprocessing layer which randomly flips images during training.

    This layer will flip the images horizontally and or vertically based on the
    `mode` attribute. During inference time, the output will be identical to
    input. Call the layer with `training=True` to flip the input.

    Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
    of integer or floating point dtype.
    By default, the layer will output floats.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Args:
        mode: String indicating which flip mode to use. Can be `"horizontal"`,
            `"vertical"`, or `"horizontal_and_vertical"`. `"horizontal"` is a
            left-right flip and `"vertical"` is a top-bottom flip. Defaults to
            `"horizontal_and_vertical"`
        seed: Integer. Used to create a random seed.
    Nc                    s   t  jd|dd| tjdd || _|tkr#d| _d| _	n!|t
kr.d| _d| _	n|tkr9d| _d| _	ntd| j d| || _d S )NTrr   rs   r   FzRandomFlip layer z# received an unknown mode argument r   )r   r   r   r   r   r    mode
HORIZONTALr   r   VERTICALHORIZONTAL_AND_VERTICAL
ValueErrornamerr   )r!   r   rr   r"   r#   r   r   r     s(   

zRandomFlip.__init__Tc                    (   t | j} fdd}|r||S |S )Nc                    s   | } j r! j }|d urtjj||d}n
tj| j } jr@ j }|d ur6tjj	||d}n
tj
| j }|| j |S )Nrr   )r   ru   make_seed_for_stateless_opr3   r:    stateless_random_flip_left_rightrandom_flip_left_rightmake_legacy_seedr   stateless_random_flip_up_downrandom_flip_up_down	set_shaper7   )r-   flipped_outputsrr   r!   r   r   random_flipped_inputs  s.   

z.RandomFlip.call.<locals>.random_flipped_inputsr5   r2   )r!   r-   r{   r   r   r   r   rA     s
   zRandomFlip.callc                 C   r   rC   r   rH   r   r   r   rJ     r   zRandomFlip.compute_output_shapec                    rm   )N)r   rr   )r   rr   r   rL   rM   rN   rO   rP   r#   r   r   rL     rn   zRandomFlip.get_configr~   )
rT   rU   rV   rW   r   r   rA   rJ   rL   rX   r   r   r#   r   r     s    
#r   zkeras.layers.RandomTranslationz9keras.layers.experimental.preprocessing.RandomTranslationc                       H   e Zd ZdZ				d fdd	Zdd	d
Zdd Z fddZ  ZS )RandomTranslationa  A preprocessing layer which randomly translates images during training.

    This layer will apply random translations to each image during training,
    filling empty space according to `fill_mode`.

    Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
    of integer or floating point dtype. By default, the layer will output
    floats.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Args:
      height_factor: a float represented as fraction of value, or a tuple of
          size 2 representing lower and upper bound for shifting vertically. A
          negative value means shifting image up, while a positive value means
          shifting image down. When represented as a single positive float, this
          value is used for both the upper and lower bound. For instance,
          `height_factor=(-0.2, 0.3)` results in an output shifted by a random
          amount in the range `[-20%, +30%]`.  `height_factor=0.2` results in an
          output height shifted by a random amount in the range `[-20%, +20%]`.
      width_factor: a float represented as fraction of value, or a tuple of size
          2 representing lower and upper bound for shifting horizontally. A
          negative value means shifting image left, while a positive value means
          shifting image right. When represented as a single positive float,
          this value is used for both the upper and lower bound. For instance,
          `width_factor=(-0.2, 0.3)` results in an output shifted left by 20%,
          and shifted right by 30%. `width_factor=0.2` results
          in an output height shifted left or right by 20%.
      fill_mode: Points outside the boundaries of the input are filled according
          to the given mode
          (one of `{"constant", "reflect", "wrap", "nearest"}`).
          - *reflect*: `(d c b a | a b c d | d c b a)` The input is extended by
              reflecting about the edge of the last pixel.
          - *constant*: `(k k k k | a b c d | k k k k)` The input is extended by
              filling all values beyond the edge with the same constant value
              k = 0.
          - *wrap*: `(a b c d | a b c d | a b c d)` The input is extended by
              wrapping around to the opposite edge.
          - *nearest*: `(a a a a | a b c d | d d d d)` The input is extended by
              the nearest pixel.
      interpolation: Interpolation mode. Supported values: `"nearest"`,
          `"bilinear"`.
      seed: Integer. Used to create a random seed.
      fill_value: a float represents the value to be filled outside the
          boundaries when `fill_mode="constant"`.

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`,  in `"channels_last"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`,  in `"channels_last"` format.
    r   r   Nr   c                    sH  t jdd t jd|dd| || _t|tt	fr*|d | _
|d | _n| | _
|| _| j| j
k r>td| t| j
dksLt| jdkrStd| || _t|tt	frh|d | _|d | _n| | _|| _| j| jk r|td	| t| jdkst| jdkrtd
| t|| || _|| _|| _|| _d S )Nr   Tr   r   rt   zC`height_factor` cannot have upper bound less than lower bound, got       ?S`height_factor` argument must have values between [-1, 1]. Received: height_factor=zB`width_factor` cannot have upper bound less than lower bound, got z5`width_factor` must have values between [-1, 1], got r   )r   r   r   r    r   r   height_factor
isinstancetuplerN   height_lowerheight_upperr   abswidth_factorwidth_lowerwidth_upperr   r   
fill_valuer   rr   r!   r   r   r   r   rr   r   r"   r#   r   r   r   1  s\   




zRandomTranslation.__init__Tc                    r   )Nc                    s   | j }| j jdk}|rt| d} t | }|d }t|t tj}t|t tj} jj	|dg j
 jtjd}|| } jj	|dg j jtjd}|| }tjtj||gddtjd}	t| t|	 j j jd}
|rwt|
d}
|
| |
S )z"Translated inputs with random ops.   r   rt   )r7   minvalmaxvalr&   axisr%   )r   r   r   )r7   rankr3   expand_dimsr<   rF   r4   rG   ru   rv   r   r   r   r   concat	transformget_translation_matrixr   r   r   squeezer   )r-   original_shape	unbatchedinputs_shape
batch_sizeimg_hdimg_wdheight_translatewidth_translatetranslationsoutputr   r   r   random_translated_inputsm  sJ   

z8RandomTranslation.call.<locals>.random_translated_inputsr   )r!   r-   r{   r   r   r   r   rA   j  s
   ,zRandomTranslation.callc                 C   r   rC   r   rH   r   r   r   rJ     r   z&RandomTranslation.compute_output_shapec                    D   | j | j| j| j| j| jd}t  }tt	|
 t	|
  S N)r   r   r   r   r   rr   r   r   r   r   r   rr   r   rL   rM   rN   rO   rP   r#   r   r   rL        
zRandomTranslation.get_configr   r   Nr   r~   rS   r   r   r#   r   r     s    <
94r   c                 C   s   t |pdP t| d }tjt|dftjt|dftj| ddddf  t|dftjt|dftj| ddddf  t|dftjgddW  d   S 1 sZw   Y  dS )ay  Returns projective transform(s) for the given translation(s).

    Args:
        translations: A matrix of 2-element lists representing `[dx, dy]`
            to translate for each image (for a batch of images).
        name: The name of the op.

    Returns:
        A tensor of shape `(num_images, 8)` projective transforms
            which can be given to `transform`.
    translation_matrixr   rt   Nr[   valuesr   )r   
name_scoper3   r7   r   onesr4   zeros)r   r   num_translationsr   r   r   r     s   	$r   r   r   r   c              	   C   s   t |pdU |du r$t| dd }t s$t|}|dur$|}tj|tjdd}| 	dgs<t
d| tj|tjd	d}tjj| |||| | d
W  d   S 1 s_w   Y  dS )a	  Applies the given transform(s) to the image(s).

    Args:
        images: A tensor of shape
            `(num_images, num_rows, num_columns, num_channels)` (NHWC).
            The rank must be statically known
            (the shape is not `TensorShape(None)`).
        transforms: Projective transform matrix/matrices.
            A vector of length 8 or tensor of size N x 8.
            If one row of transforms is [a0, a1, a2, b0, b1, b2,
            c0, c1], then it maps the *output* point `(x, y)`
            to a transformed *input* point
            `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`, where
            `k = c0 x + c1 y + 1`. The transforms are *inverted* compared to the
            transform mapping input points to output points.
            Note that gradients are not backpropagated
            into transformation parameters.
        fill_mode: Points outside the boundaries of the input are filled
            according to the given mode
            (one of `{"constant", "reflect", "wrap", "nearest"}`).
        fill_value: a float represents the value to be filled outside
            the boundaries when `fill_mode="constant"`.
        interpolation: Interpolation mode. Supported values: `"nearest"`,
            `"bilinear"`.
        output_shape: Output dimension after the transform, `[height, width]`.
            If `None`, output is the same size as input image.
        name: The name of the op.

    Fill mode behavior for each valid value is as follows:

    - `"reflect"`: `(d c b a | a b c d | d c b a)`
    The input is extended by reflecting about the edge of the last pixel.

    - `"constant"`: `(k k k k | a b c d | k k k k)`
    The input is extended by filling all
    values beyond the edge with the same constant value k = 0.

    - `"wrap"`: `(a b c d | a b c d | a b c d)`
    The input is extended by wrapping around to the opposite edge.

    - `"nearest"`: `(a a a a | a b c d | d d d d)`
    The input is extended by the nearest pixel.

    Input shape:
        4D tensor with shape: `(samples, height, width, channels)`,
            in `"channels_last"` format.

    Output shape:
        4D tensor with shape: `(samples, height, width, channels)`,
            in `"channels_last"` format.

    Returns:
        Image(s) with the same type and shape as `images`, with the given
        transform(s) applied. Transformed coordinates outside of the input image
        will be filled with zeros.
    r   Nrt   r   output_shape)r   r[   zaoutput_shape must be a 1-D Tensor of 2 elements: new_height, new_width, instead got output_shape=r   )imagesr   r   
transformsr   r   )r   r   r3   r7   executing_eagerlyget_static_valueconvert_to_tensorr\   	get_shapeis_compatible_withr   r4   raw_opsImageProjectiveTransformV3upper)r   r   r   r   r   r   r   output_shape_valuer   r   r   r     s8   A
$r   c                 C   s,  t |pd |d t| |d  t| |d    d }|d t| |d  t| |d    d }t| d }tjt| dddf t| dddf  |dddf t| dddf t| dddf |dddf t|dftjgddW  d   S 1 sw   Y  dS )a  Returns projective transform(s) for the given angle(s).

    Args:
        angles: A scalar angle to rotate all images by,
            or (for batches of images) a vector with an angle to
            rotate each image in the batch. The rank must be
            statically known (the shape is not `TensorShape(None)`).
        image_height: Height of the image(s) to be transformed.
        image_width: Width of the image(s) to be transformed.
        name: The name of the op.

    Returns:
        A tensor of shape (num_images, 8).
            Projective transforms which can be given
            to operation `image_projective_transform_v2`.
            If one row of transforms is
            [a0, a1, a2, b0, b1, b2, c0, c1], then it maps the *output* point
            `(x, y)` to a transformed *input* point
            `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`,
            where `k = c0 x + c1 y + 1`.
    rotation_matrixrt          @r   Nr[   r   )	r   r   r3   cossinr7   r   r   r4   )anglesimage_heightimage_widthr   x_offsety_offset
num_anglesr   r   r   get_rotation_matrix2  s8   	$r   zkeras.layers.RandomRotationz6keras.layers.experimental.preprocessing.RandomRotationc                       r   )RandomRotationa
  A preprocessing layer which randomly rotates images during training.

    This layer will apply random rotations to each image, filling empty space
    according to `fill_mode`.

    By default, random rotations are only applied during training.
    At inference time, the layer does nothing. If you need to apply random
    rotations at inference time, set `training` to True when calling the layer.

    Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
    of integer or floating point dtype.
    By default, the layer will output floats.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format

    Args:
        factor: a float represented as fraction of 2 Pi, or a tuple of size 2
            representing lower and upper bound for rotating clockwise and
            counter-clockwise. A positive values means rotating
            counter clock-wise,
            while a negative value means clock-wise.
            When represented as a single
            float, this value is used for both the upper and lower bound.
            For instance, `factor=(-0.2, 0.3)`
            results in an output rotation by a random
            amount in the range `[-20% * 2pi, 30% * 2pi]`.
            `factor=0.2` results in an
            output rotating by a random amount
            in the range `[-20% * 2pi, 20% * 2pi]`.
        fill_mode: Points outside the boundaries of the input are filled
            according to the given mode
            (one of `{"constant", "reflect", "wrap", "nearest"}`).
            - *reflect*: `(d c b a | a b c d | d c b a)`
                The input is extended by reflecting about
                the edge of the last pixel.
            - *constant*: `(k k k k | a b c d | k k k k)`
                The input is extended by
                filling all values beyond the edge with
                the same constant value k = 0.
            - *wrap*: `(a b c d | a b c d | a b c d)` The input is extended by
                wrapping around to the opposite edge.
            - *nearest*: `(a a a a | a b c d | d d d d)`
                The input is extended by the nearest pixel.
        interpolation: Interpolation mode. Supported values: `"nearest"`,
            `"bilinear"`.
        seed: Integer. Used to create a random seed.
        fill_value: a float represents the value to be filled outside
            the boundaries when `fill_mode="constant"`.
    r   r   Nr   c                    s   t jdd t jd|dd| || _t|tt	fr*|d | _
|d | _n| | _
|| _| j| j
k r>td| t|| || _|| _|| _|| _d S )Nr   Tr   r   rt   zA`factor` argument cannot have a negative value. Received: factor=r   )r   r   r   r    r   r   factorr   r   rN   lowerr   r   r   r   r   r   rr   )r!   r   r   r   rr   r   r"   r#   r   r   r     s*   	


zRandomRotation.__init__Tc                    r   )Nc                    s   | j }| j jdk}|rt| d} t | }|d }t|t tj}t|t tj} jd t	j
 } jd t	j
 } jj|g||d}	t| t|	|| j j jd}
|r^t|
d}
|
| |
S )zRotated inputs with random ops.r   r   r   r7   r   r   r   r   r   )r7   r   r3   r   r<   rF   r4   rG   r   nppir   ru   rv   r   r   r   r   r   r   r   )r-   r   r   r   r   r   r   	min_angle	max_angler   r   r   r   r   random_rotated_inputs  s0   


z2RandomRotation.call.<locals>.random_rotated_inputsr   )r!   r-   r{   r   r   r   r   rA     s
   zRandomRotation.callc                 C   r   rC   r   rH   r   r   r   rJ     r   z#RandomRotation.compute_output_shapec                    s@   | j | j| j| j| jd}t  }tt|	 t|	  S )N)r   r   r   r   rr   )
r   r   r   r   rr   r   rL   rM   rN   rO   rP   r#   r   r   rL     s   
zRandomRotation.get_configr   r~   rS   r   r   r#   r   r   f  s    >
&r   zkeras.layers.RandomZoomz2keras.layers.experimental.preprocessing.RandomZoomc                       sJ   e Zd ZdZ					d fdd	Zdd	d
Zdd Z fddZ  ZS )
RandomZoomaX  A preprocessing layer which randomly zooms images during training.

    This layer will randomly zoom in or out on each axis of an image
    independently, filling empty space according to `fill_mode`.

    Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
    of integer or floating point dtype.
    By default, the layer will output floats.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Args:
        height_factor: a float represented as fraction of value,
            or a tuple of size 2 representing lower and upper bound
            for zooming vertically. When represented as a single float,
            this value is used for both the upper and
            lower bound. A positive value means zooming out,
            while a negative value
            means zooming in. For instance, `height_factor=(0.2, 0.3)`
            result in an output zoomed out by a random amount
            in the range `[+20%, +30%]`.
            `height_factor=(-0.3, -0.2)` result in an output zoomed
            in by a random amount in the range `[+20%, +30%]`.
        width_factor: a float represented as fraction of value,
            or a tuple of size 2 representing lower and upper bound
            for zooming horizontally. When
            represented as a single float, this value is used
            for both the upper and
            lower bound. For instance, `width_factor=(0.2, 0.3)`
            result in an output
            zooming out between 20% to 30%.
            `width_factor=(-0.3, -0.2)` result in an
            output zooming in between 20% to 30%. `None` means
            i.e., zooming vertical and horizontal directions
            by preserving the aspect ratio. Defaults to `None`.
        fill_mode: Points outside the boundaries of the input are
            filled according to the given mode
            (one of `{"constant", "reflect", "wrap", "nearest"}`).
            - *reflect*: `(d c b a | a b c d | d c b a)`
                The input is extended by reflecting about
                the edge of the last pixel.
            - *constant*: `(k k k k | a b c d | k k k k)`
                The input is extended by filling all values beyond
                the edge with the same constant value k = 0.
            - *wrap*: `(a b c d | a b c d | a b c d)` The input is extended by
                wrapping around to the opposite edge.
            - *nearest*: `(a a a a | a b c d | d d d d)`
                The input is extended by the nearest pixel.
        interpolation: Interpolation mode. Supported values: `"nearest"`,
            `"bilinear"`.
        seed: Integer. Used to create a random seed.
        fill_value: a float represents the value to be filled outside
            the boundaries when `fill_mode="constant"`.

    Example:

    >>> input_img = np.random.random((32, 224, 224, 3))
    >>> layer = tf.keras.layers.RandomZoom(.5, .2)
    >>> out_img = layer(input_img)
    >>> out_img.shape
    TensorShape([32, 224, 224, 3])

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.
    Nr   r   r   c                    s  t jdd t jd
|dd| || _t|tt	fr*|d | _
|d | _n| | _
|| _t| j
dks?t| jdkrFtd| || _|d urwt|tt	fr_|d | _|d | _n| | _|| _| jdk sp| jdk rwtd	| t|| || _|| _|| _|| _d S )Nr   Tr   r   rt   r   r         zP`width_factor` argument must have values larger than -1. Received: width_factor=r   )r   r   r   r    r   r   r   r   r   rN   r   r   r   r   r   r   r   r   r   r   r   rr   r   r#   r   r   r   I  sD   




zRandomZoom.__init__Tc                    r   )Nc                    s  | j }| j jdk}|rt| d} t | }|d }t|t tj}t|t tj} jj	|dgd j
 d j d} jdurT jj	|dgd j d j d}n|}tjtj||gddtjd}	t| t|	|| j j jd	}
|r}t|
d}
|
| |
S )
zZoomed inputs with random ops.r   r   rt   r   r   Nr   r%   r   )r7   r   r3   r   r<   rF   r4   rG   ru   rv   r   r   r   r   r   r   r   get_zoom_matrixr   r   r   r   r   )r-   r   r   r   r   r   r   height_zoom
width_zoomzoomsr   r   r   r   random_zoomed_inputs~  sD   



z-RandomZoom.call.<locals>.random_zoomed_inputsr   )r!   r-   r{   r   r   r   r   rA   {  s
   )zRandomZoom.callc                 C   r   rC   r   rH   r   r   r   rJ     r   zRandomZoom.compute_output_shapec                    r   r   r   rP   r#   r   r   rL     r   zRandomZoom.get_config)Nr   r   Nr   r~   rS   r   r   r#   r   r     s    K
21r   c                 C   s   t |pdb t| d }|d d d| ddddf   }|d d d| ddddf   }tj| ddddf t|dftj|t|dftj| ddddf |t|dftjgddW  d   S 1 slw   Y  dS )	a#  Returns projective transform(s) for the given zoom(s).

    Args:
        zooms: A matrix of 2-element lists representing `[zx, zy]`
            to zoom for each image (for a batch of images).
        image_height: Height of the image(s) to be transformed.
        image_width: Width of the image(s) to be transformed.
        name: The name of the op.

    Returns:
        A tensor of shape `(num_images, 8)`. Projective transforms which can be
            given to operation `image_projective_transform_v2`.
            If one row of transforms is
            `[a0, a1, a2, b0, b1, b2, c0, c1]`, then it maps the *output* point
            `(x, y)` to a transformed *input* point
            `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`,
            where `k = c0 x + c1 y + 1`.
    zoom_matrixr   r   r   Nrt   r[   r   )r   r   r3   r7   r   r   r4   )r   r   r   r   	num_zoomsr   r   r   r   r   r     s    ""	$r   zkeras.layers.RandomContrastz6keras.layers.experimental.preprocessing.RandomContrastc                       rp   )RandomContrasta  A preprocessing layer which randomly adjusts contrast during training.

    This layer will randomly adjust the contrast of an image or images
    by a random factor. Contrast is adjusted independently
    for each channel of each image during training.

    For each channel, this layer computes the mean of the image pixels in the
    channel and then adjusts each component `x` of each pixel to
    `(x - mean) * contrast_factor + mean`.

    Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
    in integer or floating point dtype.
    By default, the layer will output floats.
    The output value will be clipped to the range `[0, 255]`, the valid
    range of RGB colors.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Args:
        factor: a positive float represented as fraction of value, or a tuple of
            size 2 representing lower and upper bound.
            When represented as a single float, lower = upper.
            The contrast factor will be randomly picked between
            `[1.0 - lower, 1.0 + upper]`. For any pixel x in the channel,
            the output will be `(x - mean) * factor + mean`
            where `mean` is the mean value of the channel.
        seed: Integer. Used to create a random seed.
    Nc                    s   t jdd t jd	|dd| || _t|tt	fr*|d | _
|d | _n| | _
| _| j
dk s?| jdk s?| j
dkrFtd| || _d S )
Nr   Tr   r   rt   r   r   zX`factor` argument cannot have negative values or values greater than 1.Received: factor=r   )r   r   r   r    r   r   r   r   r   rN   r   r   r   rr   )r!   r   rr   r"   r#   r   r   r     s    

zRandomContrast.__init__Tc                    r   )Nc                    sx    j  }|d urtjj| d j d j |d}ntjj| d j d j  j  d}t	|dd}|
| j |S )Nr   r   r      )ru   r   r3   r:   stateless_random_contrastr   r   random_contrastr   clip_by_valuer   r7   )r-   rr   r   r   r   r   random_contrasted_inputs)  s   
z5RandomContrast.call.<locals>.random_contrasted_inputsr   )r!   r-   r{   r   r   r   r   rA   &  s
   zRandomContrast.callc                 C   r   rC   r   rH   r   r   r   rJ   ?  r   z#RandomContrast.compute_output_shapec                    rm   )N)r   rr   )r   rr   r   rL   rM   rN   rO   rP   r#   r   r   rL   B  rn   zRandomContrast.get_configrC   r~   rS   r   r   r#   r   r     s    &
r   zkeras.layers.RandomBrightnessc                       s`   e Zd ZdZdZdZd fdd	Zdd	 Zd
d Zdd Z	dddZ
dd Z fddZ  ZS )RandomBrightnessap
  A preprocessing layer which randomly adjusts brightness during training.

    This layer will randomly increase/reduce the brightness for the input RGB
    images. At inference time, the output will be identical to the input.
    Call the layer with `training=True` to adjust the brightness of the input.

    Note that different brightness adjustment factors
    will be apply to each the images in the batch.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Args:
        factor: Float or a list/tuple of 2 floats between -1.0 and 1.0. The
            factor is used to determine the lower bound and upper bound of the
            brightness adjustment. A float value will be chosen randomly between
            the limits. When -1.0 is chosen, the output image will be black, and
            when 1.0 is chosen, the image will be fully white.
            When only one float is provided, eg, 0.2,
            then -0.2 will be used for lower bound and 0.2
            will be used for upper bound.
        value_range: Optional list/tuple of 2 floats
            for the lower and upper limit
            of the values of the input data.
            To make no change, use [0.0, 1.0], e.g., if the image input
            has been scaled before this layer. Defaults to [0.0, 255.0].
            The brightness adjustment will be scaled to this range, and the
            output values will be clipped to this range.
        seed: optional integer, for fixed RNG behavior.

    Inputs: 3D (HWC) or 4D (NHWC) tensor, with float or int dtype. Input pixel
        values can be of any range (e.g. `[0., 1.)` or `[0, 255]`)

    Output: 3D (HWC) or 4D (NHWC) tensor with brightness adjusted based on the
        `factor`. By default, the layer will output floats.
        The output value will be clipped to the range `[0, 255]`,
        the valid range of RGB colors, and
        rescaled based on the `value_range` if needed.

    Sample usage:

    ```python
    random_bright = tf.keras.layers.RandomBrightness(factor=0.2)

    # An image with shape [2, 2, 3]
    image = [[[1, 2, 3], [4 ,5 ,6]], [[7, 8, 9], [10, 11, 12]]]

    # Assume we randomly select the factor to be 0.1, then it will apply
    # 0.1 * 255 to all the channel
    output = random_bright(image, training=True)

    # output will be int64 with 25.5 added to each channel and round down.
    tf.Tensor([[[26.5, 27.5, 28.5]
                [29.5, 30.5, 31.5]]
               [[32.5, 33.5, 34.5]
                [35.5, 36.5, 37.5]]],
              shape=(2, 2, 3), dtype=int64)
    ```
    z^The `factor` argument should be a number (or a list of two numbers) in the range [-1.0, 1.0]. z<The `value_range` argument should be a list of two numbers. r   r   Nc                    sH   t jdd t jd|dd| | | | | || _d S )Nr   Tr   r   )	r   r   r   r    r   r   _set_factor_set_value_range_seed)r!   r   value_rangerr   r"   r#   r   r   r     s   


zRandomBrightness.__init__c                 C   sP   t |ttfst| jd|  t|dkr!t| jd|  t|| _d S )NGot r[   )r   r   rN   r   _VALUE_RANGE_VALIDATION_ERRORlensorted_value_range)r!   r  r   r   r   r    s   z!RandomBrightness._set_value_rangec                 C   s   t |ttfr,t|dkrt| jd|  | |d  | |d  t|| _d S t |t	t
frD| | t|}| |g| _d S t| jd|  )Nr[   r  r   rt   )r   r   rN   r  r   _FACTOR_VALIDATION_ERROR_check_factor_ranger  _factorintfloatr   )r!   r   r   r   r   r    s   
zRandomBrightness._set_factorc                 C   s(   |dks|dk rt | jd|  d S )Nr   r   r  )r   r
  )r!   input_numberr   r   r   r    s
   z$RandomBrightness._check_factor_rangeTc                 C   s    t || jd}|r| |S |S r   )r5   r2   _brightness_adjust)r!   r-   r{   r   r   r   rA     s   
zRandomBrightness.callc                 C   s   |j j}|dkrd}n|dkrt |d dddg}ntd|j  | jj|| jd | jd d}|| jd | jd   }t||j	}||7 }t
|| jd | jd S )Nr   )rt   rt   rt      r   rt   z?Expected the input image to be rank 3 or 4. Got inputs.shape = r   )r7   r   r3   r   ru   rv   r  r	  r<   r&   r   )r!   r   r   rgb_delta_shape	rgb_deltar   r   r   r    s*   z#RandomBrightness._brightness_adjustc                    r|   )N)r   r  rr   )r  r	  r  r   rL   rM   rN   rO   rP   r#   r   r   rL     r}   zRandomBrightness.get_config)r   Nr~   )rT   rU   rV   rW   r
  r  r   r  r  r  rA   r  rL   rX   r   r   r#   r   r   K  s    =	
r   zkeras.layers.RandomHeightz4keras.layers.experimental.preprocessing.RandomHeightc                       @   e Zd ZdZd fdd	ZdddZd	d
 Z fddZ  ZS )RandomHeightas  A preprocessing layer which randomly varies image height during training.

    This layer adjusts the height of a batch of images by a random factor.
    The input should be a 3D (unbatched) or 4D (batched) tensor in the
    `"channels_last"` image data format. Input pixel values can be of any range
    (e.g. `[0., 1.)` or `[0, 255]`) and of integer or floating point dtype. By
    default, the layer will output floats.


    By default, this layer is inactive during inference.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Args:
        factor: A positive float (fraction of original height),
            or a tuple of size 2 representing lower and upper bound
            for resizing vertically. When represented as a single float,
            this value is used for both the upper and
            lower bound. For instance, `factor=(0.2, 0.3)` results
            in an output with
            height changed by a random amount in the range `[20%, 30%]`.
            `factor=(-0.2, 0.3)` results in an output with height
            changed by a random amount in the range `[-20%, +30%]`.
            `factor=0.2` results in an output with
            height changed by a random amount in the range `[-20%, +20%]`.
        interpolation: String, the interpolation method.
            Supports `"bilinear"`, `"nearest"`, `"bicubic"`, `"area"`,
            `"lanczos3"`, `"lanczos5"`, `"gaussian"`, `"mitchellcubic"`.
            Defaults to `"bilinear"`.
        seed: Integer. Used to create a random seed.

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., random_height, width, channels)`.
    r   Nc                       t jdd t jd	|dd| || _t|tt	fr*|d | _
|d | _n| | _
|| _| j| j
k r>td| | j
dk sH| jdk rOtd| || _t|| _|| _d S )
Nr  Tr   r   rt   z[`factor` argument cannot have an upper bound lesser than the lower bound. Received: factor=r   D`factor` argument must have values larger than -1. Received: factor=r   )r   r   r   r    r   r   r   r   r   rN   r   r   r   r   r   r   r   rr   r!   r   r   rr   r"   r#   r   r   r     s6   

zRandomHeight.__init__Tc                    $   t |} fdd}|r||S |S )Nc           	         s   t | }t |t t j}|t } jjg d j d j	 d}t || t j
}t ||g}t jj| | jd}t | j}| j }d|t< || |S )z'Inputs height-adjusted with random ops.r   r   r   r'   r1   N)r3   r7   r<   rF   r4   rG   ru   rv   r   r   r\   stackr:   r;   r   r2   rE   r   )	r-   r   r   r   r   adjusted_heightadjusted_sizer   r   r   r   r   random_height_inputs4  s(   


z/RandomHeight.call.<locals>.random_height_inputsr5   )r!   r-   r{   r  r   r   r   rA   1  
   zRandomHeight.callc                 C       t | }d |t< t |S rC   )r3   r6   rE   rF   rH   r   r   r   rJ   Q     
z!RandomHeight.compute_output_shapec                    r|   N)r   r   rr   r   r   rr   r   rL   rM   rN   rO   rP   r#   r   r   rL   V  r}   zRandomHeight.get_configr   Nr~   rS   r   r   r#   r   r    s    )
 r  zkeras.layers.RandomWidthz3keras.layers.experimental.preprocessing.RandomWidthc                       r  )RandomWidtha  A preprocessing layer which randomly varies image width during training.

    This layer will randomly adjusts the width of a batch of images of a
    batch of images by a random factor. The input should be a 3D (unbatched) or
    4D (batched) tensor in the `"channels_last"` image data format. Input pixel
    values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and of integer or
    floating point dtype. By default, the layer will output floats.

    By default, this layer is inactive during inference.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Args:
        factor: A positive float (fraction of original width),
            or a tuple of size 2 representing lower and upper bound
            for resizing horizontally. When represented as a single float,
            this value is used for both the upper and
            lower bound. For instance, `factor=(0.2, 0.3)`
            results in an output with
            width changed by a random amount in the range `[20%, 30%]`.
            `factor=(-0.2, 0.3)` results in an output with width changed
            by a random amount in the range `[-20%, +30%]`.
            `factor=0.2` results in an output with width changed
            by a random amount in the range `[-20%, +20%]`.
        interpolation: String, the interpolation method.
            Supports `"bilinear"`, `"nearest"`, `"bicubic"`, `"area"`,
            `"lanczos3"`, `"lanczos5"`, `"gaussian"`, `"mitchellcubic"`.
            Defaults to `bilinear`.
        seed: Integer. Used to create a random seed.

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, random_width, channels)`.
    r   Nc                    r  )
Nr&  Tr   r   rt   zY`factor` argument cannot have an upper bound less than the lower bound. Received: factor=r   r  r   )r   r   r   r    r   r   r   r   r   rN   r   r   r   r   r   r   r   rr   r  r#   r   r   r     s6   

zRandomWidth.__init__Tc                    r  )Nc           	         s   t | }|t }t |t t j} jjg d j d j	 d}t || t j
}t ||g}t jj| | jd}t | j}| j }d|t< || |S )z&Inputs width-adjusted with random ops.r   r   r  N)r3   r7   rF   r<   rG   r4   ru   rv   r   r   r\   r  r:   r;   r   r2   rE   r   )	r-   r   r   r   r   adjusted_widthr  r   r   r   r   r   random_width_inputs  s(   


z-RandomWidth.call.<locals>.random_width_inputsr  )r!   r-   r{   r(  r   r   r   rA     r   zRandomWidth.callc                 C   r!  rC   )r3   r6   rE   rG   rH   r   r   r   rJ     r"  z RandomWidth.compute_output_shapec                    r|   r#  r$  rP   r#   r   r   rL     r}   zRandomWidth.get_configr%  r~   rS   r   r   r#   r   r&  `  s    (
 r&  c                 C   s0   t | trtdt|  dtj| |d} | S )NzhThis layer can only process a tensor representing an image or a batch of images. Received: type(inputs)=z.If you need to pass a dict containing images, labels, and bounding boxes, you should instead use the preprocessing and augmentation layers from `keras_cv.layers`. See docs at https://keras.io/api/keras_cv/layers/r%   )r   rM   r   typeutilsensure_tensor)r-   r&   r   r   r   r5     s   
	r5   rC   )r   r   r   NN)-rW   numpyr   tensorflow.compat.v2compatv2r3    tensorflow.python.util.tf_exportr   	keras.srcr   keras.src.enginer   r   keras.src.layers.preprocessingr   r*  keras.src.utilsr   r   rF   rG   r   Layerr   rY   BaseRandomLayerrq   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r&  r5   r   r   r   r   <module>   s   fN[9d 
7%

b4  
=+
_ vt