
    0hE              	          d Z ddlZddlZddlZddlZddlmc mZ	 ddl
mZ ddlmZ 	 ddlmZ 	 ej"                  ZeEej*                  ej,                  ej.                  ej0                  ej2                  ej4                  dZe	j8                  j:                  Zej,                  ej<                  ej.                  ej>                  ej@                  ejB                  ejD                  ejF                  dZ$ edg 	      dd
       Z%d Z& edd      dd       Z' edd      dd       Z( edd      dd       Z) edd      	 	 	 	 	 dd       Z*y# e$ r eZY w xY w# e$ r dZdZY ,w xY w)z$Utilities related to image handling.    N)backend)keras_export)Image)nearestbilinearbicubichammingboxlanczos)r   r   r   arealanczos3lanczos5gaussianmitchellcubicz&keras.preprocessing.image.smart_resize)v1c                 <   t        |      dk7  rt        d| d      t        j                  |       }|j                  j
                  K|j                  j
                  dk  s|j                  j
                  dkD  rt        d|j                   d      t        j                  |      }|d   |d	   }}|\  }}|j                  j
                  |j                  d
   }	nd}	t        j                  t        j                  ||z  d      |z  d      }
t        j                  t        j                  ||z  d      |z  d      }t        j                  ||
      }
t        j                  ||      }t        j                  t        j                  ||
z
  d      dz  d      }t        j                  t        j                  ||z
  d      dz  d      }|j                  j
                  dk(  r3t        j                  d||dg      }t        j                  d
|
|d
g      }n0t        j                  ||dg      }t        j                  |
|d
g      }t        j                  |||      }t        j                  j                  |||      }|j                  j
                  [|j                  j
                  dk(  r|j                  ddd|	f       |j                  j
                  dk(  r|j                  dd|	f       t        | t        j                        r|j!                         S |S )a
  Resize images to a target size without aspect ratio distortion.

    Warning: `tf.keras.preprocessing.image.smart_resize` is not recommended for
    new code. Prefer `tf.keras.layers.Resizing`, which provides the same
    functionality as a preprocessing layer and adds `tf.RaggedTensor` support.
    See the [preprocessing layer guide](
    https://www.tensorflow.org/guide/keras/preprocessing_layers)
    for an overview of preprocessing layers.

    TensorFlow image datasets typically yield images that have each a different
    size. However, these images need to be batched before they can be
    processed by TF-Keras layers. To be batched, images need to share the same
    height and width.

    You could simply do:

    ```python
    size = (200, 200)
    ds = ds.map(lambda img: tf.image.resize(img, size))
    ```

    However, if you do this, you distort the aspect ratio of your images, since
    in general they do not all have the same aspect ratio as `size`. This is
    fine in many cases, but not always (e.g. for GANs this can be a problem).

    Note that passing the argument `preserve_aspect_ratio=True` to `resize`
    will preserve the aspect ratio, but at the cost of no longer respecting the
    provided target size. Because `tf.image.resize` doesn't crop images,
    your output images will still have different sizes.

    This calls for:

    ```python
    size = (200, 200)
    ds = ds.map(lambda img: smart_resize(img, size))
    ```

    Your output images will actually be `(200, 200)`, and will not be distorted.
    Instead, the parts of the image that do not fit within the target size
    get cropped out.

    The resizing process is:

    1. Take the largest centered crop of the image that has the same aspect
    ratio as the target size. For instance, if `size=(200, 200)` and the input
    image has size `(340, 500)`, we take a crop of `(340, 340)` centered along
    the width.
    2. Resize the cropped image to the target size. In the example above,
    we resize the `(340, 340)` crop to `(200, 200)`.

    Args:
      x: Input image or batch of images (as a tensor or NumPy array). Must be in
        format `(height, width, channels)` or `(batch_size, height, width,
        channels)`.
      size: Tuple of `(height, width)` integer. Target size.
      interpolation: String, interpolation to use for resizing. Supports
        `bilinear`, `nearest`, `bicubic`, `area`, `lanczos3`, `lanczos5`,
        `gaussian`, `mitchellcubic`. Defaults to `'bilinear'`.

    Returns:
      Array with shape `(size[0], size[1], channels)`. If the input image was a
      NumPy array, the output is a NumPy array, and if it was a TF tensor,
      the output is a TF tensor.
       z6Expected `size` to be a tuple of 2 integers, but got: .N      zExpected an image array with shape `(height, width, channels)`, or `(batch_size, height, width, channels)`, but got input with incorrect rank, of shape float32int32r   )imagessizemethod)len
ValueErrortfconvert_to_tensorshaperankcastminimumstacksliceimageresize	set_shape
isinstancenpndarraynumpy)xr   interpolationimgr#   heightwidthtarget_heighttarget_widthstatic_num_channelscrop_height
crop_widthcrop_box_hstartcrop_box_wstartcrop_box_startcrop_box_sizes                   X/var/www/html/engine/venv/lib/python3.12/site-packages/tf_keras/src/utils/image_utils.pysmart_resizer?   B   s   D 4yA~DTF!L
 	
 

