
    ijQ                    v   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  G d d	e	      Z ed
      dSd       Z G d de	      Z ed      dSd       Z G d de	      Z ed      dSd       Z G d de	      Z ed      	 	 	 	 	 	 	 dTd       Z	 	 	 	 	 	 	 dTdZ G d de	      Z ed      	 	 	 	 dUd       Z G d de	      Z ed       	 	 	 	 dVd!       Z	 	 	 	 dVd"Z	 	 	 	 dVd#Z	 	 	 	 dVd$Z ed%      	 	 	 	 dVd&       Z G d' d(e	      Z ed)      	 dWd*       Zd+ Zd, Z d- Z! G d. d/e	      Z" ed0      	 	 	 	 	 	 	 dXd1       Z#	 dSd2Z$ G d3 d4e	      Z% ed5      	 	 	 	 	 	 	 dXd6       Z&	 dSd7Z' G d8 d9e	      Z( ed:      	 	 	 dYd;       Z) G d< d=e	      Z* ed>      	 dZd?       Z+ G d@ dAe	      Z, edB      	 	 	 	 	 	 	 d[dC       Z- G dD dEe	      Z. edF      	 d\dG       Z/ G dH dIe	      Z0 edJ      dSdK       Z1 G dL dMe	      Z2 edN      	 	 	 	 	 	 d]dO       Z3	 	 	 	 	 	 d]dPZ4dQ Z5dR Z6y)^    )backend)ops)keras_export)KerasTensor)any_symbolic_tensors)	Operation)compute_conv_output_shapec                   2     e Zd Zddd fdZd Zd Z xZS )RGBToGrayscaleNnamec                Z    t         |   |       t        j                  |      | _        y Nr   super__init__r   standardize_data_formatdata_formatselfr   r   	__class__s      h/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/ops/image.pyr   zRGBToGrayscale.__init__   &    d#"::;G    c                 X    t         j                  j                  || j                        S Nr   )r   imagergb_to_grayscaler   r   imagess     r   callzRGBToGrayscale.call   s)    }}-- 0 0 . 
 	
r   c                    t        |j                        }t        |      dvrt        d|       | j                  dk(  rdnd}||   }||dvrt        dt        |             d||<   t        ||j                  	      S )
N      hInvalid images rank: expected rank 3 (single image) or rank 4 (batch of images). Received: images.shape=channels_last)   r%   zaInvalid channel size: expected 3 (RGB) or 1 (Grayscale). Received input with shape: images.shape=r+   shapedtype)listr-   len
ValueErrorr   tupler   r.   )r   r!   images_shapechannels_axischannelss        r   compute_output_specz"RGBToGrayscale.compute_output_spec   s    FLL)|F***69 
 #../Ar.HF$:;;@;N:OQ  '(]#V\\BBr   N__name__
__module____qualname__r   r"   r6   __classcell__r   s   @r   r   r   
   s    H H

Cr   r   z keras.ops.image.rgb_to_grayscaleNc                     t        | f      rt        |      j                  |       S t        j                  j                  | |      S )a  Convert RGB images to grayscale.

    This function converts RGB images to grayscale images. It supports both
    3D and 4D tensors.

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        Grayscale image or batch of grayscale images.

    Examples:

    >>> import numpy as np
    >>> from keras import ops
    >>> x = np.random.random((2, 4, 4, 3))
    >>> y = ops.image.rgb_to_grayscale(x)
    >>> y.shape
    (2, 4, 4, 1)

    >>> x = np.random.random((4, 4, 3)) # Single RGB image
    >>> y = ops.image.rgb_to_grayscale(x)
    >>> y.shape
    (4, 4, 1)

    >>> x = np.random.random((2, 3, 4, 4))
    >>> y = ops.image.rgb_to_grayscale(x, data_format="channels_first")
    >>> y.shape
    (2, 1, 4, 4)
    r   )r   r   symbolic_callr   r   r   r!   r   s     r   r   r   '   s?    N VI&+6DDVLL==))&k)JJr   c                   2     e Zd Zddd fdZd Zd Z xZS )RGBToHSVNr   c                Z    t         |   |       t        j                  |      | _        y r   r   r   s      r   r   zRGBToHSV.__init__T   r   r   c                 X    t         j                  j                  || j                        S r   )r   r   
rgb_to_hsvr   r    s     r   r"   zRGBToHSV.callX   "    }}''D<L<L'MMr   c                 J   t        |j                        }|j                  }t        |      dvrt	        d|       t        j                  |      st	        d|       | j                  dk(  rdnd}||   }||dk7  rt	        d| d	      t        ||j                  
      S Nr$   r'   zCInvalid images dtype: expected float dtype. Received: images.dtype=r(   r)   r*   r%   z<Input images must have 3 channels, but received images with z
 channels.r,   	r/   r-   r.   r0   r1   r   is_float_dtyper   r   r   r!   r3   r.   r4   r5   s         r   r6   zRGBToHSV.compute_output_spec[       FLL)|F***69 
 %%e,**/2  #../Ar.HMN*J(  V\\BBr   r7   r8   r=   s   @r   rB   rB   S       H HNCr   rB   zkeras.ops.image.rgb_to_hsvc                     t        | f      rt        |      j                  |       S t        j                  j                  | |      S )a2  Convert RGB images to HSV.

    `images` must be of float dtype, and the output is only well defined if the
    values in `images` are in `[0, 1]`.

    All HSV values are in `[0, 1]`. A hue of `0` corresponds to pure red, `1/3`
    is pure green, and `2/3` is pure blue.

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        HSV image or batch of HSV images.

    Examples:

    >>> import numpy as np
    >>> from keras import ops
    >>> x = np.random.random((2, 4, 4, 3))
    >>> y = ops.image.rgb_to_hsv(x)
    >>> y.shape
    (2, 4, 4, 3)

    >>> x = np.random.random((4, 4, 3)) # Single RGB image
    >>> y = ops.image.rgb_to_hsv(x)
    >>> y.shape
    (4, 4, 3)

    >>> x = np.random.random((2, 3, 4, 4))
    >>> y = ops.image.rgb_to_hsv(x, data_format="channels_first")
    >>> y.shape
    (2, 3, 4, 4)
    r   )r   rB   r?   r   r   rE   r@   s     r   rE   rE   s   s?    T VI&K0>>vFF==##F#DDr   c                   2     e Zd Zddd fdZd Zd Z xZS )HSVToRGBNr   c                Z    t         |   |       t        j                  |      | _        y r   r   r   s      r   r   zHSVToRGB.__init__   r   r   c                 X    t         j                  j                  || j                        S r   )r   r   
hsv_to_rgbr   r    s     r   r"   zHSVToRGB.call   rF   r   c                 J   t        |j                        }|j                  }t        |      dvrt	        d|       t        j                  |      st	        d|       | j                  dk(  rdnd}||   }||dk7  rt	        d| d	      t        ||j                  
      S rH   rI   rK   s         r   r6   zHSVToRGB.compute_output_spec   rL   r   r7   r8   r=   s   @r   rP   rP      rM   r   rP   zkeras.ops.image.hsv_to_rgbc                     t        | f      rt        |      j                  |       S t        j                  j                  | |      S )a  Convert HSV images to RGB.

    `images` must be of float dtype, and the output is only well defined if the
    values in `images` are in `[0, 1]`.

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        RGB image or batch of RGB images.

    Examples:

    >>> import numpy as np
    >>> from keras import ops
    >>> x = np.random.random((2, 4, 4, 3))
    >>> y = ops.image.hsv_to_rgb(x)
    >>> y.shape
    (2, 4, 4, 3)

    >>> x = np.random.random((4, 4, 3)) # Single HSV image
    >>> y = ops.image.hsv_to_rgb(x)
    >>> y.shape
    (4, 4, 3)

    >>> x = np.random.random((2, 3, 4, 4))
    >>> y = ops.image.hsv_to_rgb(x, data_format="channels_first")
    >>> y.shape
    (2, 3, 4, 4)
    r   )r   rP   r?   r   r   rS   r@   s     r   rS   rS      s?    N VI&K0>>vFF==##F#DDr   c                   @     e Zd Z	 	 	 	 	 	 	 ddd fdZd Zd Z xZS )ResizeNr   c	                    t         