q
!C
yy~~!99>>A!!3;;>99+QH 
 HHSME"IuRyEF"&M<
yy~~!!iim"''
%y1L@'K 
%y1MA7J **V[1KE:.Jgg
$i014gO gg

"I.2GO yy~~1o"JK"k:r!BC?OQ"GH+z2!>?
((3
6C
((//4/
FC
yy~~!99>>QMM4t-@AB99>>QMM4':;<!RZZ yy{J    c                     | j                         } | t        vr-t        dj                  | t        j	                                     t        |    S )NzFValue not recognized for `interpolation`: {}. Supported values are: {})lower_TF_INTERPOLATION_METHODSNotImplementedErrorformatkeys)r1   s    r>   get_interpolationrG      sN    !'')M55!f],E,J,J,LM
 	
 %]33r@   zkeras.utils.array_to_imgz&keras.preprocessing.image.array_to_imgc                    |t        j                         }|t        j                         }t        t	        d      t        j                  | |      } | j                  dk7  rt        d| j                         |dvrt        d|       |dk(  r| j                  d	d
d      } |r<| t        j                  |       z
  } t        j                  |       }|dk7  r| |z  } | dz  } | j                  d
   dk(  r%t        j                  | j                  d      d      S | j                  d
   dk(  r%t        j                  | j                  d      d      S | j                  d
   d	k(  rvt        j                  |       dkD  r/t        j                  | dddddf   j                  d      d      S t        j                  | dddddf   j                  d      d      S t        d| j                  d
          )a$  Converts a 3D Numpy array to a PIL Image instance.

    Usage:

    ```python
    from PIL import Image
    img = np.random.random(size=(100, 100, 3))
    pil_img = tf.keras.utils.array_to_img(img)
    ```


    Args:
        x: Input data, in any form that can be converted to a Numpy array.
        data_format: Image data format, can be either `"channels_first"` or
          `"channels_last"`. None means the global
          setting `tf.keras.backend.image_data_format()` is used (unless you
          changed it, it uses `"channels_last"`). Defaults to `None`.
        scale: Whether to rescale the image such that minimum and maximum values
          are 0 and 255 respectively. Defaults to `True`.
        dtype: Dtype to use. None makes the global setting
          `tf.keras.backend.floatx()` to be used (unless you changed it, it
          uses `"float32"`). Defaults to `None`.

    Returns:
        A PIL Image instance.

    Raises:
        ImportError: if PIL is not available.
        ValueError: if invalid `x` or `data_format` is passed.
    NzCCould not import PIL.Image. The use of `array_to_img` requires PIL.dtyper   zJExpected image array to have rank 3 (single image). Got array with shape: >   channels_lastchannels_firstzInvalid data_format: rL      r   r      r   uint8RGBARGBr   ILzUnsupported channel number: )r   image_data_formatfloatx	pil_imageImportErrorr-   asarrayndimr    r#   	transposeminmax	fromarrayastype)r0   data_formatscalerJ   x_maxs        r>   array_to_imgrb      s   F //1} 6
 	
 	

1E"Avv{%%&WWI/
 	

 ==0>??
 &&KK1a q	Mq	A:JA	SwwqzQ""188G#4f==	
q""188G#4e<<	
q66!9s?&&qAqz'8'8'A3GG""1Q1W:#4#4W#=sCC7
|DEEr@   zkeras.utils.img_to_arrayz&keras.preprocessing.image.img_to_arrayc                 :   |t        j                         }|t        j                         }|dvrt        d|       t	        j
                  | |      }t        |j                        dk(  r|dk(  r|j                  ddd      }|S t        |j                        dk(  re|dk(  r0|j                  d|j                  d   |j                  d   f      }|S |j                  |j                  d   |j                  d   df      }|S t        d	|j                         )
a{  Converts a PIL Image instance to a Numpy array.

    Usage:

    ```python
    from PIL import Image
    img_data = np.random.random(size=(100, 100, 3))
    img = tf.keras.utils.array_to_img(img_data)
    array = tf.keras.utils.image.img_to_array(img)
    ```


    Args:
        img: Input PIL Image instance.
        data_format: Image data format, can be either `"channels_first"` or
          `"channels_last"`. None means the global
          setting `tf.keras.backend.image_data_format()` is used (unless you
          changed it, it uses `"channels_last"`). Defaults to `None`.
        dtype: Dtype to use. None makes the global setting
          `tf.keras.backend.floatx()` to be used (unless you changed it, it
          uses `"float32"`). Defaults to `None`.

    Returns:
        A 3D Numpy array.

    Raises:
        ValueError: if invalid `img` or `data_format` is passed.
    >   rK   rL   zUnknown data_format: rI   r   rL   r   r   rM   zUnsupported image shape: )
r   rT   rU   r    r-   rX   r   r#   rZ   reshape)r2   r_   rJ   r0   s       r>   img_to_arrayre     s   B //1} ==0>?? 	

3e$A
177|q**Aq!$A H 
QWW	**		1aggaj!''!*56A
 H 		1771:qwwqz156A H 4QWWI>??r@   zkeras.utils.save_imgz"keras.preprocessing.image.save_imgc                     |t        j                         }t        |||      }|j                  dk(  r0|dk(  s|dk(  r&t	        j
                  d       |j                  d      } |j                  | fd|i| y)	aj  Saves an image stored as a Numpy array to a path or file object.

    Args:
        path: Path or file object.
        x: Numpy array.
        data_format: Image data format, either `"channels_first"` or
          `"channels_last"`.
        file_format: Optional file format override. If omitted, the format to
          use is determined from the filename extension. If a file object was
          used instead of a filename, this parameter should always be used.
        scale: Whether to rescale image values to be within `[0, 255]`.
        **kwargs: Additional keyword arguments passed to `PIL.Image.save()`.
    N)r_   r`   rP   jpgjpegz?The JPG format does not support RGBA images, converting to RGB.rQ   rE   )r   rT   rb   modewarningswarnconvertsave)pathr0   r_   file_formatr`   kwargsr2   s          r>   save_imgrq   R  sw     //1
qk
?C
xx6{e3{f7LM	
 kk% CHHT0+00r@   zkeras.utils.load_imgz"keras.preprocessing.image.load_imgc           	         |rt        j                  d       d}t        t        d      t	        | t
        j                        rt        j                  |       }nt	        | t        j                  t        t        f      rt	        | t        j                        rt        | j                               } t        | d      5 }t        j                  t        j                  |j                                     }ddd       nt        dt        |              |dk(  r j                   dvri|j#                  d      }nW|d	k(  r!j                   d
k7  rC|j#                  d
      }n1|dk(  r!j                   dk7  r|j#                  d      }nt%        d      ||d   |d   f}|j&                  |k7  r|t(        vr<t%        dj+                  |dj-                  t(        j/                                           t(        |   }	|rr|j&                  \  }
}|\  }}|
|z  |z  }||z  |z  }t1        ||      }t1        |
|      }||z
  dz  }|