|   |	       t        |      | _        || _        || _        || _        || _        || _        || _	        t        j                  |      | _        y r   )r   r   r2   sizeinterpolation	antialiascrop_to_aspect_ratiopad_to_aspect_ratio	fill_mode
fill_valuer   r   r   )r   rY   rZ   r[   r\   r]   r^   r_   r   r   r   s             r   r   zResize.__init__   s`     	d#$K	*"$8!#6 "$"::;Gr   c                     t        || j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  	      S )NrZ   r[   r   r\   r]   r^   r_   )	_resizerY   rZ   r[   r   r\   r]   r^   r_   r    s     r   r"   zResize.call  sR    II,,nn((!%!:!: $ 8 8nn

 
	
r   c                     t        |j                        }t        |      dvrt        d|j                         | j                  dk(  rd\  }}nd\  }}| j
                  d   ||<   | j
                  d   ||<   t        ||j                        S )	Nr$   yInvalid images rank: expected rank 3 (single image) or rank 4 (batch of images). Received input with shape: images.shape=r(   r*   rf   r)   r   r+   r,   )r/   r-   r0   r1   r   rY   r   r.   )r   r!   r3   height_axis
width_axiss        r   r6   zResize.compute_output_spec  s    FLL)|F*  &~/ 
 .&,#K&,#K$(IIaL[!#'99Q<Z V\\BBr   bilinearFFFconstant        Nr8   r=   s   @r   rW   rW      s6     !"!H H.
Cr   rW   zkeras.ops.image.resizec	                    t        |      dk7  rt        d|       |d   dk  s|d   dk  rt        d|       t        | j                        dk  st        | j                        dkD  rt        d| j                         |r|rt        d	      t        | f      r"t	        ||||||||
      j                  |       S t        | ||||||||	      S )a	  Resize images to size using the specified interpolation method.

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        size: Size of output image in `(height, width)` format.
        interpolation: Interpolation method. Available methods are `"nearest"`,
            `"bilinear"`, and `"bicubic"`. Defaults to `"bilinear"`.
        antialias: Whether to use an antialiasing filter when downsampling an
            image. Defaults to `False`.
        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.
        pad_to_aspect_ratio: If `True`, pad the images without aspect
            ratio distortion. When the original aspect ratio differs
            from the target aspect ratio, the output image will be
            evenly padded on the short side.
        fill_mode: When using `pad_to_aspect_ratio=True`, padded areas
            are filled according to the given mode. Only `"constant"` is
            supported at this time
            (fill with constant value, equal to `fill_value`).
        fill_value: Float. Padding value to use when `pad_to_aspect_ratio=True`.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        Resized image or batch of images.

    Examples:

    >>> x = np.random.random((2, 4, 4, 3)) # batch of 2 RGB images
    >>> y = keras.ops.image.resize(x, (2, 2))
    >>> y.shape
    (2, 2, 2, 3)

    >>> x = np.random.random((4, 4, 3)) # single RGB image
    >>> y = keras.ops.image.resize(x, (2, 2))
    >>> y.shape
    (2, 2, 3)

    >>> x = np.random.random((2, 3, 4, 4)) # batch of 2 RGB images
    >>> y = keras.ops.image.resize(x, (2, 2),
    ...     data_format="channels_first")
    >>> y.shape
    (2, 3, 2, 2)
       z<Expected `size` to be a tuple of 2 integers. Received: size=r   r+   z;`size` must have positive height and width. Received: size=r%   r&   rd   zIOnly one of `pad_to_aspect_ratio` & `crop_to_aspect_ratio` can be `True`.ra   rZ   r[   r\   r   r]   r^   r_   )r0   r1   r-   r   rW   r?   rb   )	r!   rY   rZ   r[   r\   r]   r^   r_   r   s	            r   resizerq   $  s   D 4yA~"V%
 	
 Aw!|tAw!|I$P
 	
 6<<1FLL 1A 5"LL>+
 	

 3
 	
 VI&'#!5 3!	
 -
		  #1/
 
r   c	                 0   t         j                  j                  | ||||||||	      }	|	j                  | j                  k(  r|	S t        j                  | j                        rt        j                  |	      }	t        j                  |	| j                        S )Nrp   )r   r   rq   r.   is_int_dtyper   roundsaturate_cast)
r!   rY   rZ   r[   r\   r]   r^   r_   r   resizeds
             r   rb   rb     s     mm""#1/ # 
G }}$ FLL)))G$Wfll33r   c                   :     e Zd Z	 	 	 	 ddd fdZd Zd Z xZS )AffineTransformNr   c                    t         |   |       || _        || _        || _        t        j                  |      | _        y r   )r   r   rZ   r^   r_   r   r   r   )r   rZ   r^   r_   r   r   r   s         r   r   zAffineTransform.__init__  s>     	d#*"$"::;Gr   c                     t         j                  j                  ||| j                  | j                  | j
                  | j                        S )NrZ   r^   r_   r   )r   r   affine_transformrZ   r^   r_   r   r   r!   	transforms      r   r"   zAffineTransform.call  sD    }}--,,nn(( . 
 	
r   c                     t        |j                        dvrt        d|j                         t        |j                        dvrt        d|j                         t        |j                  |j                        S )Nr$   rd   )r+   ro   zInvalid transform rank: expected rank 1 (single transform) or rank 2 (batch of transforms). Received input with shape: transform.shape=r.   r0   r-   r1   r   r.   r}   s      r   r6   z#AffineTransform.compute_output_spec  s~    v||F*  &~/ 
 yv-##,??"35 
 6<<v||<<r   rk   rl   r   Nr8   r=   s   @r   rx   rx     s,     !H H
=r   rx   z keras.ops.image.affine_transformc                     t        | |f      rt        ||||      j                  | |      S t        j                  j                  | |||||      S )a  Applies the given transform(s) to the image(s).

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        transform: Projective transform matrix/matrices. A vector of length 8 or
            tensor of size N x 8. If one row of transform 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 transform is inverted compared to
            the transform mapping input points to output points. Note that
            gradients are not backpropagated into transformation parameters.
            Note that `c0` and `c1` are only effective when using TensorFlow
            backend and will be considered as `0` when using other backends.
        interpolation: Interpolation method. Available methods are `"nearest"`,
            and `"bilinear"`. Defaults to `"bilinear"`.
        fill_mode: Points outside the boundaries of the input are filled
            according to the given mode. Available methods are `"constant"`,
            `"nearest"`, `"wrap"` and `"reflect"`. Defaults to `"constant"`.
            - `"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 specified by
                `fill_value`.
            - `"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.
        fill_value: Value used for points outside the boundaries of the input if
            `fill_mode="constant"`. Defaults to `0`.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        Applied affine transform image or batch of images.

    Examples:

    >>> x = np.random.random((2, 64, 80, 3)) # batch of 2 RGB images
    >>> transform = np.array(
    ...     [
    ...         [1.5, 0, -20, 0, 1.5, -16, 0, 0],  # zoom
    ...         [1, 0, -20, 0, 1, -16, 0, 0],  # translation
    ...     ]
    ... )
    >>> y = keras.ops.image.affine_transform(x, transform)
    >>> y.shape
    (2, 64, 80, 3)

    >>> x = np.random.random((64, 80, 3)) # single RGB image
    >>> transform = np.array([1.0, 0.5, -20, 0.5, 1.0, -16, 0, 0])  # shear
    >>> y = keras.ops.image.affine_transform(x, transform)
    >>> y.shape
    (64, 80, 3)

    >>> x = np.random.random((2, 3, 64, 80)) # batch of 2 RGB images
    >>> transform = np.array(
    ...     [
    ...         [1.5, 0, -20, 0, 1.5, -16, 0, 0],  # zoom
    ...         [1, 0, -20, 0, 1, -16, 0, 0],  # translation
    ...     ]
    ... )
    >>> y = keras.ops.image.affine_transform(x, transform,
    ...     data_format="channels_first")
    >>> y.shape
    (2, 3, 64, 80)
    r{   )r   rx   r?   r   r   r|   )r!   r~   rZ   r^   r_   r   s         r   r|   r|     si    f VY/0'!#	

 -	
*	+ ==))# *  r   c                   @     e Zd Z	 	 	 	 ddd fdZd Zd Zd Z xZS )ExtractPatchesNr   c                    t         |   |       t        |t              r||f}|| _        t        | j                        dk(  | _        ||}|| _        || _        || _	        t        j                  |      | _        y )Nr   r%   )r   r   
isinstanceintrY   r0   is_3dstridesdilation_ratepaddingr   r   r   )r   rY   r   r   r   r   r   r   s          r   r   zExtractPatches.__init__@  sv     	d#dC $<D	^q(
?G*"::;Gr   c                     t        || j                  | j                  | j                  | j                  | j
                        S )Nr!   rY   r   r   r   r   )_extract_patchesrY   r   r   r   r   r    s     r   r"   zExtractPatches.callV  s9    LL,,LL((
 	
r   c           	         t        |j                        }t        |      }| j                  dk(  r|d   }n| j                  r|d   n|d   }| j                  rj|dk(  rdg|z   }| j
                  d   | j
                  d   z  | j
                  d   z  |z  }| j
                  d   | j
                  d   | j
                  d   f}nK|d	k(  rdg|z   }| j
                  d   | j
                  d   z  |z  }| j
                  d   | j
                  d   f}t        |||| j                  | j                  | j                  | j                  
      }| j                  r|dk(  r|dd  }n
|d	k(  r|dd  }t        ||j                        S )Nr(   r)   r*   r&   r+   r   ro   r%   )r   r   r   r   r,   )r/   r-   r0   r   r   rY   r	   r   r   r   r   r.   )r   r!   r3   original_ndimchannels_infilterskernel_size	out_shapes           r   r6   z"ExtractPatches.compute_output_spec`  sv   FLL)L).&r*K.2jj,r*l2>NK::! !s\1iilTYYq\1DIIaL@;NG99Q<1tyy|DK ! !s\1iilTYYq\1K?G99Q<16K-LLLL((,,
	 ::!%abM	!%abM	&,,??r   c                 v    | j                   | j                  | j                  | j                  | j                  dS )NrY   r   r   r   r   r   )r   s    r   