|z
  dz  }||z   }||z   }||||g}|j3                  ||	|      }|S |j3                  ||	      }|S # 1 sw Y   vxY w)a  Loads an image into PIL format.

    Usage:

    ```python
    image = tf.keras.utils.load_img(image_path)
    input_arr = tf.keras.utils.img_to_array(image)
    input_arr = np.array([input_arr])  # Convert single image to a batch.
    predictions = model.predict(input_arr)
    ```

    Args:
        path: Path to image file.
        grayscale: DEPRECATED use `color_mode="grayscale"`.
        color_mode: One of `"grayscale"`, `"rgb"`, `"rgba"`. Default: `"rgb"`.
          The desired image format.
        target_size: Either `None` (default to original size) or tuple of ints
          `(img_height, img_width)`.
        interpolation: Interpolation method used to resample the image if the
          target size is different from that of the loaded image. Supported
          methods are `"nearest"`, `"bilinear"`, and `"bicubic"`. If PIL version
          1.1.3 or newer is installed, `"lanczos"` is also supported. If PIL
          version 3.4.0 or newer is installed, `"box"` and `"hamming"` are also
          supported. By default, `"nearest"` is used.
        keep_aspect_ratio: Boolean, whether to resize images to a target
                size without aspect ratio distortion. The image is cropped in
                the center with target aspect ratio before resizing.

    Returns:
        A PIL Image instance.

    Raises:
        ImportError: if PIL is not available.
        ValueError: if interpolation method is not supported.
    z<grayscale is deprecated. Please use color_mode = "grayscale"	grayscaleNz?Could not import PIL.Image. The use of `load_img` requires PIL.rbz,path should be path-like or io.BytesIO, not )rS   zI;16rR   rS   rgbarP   rgbrQ   z0color_mode must be "grayscale", "rgb", or "rgba"rM   r   zCInvalid interpolation method {} specified. Supported methods are {}z, r   )r
   )rj   rk   rV   rW   r,   ioBytesIOopenpathlibPathbytesstrresolveread	TypeErrortyperi   rl   r    r   _PIL_INTERPOLATION_METHODSrE   joinrF   r[   r*   )rn   rs   
color_modetarget_sizer1   keep_aspect_ratior2   fwidth_height_tupleresampler4   r3   r6   r5   r8   r9   r:   r;   crop_box_wendcrop_box_hendcrop_boxs                        r>   load_imgr   l  s   X J	
 !
M
 	
 $

#nnT"	D7<<4	5dGLL)t||~&D$ 	7..AFFH!56C	7 	7 :4:,G
 	
 [  88--++c"C	v	88v++f%C	u	88u++e$CKLL)!nk!n=88))$>> %%+V%		"<"A"A"CD&  2-@H  #v.@+m$}4E$|3E
 "&+6 
3
#)K#7A"=#(:#5!"; /* < /+ =##!!	 jj!3X8jL J jj!3X>Ju	7 	7s   ?7JJ)r   )NTN)NN)NNT)Frv   Nr   F)+__doc__rw   rz   rj   r/   r-   tensorflow.compat.v2compatv2r!   tf_keras.srcr    tensorflow.python.util.tf_exportr   PILr   rV   
Resamplingpil_image_resamplingAttributeErrorrW   NEARESTBILINEARBICUBICHAMMINGBOXLANCZOSr   r)   ResizeMethodNEAREST_NEIGHBORAREALANCZOS3LANCZOS5GAUSSIANMITCHELLCUBICrC   r?   rG   rb   re   rq   r    r@   r>   <module>r      s   + 
    ! !   :	 &)(33 #'//(11'//'//#'''//" xx$$ %%,,##%%%%%%!//	  62>y ?yx4  HKFKF\  H22j $&JK1 L12 $&JK s LsU
  )()  I s.   E E EE EE 	E)(E)