get_configzExtractPatches.get_config  s3    II||!//||++
 	
r   Nr+   validN)r9   r:   r;   r   r"   r6   r   r<   r=   s   @r   r   r   ?  s3     H H,
%@N
r   r   zkeras.ops.image.extract_patchesc                 \   t        |t              sat        |t        t        f      s$t	        d| dt        |      j                         t        |      dvrt        d| dt        |             t        | f      rt        |||||      j                  |       S t        | |||||      S )a$	  Extracts patches from the image(s) or volume(s).

    This function supports both 2D and 3D patch extraction based on the
    `size` argument length, similar to how `keras.ops.conv` handles
    different dimensions.

    Args:
        images: Input image/volume or batch of images/volumes.
            For 2D patches: 3D `(H, W, C)` or 4D `(N, H, W, C)`.
            For 3D patches: 4D `(D, H, W, C)` or 5D `(N, D, H, W, C)`.
        size: Patch size as int or tuple.
            Length 2 tuple `(patch_height, patch_width)` or int for 2D patches.
            Length 3 tuple `(patch_depth, patch_height, patch_width)` for
            3D patches.
        strides: Strides for patch extraction. If not specified, defaults
            to `size` (non-overlapping patches).
        dilation_rate: Dilation rate for patch extraction. Note that
            `dilation_rate > 1` is not supported with `strides > 1`.
        padding: The type of padding algorithm to use: `"same"` or `"valid"`.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            If not specified, defaults to `keras.config.image_data_format`.

    Returns:
        Extracted patches with shape depending on input and `size`:
        - 2D patches: 3D (unbatched) or 4D (batched)
        - 3D patches: 4D (unbatched) or 5D (batched)

    Examples:

    >>> # 2D patches from batch of images
    >>> image = np.random.random(
    ...     (2, 20, 20, 3)
    ... ).astype("float32")
    >>> patches = keras.ops.image.extract_patches(image, (5, 5))
    >>> patches.shape
    (2, 4, 4, 75)

    >>> # 2D patches from single image
    >>> image = np.random.random((20, 20, 3)).astype("float32")
    >>> patches = keras.ops.image.extract_patches(image, (3, 3), (1, 1))
    >>> patches.shape
    (18, 18, 27)

    >>> # 3D patches from batch of volumes
    >>> volumes = np.random.random(
    ...     (2, 10, 10, 10, 3)
    ... ).astype("float32")
    >>> patches = keras.ops.image.extract_patches(volumes, (3, 3, 3))
    >>> patches.shape
    (2, 3, 3, 3, 81)

    >>> # 3D patches from single volume
    >>> volume = np.random.random((10, 10, 10, 3)).astype("float32")
    >>> patches = keras.ops.image.extract_patches(volume, (3, 3, 3))
    >>> patches.shape
    (3, 3, 3, 81)
    zDInvalid `size` argument. Expected an int or a tuple. Received: size=z	 of type ro   r%   zKInvalid `size` argument. Expected a tuple of length 2 or 3. Received: size=z with length r   r   )r   r   r2   r/   	TypeErrortyper9   r0   r1   r   r   r?   r   r   s         r   extract_patchesr     s    H dC $.""&yd1D1D0EG  t9F"""&}SYKA  VI&'#
 -
	  g}g; r   c                 ~    t        |t              st        |      dk(  rt        | |||||      S t	        | |||||      S )Nr%   )r   r   r0   _extract_patches_3d_extract_patches_2dr   s         r   r   r     sN     dC SY!^"D'=';
 	
 g}g{ r   c                    t        |t              r|x}}n't        |      dk(  r|d   |d   }}nt        d|       t	        j
                  |      }|dk(  r| j                  d   }n|dk(  r| j                  d   }|s|}||z  z  }	t        j                  j                  |	| j                  	      }
t        j                  j                  |
||||	f      }
d
}t        | j                        dk(  r#d}t        j                  j                  | d      } t        j                  j                  | |
||||      }|r!t        j                  j                  |d      }|S )Nro   r   r+   zPInvalid `size` argument. Expected an int or a tuple of length 2. Received: size=r(   r)   channels_firstr*   r   Fr%   Taxisinputskernelr   r   r   r   )r   r   r0   r   r   r   r-   numpyeyer.   reshapeexpand_dimsnnconvsqueeze)r!   rY   r   r   r   r   patch_hpatch_wr   out_dimr   
_unbatchedpatchess                r   r   r     sh    $  '	Ta7DG::>A
 	
 11+>Ko%ll2&	(	(ll2&+-G]]wfll;F]]""';8F J
6<<A
**6*:jjoo#  G --''a'8Nr   c                     t        |t              r|x}x}}n#t        |      dk(  r|\  }}}nt        d|       ||}t        |t              r|||f}t        |      dk7  rt	        d|       t        j                  |      }|dk(  r| j                  d   }	n|dk(  r| j                  d   }	||z  |z  	z  }
t
        j                  j                  |
| j                        }t
        j                  j                  |||||	|
f      }d	}t        | j                        d
k(  r#d}t
        j                  j                  | d      } t
        j                  j                  | |||||      }|r!t
        j                  j                  |d      }|S )Nr%   zPInvalid `size` argument. Expected an int or a tuple of length 3. Received: size=z!Invalid `strides` argument. Got: r(   r)   r   r   r   Fr&   Tr   r   r   )r   r   r0   r   r1   r   r   r-   r   r   r.   r   r   r   r   r   )volumesrY   r   r   r   r   patch_dr   r   r   r   r   r   r   s                 r   r   r   /  s    $&***'G	Ta$(!'::>A
 	
 '3GW-
7|q<WIFGG11+>Ko%mmB'	(	(mmB'')K7G]]wgmm<F]]""'7KAF J
7==Q
--++G!+<jjoo#  G --''a'8Nr   z"keras.ops.image.extract_patches_3dc                     t        |t              r|||f}t        | f      rt        |||||      j	                  |       S t        | |||||      S )a  Extracts patches from the volume(s).

    Args:
        volumes: Input volume or batch of volumes. Must be 4D or 5D.
        size: Patch size int or tuple (patch_depth, patch_height, patch_width)
        strides: strides along depth, height, and width. If not specified, or
            if `None`, it defaults to the same value as `size`.
        dilation_rate: This is the input stride, specifying how far two
            consecutive patch samples are in the input. Note that using
            `dilation_rate > 1` is not supported in conjunction with
            `strides > 1` on the TensorFlow backend.
        padding: The type of padding algorithm to use: `"same"` or `"valid"`.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, depth, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape
            `(batch, channels, depth, height, width)`. If not specified,
             the value will default to `keras.config.image_data_format()`.

    Returns:
        Extracted patches 4D (if not batched) or 5D (if batched)

    Examples:

    >>> import numpy as np
    >>> import keras
    >>> # Batched case
    >>> volumes = np.random.random(
    ...     (2, 10, 10, 10, 3)
    ... ).astype("float32") # batch of 2 volumes
    >>> patches = keras.ops.image.extract_patches_3d(volumes, (3, 3, 3))
    >>> patches.shape
    (2, 3, 3, 3, 81)
    >>> # Unbatched case
    >>> volume = np.random.random((10, 10, 10, 3)).astype("float32") # 1 volume
    >>> patches = keras.ops.image.extract_patches_3d(volume, (3, 3, 3))
    >>> patches.shape
    (3, 3, 3, 81)
    r   r   )r   r   r   r   r?   r   )r   rY   r   r   r   r   s         r   extract_patches_3dr   a  si    d $dD!WJ''#
 -
 	! wwK r   c                   2     e Zd Zddd fdZd Zd Z xZS )MapCoordinatesNr   c                P    t         |   |       || _        || _        || _        y r   )r   r   orderr^   r_   )r   r   r^   r_   r   r   s        r   r   zMapCoordinates.__init__  s(    d#
"$r   c                     t         j                  j                  ||| j                  | j                  | j
                        S )N)r   r^   r_   )r   r   map_coordinatesr   r^   r_   r   r   coordinatess      r   r"   zMapCoordinates.call  s9    }},,**nn - 
 	
r   c                 D   |j                   d   t        |j                         k7  r(t        d|j                    d|j                   d          t        |j                         dk  rt        d|j                          t        |j                   dd  |j                        S )Nr   zaFirst dim of `coordinates` must be the same as the rank of `inputs`. Received inputs with shape: z and coordinate leading dim of ro   zOInvalid coordinates rank: expected at least rank 2. Received input with shape: r+   r   )r-   r0   r1   r   r.   r   s      r   r6   z"MapCoordinates.compute_output_spec  s    Q3v||#44//5||n =""-"3"3A"6!79  {  !A%//:/@/@.AC  ;,,QR0EEr   rl   r   r8   r=   s   @r   r   r     s    %$ %
Fr   r   zkeras.ops.image.map_coordinatesc                     t        | |f      rt        |||      j                  | |      S t        j                  j                  | ||||      S )a  Map the input array to new coordinates by interpolation.

    Note that interpolation near boundaries differs from the scipy function,
    because we fixed an outstanding bug
    [scipy/issues/2640](https://github.com/scipy/scipy/issues/2640).

    Args:
        inputs: The input array.
        coordinates: The coordinates at which inputs is evaluated.
        order: The order of the spline interpolation. The order must be `0` or
            `1`. `0` indicates the nearest neighbor and `1` indicates the linear
            interpolation.
        fill_mode: Points outside the boundaries of the inputs are filled
            according to the given mode. Available methods are `"constant"`,
            `"nearest"`, `"wrap"` and `"mirror"` and `"reflect"`. Defaults to
            `"constant"`.
            - `"constant"`: `(k k k k | a b c d | k k k k)`
                The inputs is extended by filling all values beyond
                the edge with the same constant value k specified by
                `fill_value`.
            - `"nearest"`: `(a a a a | a b c d | d d d d)`
                The inputs is extended by the nearest pixel.
            - `"wrap"`: `(a b c d | a b c d | a b c d)`
                The inputs is extended by wrapping around to the opposite edge.
            - `"mirror"`: `(c d c b | a b c d | c b a b)`
                The inputs is extended by mirroring about the edge.
            - `"reflect"`: `(d c b a | a b c d | d c b a)`
                The inputs is extended by reflecting about the edge of the last
                pixel.
        fill_value: Value used for points outside the boundaries of the inputs
            if `fill_mode="constant"`. Defaults to `0`.

    Returns:
        Output input or batch of inputs.

    )r   r   r?   r   r   r   )r   r   r   r^   r_   s        r   r   r     s^    P V[12
 -
,		-
 ==(( r   c                 :    | | dk  rt        | d| d|        y y )Nr   z must be >= 0. Received: =)r1   )valuer   s     r   _validate_non_negativer     s3    UQYD6!:4&%IJJ 'r   c                 @   | ||gj                  d       dk7  rt        d|  d| d|       |||gj                  d       dk7  rt        d| d| d|       t        | d       t        |d	       t        |d
       t        |d       t        |d       t        |d       y )Nr+   z^Must specify exactly two of top_padding, bottom_padding, target_height. Received: top_padding=z, bottom_padding=, target_height=z^Must specify exactly two of left_padding, right_padding, target_width. Received: left_padding=z, right_padding=, target_width=top_paddingbottom_paddingtarget_heightleft_paddingright_paddingtarget_widthcountr1   r   )r   r   r   r   r   r   s         r   _validate_pad_images_argsr     s     	^]399$?1D%%0M 2,- .*O	-
 	
 	m\288>!C&&2^ 4*O ,(>	+
 	
 ;6>+;<=/:<8=/:<8r   c                 @   | ||gj                  d       dk7  rt        d|  d| d|       |||gj                  d       dk7  rt        d| d| d|       t        | d       t        |d	       t        |d
       t        |d       t        |d       t        |d       y )Nr+   zaMust specify exactly two of top_cropping, bottom_cropping, target_height. Received: top_cropping=z, bottom_cropping=r   zaMust specify exactly two of left_cropping, right_cropping, target_width. Received: left_cropping=z, right_cropping=r   top_croppingbottom_croppingr   left_croppingright_croppingr   r   )r   r   r   r   r   r   s         r   _validate_crop_images_argsr      s     	o}5;;DAQF&&2^ 4./ 0*O	-
 	
 	~|4::4@AE''4o 6,- .(>	+
 	
 <8?,=>=/:=/:>+;<<8r   c                   @     e Zd Z	 	 	 	 	 	 	 ddd fdZd Zd Z xZS )	PadImagesNr   c                    t         	|   |       || _        || _        || _        || _        || _        || _        t        j                  |      | _
        y r   )r   r   r   r   r   r   r   r   r   r   r   )
r   r   r   r   r   r   r   r   r   r   s
            r   r   zPadImages.__init__B  sX     	d#&(,**("::;Gr   c           
          t        || j                  | j                  | j                  | j                  | j
                  | j                  | j                        S r7   )_pad_imagesr   r   r   r   r   r   r   r    s     r   r"   zPadImages.callW  sQ    	
 		
r   c                    t        |j                        }t        |      dvrt        d|       t	        | j
                  | j                  | j                  | j                  | j                  | j                         | j                  dk(  rd\  }}||   ||   }}nd\  }}||   ||   }}| j                  }||| j
                  |z   | j                  z   }| j                  }||| j                  |z   | j                  z   }|e| j
                  }	| j                  }
|	||z
  |
z
  }	|
||z
  |	z
  }
|	dk  rt        d|	       |
dk  rt        d|
       |dk  rt        d	|       |e| j                  }| j                  }|||z
  |z
  }|||z
  |z
  }|dk  rt        d
|       |dk  rt        d|       |dk  rt        d|       |||<   |||<   t        ||j                        S )Nr$   r'   r(   re   rg   r   0top_padding must be >= 0. Received: top_padding=6bottom_padding must be >= 0. Received: bottom_padding=4target_height must be >= 0. Received: target_height=2left_padding must be >= 0. Received: left_padding=4right_padding must be >= 0. Received: right_padding=2target_width must be >= 0. Received: target_width=r,   )r/   r-   r0   r1   r   r   r   r   r   r   r   r   r   r.   )r   r!   r3   rh   ri   heightwidthr   r   r   r   r   r   s                r   r6   zPadImages.compute_output_specc  s   FLL)|F***69 
 	"	
 .&,#K(5|J7OEF&,#K(5|J7OEF** V%7 ,,v58K8KKM((E$5,,u4t7I7IIL**K!00N"+f4~E%!.!7+!EQ --8M;  ! 00>/?A  q  //<o? 
 ,,L ..M#+e3mC$ ,u 4| Ca ..:^=  q  //<o?  a ..:^= 
 %2[!#/Z V\\BBr   NNNNNNNr8   r=   s   @r   r   r   A  s7     H H*

OCr   r   zkeras.ops.image.pad_imagesc           
      ~    t        | f      r t        |||||||      j                  |       S t        | |||||||      S )a  Pad `images` with zeros to the specified `height` and `width`.

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        top_padding: Number of rows of zeros to add on top.
        left_padding: Number of columns of zeros to add on the left.
        bottom_padding: Number of rows of zeros to add at the bottom.
        right_padding: Number of columns of zeros to add on the right.
        target_height: Height of output images.
        target_width: Width of output images.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        Padded image or batch of images.

    Example:

    >>> images = np.random.random((15, 25, 3))
    >>> padded_images = keras.ops.image.pad_images(
    ...     images, 2, 3, target_height=20, target_width=30
    ... )
    >>> padded_images.shape
    (20, 30, 3)

    >>> batch_images = np.random.random((2, 15, 25, 3))
    >>> padded_batch = keras.ops.image.pad_images(
    ...     batch_images, 2, 3, target_height=20, target_width=30
    ... )
    >>> padded_batch.shape
    (2, 20, 30, 3))r   r   r?   r   )r!   r   r   r   r   r   r   r   s           r   
pad_imagesr     sd    ` VI&
 -
	  	 	r   c                    t        j                  |      }t        j                  |       } t        j                  |       }t        |      dvrt        d|       t        ||||||       t        |      dk(  rdnd}	|dk(  r|d   |d   }}
n
|d   |d	   }}
|||z
  |
z
  }|||z
  |
z
  }|||z
  |z
  }|||z
  |z
  }|d
k  rt        d|       |d
k  rt        d|       |d
k  rt        d|       |d
k  rt        d|       ||g||gg}|dk(  r	|d
d
ggz   }nd
d
gg|z   }|	rd
d
gg|z   }t         j                  j                  | |      }|S )Nr$   r'   r%   FTr(   r*   rf   r)   r   r   r   r   r   )
r   r   convert_to_tensorr   r-   r0   r1   r   r   pad)r!   r   r   r   r   r   r   r   r3   is_batchr   r   	pad_widthpadded_imagess                 r   r   r     s    11+>K&&v.F99V$L <&&&2^5
 	

  L)Q.uDHo%$R(,r*:$R(,r*: #n4v=&4v=#m3e;$|3e;Q>{mL
 	
 a@O
 	
 q''4o7
 	
 ((6'79
 	
 ~.}0MNIo%!Q(	VHy(	VHy(	MM%%fi8Mr   c                   @     e Zd Z	 	 	 	 	 	 	 ddd fdZd Zd Z xZS )
CropImagesNr   c                    t         	|   |       || _        || _        || _        || _        || _        || _        t        j                  |      | _
        y r   )r   r   r   r   r   r   r   r   r   r   r   )
r   r   r   r   r   r   r   r   r   r   s
            r   r   zCropImages.__init__K  sX     	d#(.*,*("::;Gr   c           
          t        || j                  | j                  | j                  | j                  | j
                  | j                  | j                        S r7   )_crop_imagesr   r   r   r   r   r   r   r    s     r   r"   zCropImages.call`  sQ      	
 		
r   c                 l   t        |j                        }t        |      dvrt        d|       t	        | j
                  | j                  | j                  | j                  | j                  | j                         | j                  dk(  rd\  }}nd\  }}||   ||   }}|'| j                  t        d| d| j                         |'| j                  t        d| d	| j                         | j                  }||| j
                  z
  | j                  z
  }| j                  }||| j                  z
  | j                  z
  }|e| j
                  }	| j                  }
|	||z
  |
z
  }	|
||z
  |	z
  }
|	d
k  rt        d|	       |
d
k  rt        d|
       |d
k  rt        d|       |e| j                  }| j                  }|||z
  |z
  }|||z
  |z
  }|d
k  rt        d|       |d
k  rt        d|       |d
k  rt        d|       |||<   |||<   t        ||j                        S )Nr$   r'   r(   re   rg   zbWhen the height of the images is unknown, `target_height` must be specified.Received images.shape=z and target_height=z`When the width of the images is unknown, `target_width` must be specified.Received images.shape=z and target_width=r   2top_cropping must be >= 0. Received: top_cropping=z8bottom_cropping must be >= 0. Received: bottom_cropping=r   4left_cropping must be >= 0. Received: left_cropping=z6right_cropping must be >= 0. Received: right_cropping=r   r,   )r/   r-   r0   r1   r   r   r   r   r   r   r   r   r   r.   )r   r!   r3   rh   ri   r   r   r   r   r   r   r   r   s                r   r6   zCropImages.compute_output_specl  s   FLL)|F***69 
 	#  	
 .&,#K&,#K$[1<
3K>d008))5 7!!%!3!3 46  =T..6))5 7  $ 1 124  ** "T%6%669M9MMM(( 4#5#558K8KKL,,L"22O#%5G&"(="8<"Ga ..:^=  " 11@0AC  q  //<o? 
  ..M!00N$ % 4~ E%!&!5!Eq  //<o?  ! 00>/?A  a ..:^= 
 %2[!#/Z V\\BBr   r   r8   r=   s   @r   r   r   J  s7     H H*

]Cr   r   zkeras.ops.image.crop_imagesc           
      ~    t        | f      r t        |||||||      j                  |       S t        | |||||||      S )a  Crop `images` to a specified `height` and `width`.

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        top_cropping: Number of columns to crop from the top.
        left_cropping: Number of columns to crop from the left.
        bottom_cropping: Number of columns to crop from the bottom.
        right_cropping: Number of columns to crop from the right.
        target_height: Height of the output images.
        target_width: Width of the output images.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        Cropped image or batch of images.

    Example:

    >>> images = np.reshape(np.arange(1, 28, dtype="float32"), [3, 3, 3])
    >>> images[:,:,0] # print the first channel of the images
    array([[ 1.,  4.,  7.],
           [10., 13., 16.],
           [19., 22., 25.]], dtype=float32)
    >>> cropped_images = keras.image.crop_images(images, 0, 0, 2, 2)
    >>> cropped_images[:,:,0] # print the first channel of the cropped images
    array([[ 1.,  4.],
           [10., 13.]], dtype=float32))r   r   r?   r   )r!   r   r   r   r   r   r   r   s           r   crop_imagesr     sd    X VI&
 -
	  	 	r   c                    t        j                  |      }t        j                  |       } t        j                  |       }t        |      dvrt        d|       t        ||||||       t        |      dk(  rdnd}	|dk(  r|d   |d   }}
|d	   }n|d   |d	   }}
|d   }||
|z
  |z
  }||
|z
  |z
  }|||z
  |z
  }|||z
  |z
  }|d
k  rt        d|       |d
k  rt        d|       |d
k  rt        d|       |d
k  rt        d|       ||g}||g}|dk(  r|d
gz   }||gz   }nd
g|z   }|g|z   }|	r|d
   }d
g|z   }|g|z   }t        j                  | ||      }|S )Nr$   r'   r%   FTr(   r*   rf   r)   r   r   r   r   r   )	r   r   r   r   r-   r0   r1   r   slice)r!   r   r   r   r   r   r   r   r3   r   r   r   r5   start_indicesr-   
batch_sizecropped_imagess                    r   r   r     s<    11+>K&&v.F99V$L <&&&2^5
 	

  L)Q.uDHo%$R(,r*:#$R(,r*:# -?0<?,~=~-=a@O
 	
 q''4o7
 	
 q''4o7
 	
 a@O
 	

 "=1ML)Eo%%+
"m+
U"!!_
m+u$YYv}e<Nr   c                   8     e Zd Z	 	 	 ddd fdZd Zd Z xZS )PerspectiveTransformNr   c                v    t         |   |       || _        || _        t	        j
                  |      | _        y r   )r   r   rZ   r_   r   r   r   )r   rZ   r_   r   r   r   s        r   r   zPerspectiveTransform.__init__e  s7     	d#*$"::;Gr   c                     t         j                  j                  |||| j                  | j                  | j
                        S )NrZ   r_   r   )r   r   perspective_transformrZ   r_   r   r   r!   start_points
end_pointss       r   r"   zPerspectiveTransform.callr  s@    }}22,,(( 3 
 	
r   c                    t        |j                        dvrt        d|j                         |j                  dd  dk7  s|j                  dvrt        d|j                         |j                  dd  dk7  s|j                  dvrt        d|j                         |j                  |j                  k7  r%t        d|j                   d	|j                         t	        |j                  |j
                  
      S )Nr$   rd   rf   )r&   ro   r   zfInvalid start_points shape: expected (4,2) for a single image or (N,4,2) for a batch. Received shape: zdInvalid end_points shape: expected (4,2) for a single image or (N,4,2) for a batch. Received shape: zRstart_points and end_points must have the same shape. Received start_points.shape=z, end_points.shape=r   )r0   r-   r1   ndimr   r.   r	  s       r   r6   z(PerspectiveTransform.compute_output_spec|  s#   v||F*  &~/ 
 bc"f,0A0A0O<<H<N<N;OQ  BC F*jooV.K<<F<L<L;MO  !1!1100<0B0B/C D$$.$4$4#57 
 6<<v||<<r   rk   r   Nr8   r=   s   @r   r  r  d  s)     !	H H
=r   r  z%keras.ops.image.perspective_transformc                     t        | ||f      rt        |||      j                  | ||      S t        j                  j                  | |||||      S )a
  Applies a perspective transformation to the image(s).

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        start_points: A tensor of shape `(N, 4, 2)` or `(4, 2)`,
            representing the source points in the original image
            that define the transformation.
        end_points: A tensor of shape `(N, 4, 2)` or `(4, 2)`,
            representing the target points in the output image
            after transformation.
        interpolation: Interpolation method. Available methods are `"nearest"`,
            and `"bilinear"`. Defaults to `"bilinear"`.
        fill_value: Value used for points outside the boundaries of the input if
            extrapolation is needed. Defaults to `0`.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        Applied perspective transform image or batch of images.

    Examples:

    >>> x = np.random.random((2, 64, 80, 3))  # batch of 2 RGB images
    >>> start_points = np.array(
    ...     [
    ...         [[0, 0], [0, 64], [80, 0], [80, 64]],
    ...         [[0, 0], [0, 64], [80, 0], [80, 64]],
    ...     ]
    ... )
    >>> end_points = np.array(
    ...     [
    ...         [[3, 5], [7, 64], [76, -10], [84, 61]],
    ...         [[8, 10], [10, 61], [65, 3], [88, 43]],
    ...     ]
    ... )
    >>> y = keras.ops.image.perspective_transform(x, start_points, end_points)
    >>> y.shape
    (2, 64, 80, 3)

    >>> x = np.random.random((64, 80, 3))  # single RGB image
    >>> start_points = np.array([[0, 0], [0, 64], [80, 0], [80, 64]])
    >>> end_points = np.array([[3, 5], [7, 64], [76, -10], [84, 61]])
    >>> y = keras.ops.image.perspective_transform(x, start_points, end_points)
    >>> y.shape
    (64, 80, 3)

    >>> x = np.random.random((2, 3, 64, 80))  # batch of 2 RGB images
    >>> start_points = np.array(
    ...     [
    ...         [[0, 0], [0, 64], [80, 0], [80, 64]],
    ...         [[0, 0], [0, 64], [80, 0], [80, 64]],
    ...     ]
    ... )
    >>> end_points = np.array(
    ...     [
    ...         [[3, 5], [7, 64], [76, -10], [84, 61]],
    ...         [[8, 10], [10, 61], [65, 3], [88, 43]],
    ...     ]
    ... )
    >>> y = keras.ops.image.perspective_transform(
    ...     x, start_points, end_points, data_format="channels_first"
    ... )
    >>> y.shape
    (2, 3, 64, 80)
    r  )r   r  r?   r   r   r  )r!   r
  r  rZ   r_   r   s         r   r  r    sj    ^ V\:>?#'!#
 -j
9		:
 ==..# /  r   c                   8     e Zd Z	 	 	 ddd fdZd Zd Z xZS )GaussianBlurNr   c                v    t         |   |       || _        || _        t	        j
                  |      | _        y r   )r   r   r   sigmar   r   r   )r   r   r  r   r   r   s        r   r   zGaussianBlur.__init__  s7     	d#&
"::;Gr   c                     t         j                  j                  || j                  | j                  | j
                        S )Nr   r  r   )r   r   gaussian_blurr   r  r   r    s     r   r"   zGaussianBlur.call  s:    }}**((**((	 + 
 	
r   c                     t        |j                        dvrt        d|j                         t        |j                  |j                        S Nr$   rd   r   r   r    s     r   r6   z GaussianBlur.compute_output_spec  J    v||F*  &~/ 
 6<<v||<<r   )r%   r%   )      ?r  Nr8   r=   s   @r   r  r    s)     	H H
=r   r  zkeras.ops.image.gaussian_blurc                     t        | f      rt        |||      j                  |       S t        j                  j                  | |||      S )an  Applies a Gaussian blur to the image(s).

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        kernel_size: A tuple of two integers, specifying the height and width
            of the Gaussian kernel.
        sigma: A tuple of two floats, specifying the standard deviation of
            the Gaussian kernel along height and width.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        Blurred image or batch of images.

    Examples:

    >>> x = np.random.random((2, 64, 80, 3))  # batch of 2 RGB images
    >>> y = keras.ops.image.gaussian_blur(x)
    >>> y.shape
    (2, 64, 80, 3)

    >>> x = np.random.random((64, 80, 3))  # single RGB image
    >>> y = keras.ops.image.gaussian_blur(x)
    >>> y.shape
    (64, 80, 3)

    >>> x = np.random.random((2, 3, 64, 80))  # batch of 2 RGB images
    >>> y = keras.ops.image.gaussian_blur(
    ...     x, data_format="channels_first")
    >>> y.shape
    (2, 3, 64, 80)
    r  )r   r  r?   r   r   r  )r!   r   r  r   s       r   r  r    s[    R VI&##
 -
		 
 ==&&	 '  r   c                   @     e Zd Z	 	 	 	 	 	 	 ddd fdZd Zd Z xZS )ElasticTransformNr   c                    t         	|   |       || _        || _        || _        || _        || _        || _        t        j                  |      | _
        y r   )r   r   alphar  rZ   r^   r_   seedr   r   r   )
r   r   r  rZ   r^   r_   r!  r   r   r   s
            r   r   zElasticTransform.__init__M  sS     	d#

*"$	"::;Gr   c           
          t         j                  j                  || j                  | j                  | j
                  | j                  | j                  | j                  | j                        S )Nr   r  rZ   r^   r_   r!  r   )
r   r   elastic_transformr   r  rZ   r^   r_   r!  r   r    s     r   r"   zElasticTransform.callb  sV    }}..****,,nn(( / 	
 		
r   c                     t        |j                        dvrt        d|j                         t        |j                  |j                        S r  r   r    s     r   r6   z$ElasticTransform.compute_output_specn  r  r   g      4@g      @rk   reflectrm   NNr8   r=   s   @r   r  r  L  s5      H H*

=r   r  z!keras.ops.image.elastic_transformc           
          t        | f      r!t        |||||||      j                  |       S t        j                  j                  | |||||||      S )a	  Applies elastic deformation to the image(s).

    Args:
        images: Input image or batch of images. Must be 3D or 4D.
        alpha: Scaling factor that controls the intensity of the deformation.
        sigma: Standard deviation of the Gaussian filter used for
            smoothing the displacement fields.
        interpolation: Interpolation method. Available methods are `"nearest"`,
            and `"bilinear"`. Defaults to `"bilinear"`.
        fill_mode: Points outside the boundaries of the input are filled
            according to the given mode. Available methods are `"constant"`,
            `"nearest"`, `"wrap"` and `"reflect"`. Defaults to `"constant"`.
            - `"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 specified by
                `fill_value`.
            - `"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.
        fill_value: Value used for points outside the boundaries of the input if
            `fill_mode="constant"`. Defaults to `0`.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        Transformed image or batch of images with elastic deformation.

    Examples:

    >>> x = np.random.random((2, 64, 80, 3))  # batch of 2 RGB images
    >>> y = keras.ops.image.elastic_transform(x)
    >>> y.shape
    (2, 64, 80, 3)

    >>> x = np.random.random((64, 80, 3))  # single RGB image
    >>> y = keras.ops.image.elastic_transform(x)
    >>> y.shape
    (64, 80, 3)

    >>> x = np.random.random((2, 3, 64, 80))  # batch of 2 RGB images
    >>> y = keras.ops.image.elastic_transform(
    ...     x, data_format="channels_first")
    >>> y.shape
    (2, 3, 64, 80)
    r#  )r   r  r?   r   r   r$  )r!   r   r  rZ   r^   r_   r!  r   s           r   r$  r$  x  ss    B VI&'!#
 -
	  ==**# + 	 	r   c                   2     e Zd Zddd fdZd Zd Z xZS )ScaleAndTranslateNr   c                P    t         |   |       || _        || _        || _        y r   )r   r   spatial_dimsmethodr[   )r   r,  r-  r[   r   r   s        r   r   zScaleAndTranslate.__init__  s)    d#("r   c           	          t         j                  j                  ||||| j                  | j                  | j
                        S )N)output_shapescaletranslationr,  r-  r[   )r   r   scale_and_translater,  r-  r[   r   r!   r/  r0  r1  s        r   r"   zScaleAndTranslate.call  sA    }}00%#**;;nn 1 
 	
r   c                 0    t        ||j                        S )Nr   )r   r.   r3  s        r   r6   z%ScaleAndTranslate.compute_output_spec  s    <v||<<r   Tr8   r=   s   @r   r*  r*    s    #T #	
=r   r*  z#keras.ops.image.scale_and_translatec           	          t        | ||f      rt        |||      j                  | |||      S t        j                  j                  | ||||||      S )a'  Apply a scale and translation to the images.

    Generates a new image of `output_shape` by resampling from the input image
    using the sampling method corresponding to method. For 2D images, this
    operation transforms a location in the input images, (x, y), to a location
    in the output image according to:

    `(x * scale[1] + translation[1], y * scale[0] + translation[0])`.

    (Note the inverse warp is used to generate the sample locations.) Assumes
    half-centered pixels, i.e the pixel at integer location row, col has
    coordinates y, x = row + 0.5, col + 0.5, and similarly for other input image
    dimensions.

    If an output location(pixel) maps to an input sample location that is
    outside the input boundaries then the value for the output location will be
    set to zero.

    The `method` argument expects one of the following resize methods:

    - `"linear"`, `"bilinear"`, `"trilinear"`, `"triangle"`: Linear
        interpolation. If `antialias` is True, uses a triangular filter when
        downsampling.
    - `"cubic"`, `"bicubic"`, `"tricubic"`: Cubic interpolation, using the Keys
        cubic kernel.
    - `"lanczos3"`: Lanczos resampling, using a kernel of radius 3.
    - `"lanczos5"`: Lanczos resampling, using a kernel of radius 5.

    Args:
        images: The input array.
        output_shape: The output shape, as a sequence of integers with length
            equal to the number of dimensions of image.
        scale: A [K] array with the same number of dimensions as `images`,
            containing the scale to apply in each dimension.
        translation: A [K] array with the same number of dimensions as `images`,
            containing the translation to apply in each dimension.
        spatial_dims: A length K tuple specifying the spatial dimensions that
            the passed `scale` and `translation` should be applied to.
        method: A string specifying the resizing method to use. Available
            methods are `"linear"`, `"bilinear"`, `"trilinear"`, `"triangle"`,
            `"cubic"`, `"bicubic"`, `"tricubic"`, `"lanczos3"` and `"lanczos5"`.
        antialias: Whether an antialiasing filter should be applied when
            downsampling. Has no effect when upsampling. Defaults to `True`.

    Returns:
        The scale and translated images.

    Example:

    >>> images = np.arange(9, dtype="float32").reshape((3, 3))
    >>> scale = np.array([2.0, 2.0]).astype("float32")
    >>> translation = -(scale / 2.0 - 0.5)
    >>> resized_images = keras.image.scale_and_translate(
    ...     images, (5, 5), scale, translation, (0, 1), "linear"
    ... )
    >>> resized_images
    array([[0.0 0.5 1.0 1.5 2.0]
           [1.5 2.0 2.5 3.0 3.5]
           [3.0 3.5 4.0 4.5 5.0]
           [4.5 5.0 5.5 6.0 6.5]
           [6.0 6.5 7.0 7.5 8.0]], dtype=float32)
    )r   r*  r?   r   r   r2  )r!   r/  r0  r1  r,  r-  r[   s          r   r2  r2    sg    P VUK89 vyAOOL%
 	
 ==,, r   c                   2     e Zd Zddd fdZd Zd Z xZS )
SobelEdgesNr   c                Z    t         |   |       t        j                  |      | _        y r   r   r   s      r   r   zSobelEdges.__init__=  r   r   c                 X    t         j                  j                  || j                        S r   )r   r   sobel_edgesr   r    s     r   r"   zSobelEdges.callA  s"    }}((T=M=M(NNr   c                     t        |j                        }t        |      dk7  rt        d|       |dgz   }t	        ||j
                        S )Nr&   zOInvalid images rank: expected rank 4 (batch of images). Received: images.shape=ro   r,   )r/   r-   r0   r1   r   r.   )r   r!   r3   r/  s       r   r6   zSobelEdges.compute_output_specD  sX    FLL)|!**69 
 $qc)V\\BBr   r7   r8   r=   s   @r   r8  r8  <  s    H HO	Cr   r8  zkeras.ops.image.sobel_edgesc                     t        | f      rt        |      j                  |       S t        j                  j                  | t        j                  |            S )ah  Computes Sobel edge detection on images.

    The Sobel operator computes the gradient of the image intensity at each
    pixel, giving the direction of the largest increase from light to dark
    and the rate of change in that direction.

    Args:
        images: Input tensor of shape `(batch, height, width, channels)` if
            `data_format="channels_last"`, or
            `(batch, channels, height, width)` if
            `data_format="channels_first"`.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        A tensor containing the Sobel edges. For `data_format="channels_last"`,
        the output shape is `(batch, height, width, channels, 2)` where the
        last dimension contains `[dy, dx]` representing the vertical and
        horizontal gradients. For `data_format="channels_first"`, the output
        shape is `(batch, channels, height, width, 2)`.

    Example:

    >>> import numpy as np
    >>> from keras import ops
    >>> # Create image with vertical edge
    >>> image = np.zeros((1, 8, 8, 1), dtype="float32")
    >>> image[0, :, 4:, 0] = 1.0
    >>> edges = ops.image.sobel_edges(image)
    >>> edges.shape
    (1, 8, 8, 1, 2)
    r   )r   r8  r?   r   r   r;  r   r@   s     r   r;  r;  P  sQ    H VI&k2@@HH==$$G;;KH %  r   c                   >     e Zd Z	 	 	 	 	 	 ddd fdZd Zd Z xZS )SSIMNr   c                    t         |   |       || _        || _        || _        || _        || _        t        j                  |      | _	        y r   )
r   r   max_valfilter_sizefilter_sigmak1k2r   r   r   )	r   rA  rB  rC  rD  rE  r   r   r   s	           r   r   zSSIM.__init__|  sM     	d#&("::;Gr   c           
          t        ||| j                  | j                  | j                  | j                  | j
                  | j                        S )NrA  rB  rC  rD  rE  r   )_ssimrA  rB  rC  rD  rE  r   )r   image1image2s      r   r"   z	SSIM.call  sE    LL((**wwww((	
 		
r   c                 B   t        |j                        dvrt        d|j                         t        |j                        dvrt        d|j                         t        |j                        dk(  rd}n|j                  d   f}t        ||j                        S )Nr$   yInvalid image1 rank: expected rank 3 (single image) or rank 4 (batch of images). Received input with shape: image1.shape=yInvalid image2 rank: expected rank 3 (single image) or rank 4 (batch of images). Received input with shape: image2.shape=r%    r   r,   r   )r   rI  rJ  r/  s       r   r6   zSSIM.compute_output_spec  s    v||F*  &~/ 
 v||F*  &~/  v||!L"LLO-LV\\BBr   r     g      ?g{Gz?gQ?Nr8   r=   s   @r   r?  r?  {  s3     H H&

Cr   r?  zkeras.ops.image.ssimc           
          t        | |f      r!t        ||||||      j                  | |      S t        | |||||||      S )a	  Computes the Structural Similarity Index (SSIM) between two images.

    The SSIM index is a method for measuring the similarity between two images.
    It is based on the comparison of luminance, contrast, and structure
    between the images. The resulting SSIM index is a value between -1 and 1,
    where 1 indicates identical images.

    This implementation is based on the original SSIM paper:
    Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004).
    "Image quality assessment: from error visibility to structural similarity."
    IEEE Transactions on Image Processing.

    Args:
        image1: First image or batch of images. Must be 3D or 4D.
        image2: Second image or batch of images. Must have the same shape
            as `image1`.
        max_val: The maximum possible pixel value of the images. Defaults to
            `1.0` (for normalized images). Use `255.0` for images with pixel
            values in `[0, 255]`.
        filter_size: Size of the Gaussian filter used for computing SSIM.
            Defaults to `11`. Must be an odd integer >= 1.
        filter_sigma: Standard deviation of the Gaussian filter. Defaults to
            `1.5`.
        k1: First stabilization constant. Defaults to `0.01`.
        k2: Second stabilization constant. Defaults to `0.03`.
        data_format: A string specifying the data format of the input tensor.
            It can be either `"channels_last"` or `"channels_first"`.
            `"channels_last"` corresponds to inputs with shape
            `(batch, height, width, channels)`, while `"channels_first"`
            corresponds to inputs with shape `(batch, channels, height, width)`.
            If not specified, the value will default to
            `keras.config.image_data_format`.

    Returns:
        A tensor of SSIM values. For batched inputs, returns a 1D tensor
        with one SSIM value per image pair. For unbatched inputs, returns
        a scalar tensor.

    Examples:

    >>> import numpy as np
    >>> from keras import ops
    >>> # Two identical images should have SSIM = 1
    >>> image = np.random.random((32, 32, 3)).astype("float32")
    >>> ssim_value = ops.image.ssim(image, image, max_val=1.0)
    >>> float(ssim_value) > 0.99
    True

    >>> # Batched images
    >>> images1 = np.random.random((2, 32, 32, 3)).astype("float32")
    >>> images2 = np.random.random((2, 32, 32, 3)).astype("float32")
    >>> ssim_values = ops.image.ssim(images1, images2, max_val=1.0)
    >>> ssim_values.shape
    (2,)
    rG  )r   r?  r?   rH  )rI  rJ  rA  rB  rC  rD  rE  r   s           r   ssimrR    sf    D VV,-#%#
 -
'	( !	 	r   c                 `   t        j                  |      }t        j                  |       } t        j                  |      }| j                  }t        j                  | j                  t
              }	t        j                  | |	      } t        j                  ||	      }t        | j                        dvrt        d| j                         t        |j                        dvrt        d|j                         t        | j                        dk(  }
|
r.t        j                  | d      } t        j                  |d      }|dk(  r.t        j                  | dd	      } t        j                  |dd	      }t        j                  |       }|d   }|d   }|d
   }|d   }t        |||	      }t        j                  |||ddf      }||z  d
z  }||z  d
z  }t        j                  | d      }t        j                  |d      }t        j                  |d	||dg      }t        j                  |d	||dg      }t!        ||      }t!        ||      }||z  }||z  }||z  }t!        ||z  |      |z
  }t!        ||z  |      |z
  }t!        ||z  |      |z
  }d|z  |z   d|z  |z   z  }||z   |z   ||z   |z   z  } || z  }!t        j"                  |!g d      }"t        j                  |"||g      }#t        j"                  |#d	      }$|
rt        j$                  |$d      }$t        j                  |$|      S )z5Backend-agnostic SSIM implementation using Keras ops.r$   rL  rM  r%   r   r   r   r+   r)   ro   )r   r%   r+   ro          @)r+   ro   r%   )r   r   r   r.   result_typefloatr   castr0   r-   r1   r   moveaxis_create_gaussian_kernelr   	transpose_depthwise_convmeanr   )%rI  rJ  rA  rB  rC  rD  rE  r   original_dtypecompute_dtype	unbatchedr-   r  r   r   r5   r   c1c2image1_transposedimage2_transposed	image1_ch	image2_chmu1mu2mu1_sqmu2_sqmu1_mu2	sigma1_sq	sigma2_sqsigma12	numeratordenominatorssim_mapssim_valssim_per_imagessim_results%                                        r   rH  rH  	  s2    11+>K&&v.F&&v.F \\N''e<MXXfm,FXXfm,F 6<<&"LL>+
 	

 6<<&"LL>+
 	
 FLL!Q&Ia0a0 &&fa,fa, IIfEqJ1XF!HEQxH %[,NF[[+{Aq!ABF w,1	B
w,1	B
 fl;fl;-FE1/EFI-FE1/EFI )V
,C
)V
,C3YF3YFCiG  	I 5v>GI	I 5v>GIi)3V<wFG w#g(:;IF?R'I	,AB,FGK;&H xxy1H [[J+ABN((>3K kk+A688K00r   c                     t        j                  | |      }|| dz
  dz  z
  }t        j                  |dz   d|dz  z  z        }|t        j                  |      z  }t        j                  ||      }|S )zCreate a 2D Gaussian kernel.r   r+   rT  ro   )r   arangeexpsumouter)rY   r  r.   xgauss_1dr   s         r   rY  rY  m	  sr     	

4u%A	TAXAwwAw#q.12H#''(++H YYx*FMr   c                 J    t         j                  j                  | |ddd      S )z/Apply depthwise convolution with valid padding.r+   r   r(   )r   r   r   )r   r   r   )r!   r   s     r   r[  r[  z	  s-     ::??#   r   r7   rj   r   r   r   r   r  r  r&  r5  rO  )7	keras.srcr   r   keras.src.api_exportr   keras.src.backendr   r   keras.src.ops.operationr   keras.src.ops.operation_utilsr	   r   r   rB   rE   rP   rS   rW   rq   rb   rx   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r$  r*  r2  r8  r;  r?  rR  rH  rY  r[  rN  r   r   <module>r     s     - ) 2 - CCY C: 01(K 2(KVCy C@ *++E ,+E\Cy C@ *+(E ,(EV3CY 3Cl &' j (j` 4>'=i '=T 01 ` 2`FO
Y O
d /0 [ 1[B ( +b /d 23 > 4>BFY F@ /0AB3 13lK
9B9BqC	 qCh *+ C ,C\ K\C CD +, ? -?T Rj/=9 /=d 56
 [ 7[|=9 =@ -.>B3 /3l)=y )=X 12 
	S 3Sl=	 =, 34 S 5SlC C( +,' -'T2C9 2Cj $% S &Sr c1L
	r   