
    2Vh?A                        d Z ddlZddlZddlZddlZddlmZ ddlm	Z	 	 ddl
mZ 	 ej                  ZeEej"                  ej$                  ej&                  ej(                  ej*                  ej,                  dZ e	ddg      dd	       Z e	d
dg      dd       Z e	ddg      dd       Z e	ddg      	 	 	 	 dd       Z e	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lanczosz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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.

    Example:

    ```python
    from PIL import Image
    img = np.random.random(size=(100, 100, 3))
    pil_img = 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"`. Defaults to `None`, in which case the global
            setting `keras.backend.image_data_format()` is used (unless you
            changed it, it defaults to `"channels_last"`).
        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` means the global setting
            `keras.backend.floatx()` is used (unless you changed it, it
            defaults to `"float32"`). Defaults to `None`.

    Returns:
        A PIL Image instance.
    NzCCould not import PIL.Image. The use of `array_to_img` requires PIL.dtype   zJExpected image array to have rank 3 (single image). Got array with shape: channels_first      r         uint8RGBARGBint32ILzUnsupported channel number: )r   standardize_data_formatfloatx	pil_imageImportErrornpasarrayndim
ValueErrorshape	transposeminmax	fromarrayastype)xdata_formatscaler   x_maxs        K/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/utils/image_utils.pyarray_to_imgr.   #   s   B 11+>K} 6
 	
 	

1E"Avv{%%&WWI/
 	
 &&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E    zkeras.utils.img_to_arrayz&keras.preprocessing.image.img_to_arrayc                    t        j                  |      }|t        j                         }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.

    Example:

    ```python
    from PIL import Image
    img_data = np.random.random(size=(100, 100, 3))
    img = keras.utils.array_to_img(img_data)
    array = 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"`. Defaults to `None`, in which case the global
            setting `keras.backend.image_data_format()` is used (unless you
            changed it, it defaults to `"channels_last"`).
        dtype: Dtype to use. `None` means the global setting
            `keras.backend.floatx()` is used (unless you changed it, it
            defaults to `"float32"`).

    Returns:
        A 3D NumPy array.
    r   r   r   r   r   r   zUnsupported image shape: )
r   r   r   r   r    lenr#   r$   reshaper"   )imgr*   r   r)   s       r-   img_to_arrayr4   n   s    @ 11+>K}  	

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)	ap  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()`.
    )r*   r+   r   jpgjpegz?The JPG format does not support RGBA images, converting to RGB.r   formatN)r   r   r.   modewarningswarnconvertsave)pathr)   r*   file_formatr+   kwargsr3   s          r-   save_imgrA      ss     11+>K
qk
?C
xx6{e3{f7LM	
 kk% CHHT0+00r/   zkeras.utils.load_imgz"keras.preprocessing.image.load_imgc           	         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  }t-        |
|      }t-        |	|      }|
|z
  dz  }|	|z
  dz  }||z   }||z   }||||g}|j/                  |||      }|S |j/                  ||      }|S # 1 sw Y   vxY w)a  Loads an image into PIL format.

    Example:

    ```python
    image = keras.utils.load_img(image_path)
    input_arr = 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.
        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.
    Nz?Could not import PIL.Image. The use of `load_img` requires PIL.rbz,path should be path-like or io.BytesIO, not 	grayscale)r   zI;16r   r   rgbar   rgbr   z0color_mode must be "grayscale", "rgb", or "rgba"r   r   zCInvalid interpolation method {} specified. Supported methods are {}z, r   )r
   )r   r   
isinstanceioBytesIOopenpathlibPathbytesstrresolveread	TypeErrortyper9   r<   r"   sizePIL_INTERPOLATION_METHODSr8   joinkeysr%   resize)r>   
color_modetarget_sizeinterpolationkeep_aspect_ratior3   fwidth_height_tupleresamplewidthheighttarget_widthtarget_heightcrop_height
crop_widthcrop_box_hstartcrop_box_wstartcrop_box_wendcrop_box_hendcrop_boxs                       r-   load_imgrj      s   N 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%		";"@"@"BC&  1?H  #v.@+m$}4E$|3E
 "&+6 
3
#)K#7A"=#(:#5!"; /* < /+ =##!!	 jj!3X8jL J jj!3X>Ju	7 	7s   &7I))I3z&keras.preprocessing.image.smart_resizec                    |xs t         }t        |      dk7  rt        d| d      |j                  |       }t        |j                        It        |j                        dk  st        |j                        dkD  rt        d|j                   d      |j	                  |      }|dk(  r|d	   |d
   }}n
|d
   |d   }}|\  }	}
t        |t              rt        |t              rt        t        ||	z        |
z        }t        t        ||      d      }t        t        ||
z        |	z        }t        t        ||      d      }t        t        ||z
        dz        }t        t        ||z
        dz        }n4|j                  |j                  ||	z  d      |
z  d      }|j                  j                  ||      }|j                  j                  |d      }|j                  |d      }|j                  |j                  ||
z  d      |	z  d      }|j                  j                  ||      }|j                  j                  |d      }|j                  |d      }|j                  |j                  ||z
  d      dz  d      }|j                  |j                  ||z
  d      dz  d      }|dk(  rEt        |j                        dk(  r|dd|||z   |||z   ddf   }nY||||z   |||z   ddf   }nDt        |j                        dk(  r|dddd|||z   |||z   f   }n|dd|||z   |||z   f   }|j                  j                  ||||      }t        | t         j"                        rt!        j$                  |      S |S )a	  Resize images to a target size without aspect ratio distortion.

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

    You could simply do, in TF (or JAX equivalent):

    ```python
    size = (200, 200)
    ds = ds.map(lambda img: 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 image generation models
    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.

    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"`,
            `"lanczos3"`, `"lanczos5"`.
            Defaults to `"bilinear"`.
        data_format: `"channels_last"` or `"channels_first"`.
        backend_module: Backend module to use (if different from the default
            backend).

    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 backend-native tensor,
        the output is a backend-native tensor.
    r   z6Expected `size` to be a tuple of 2 integers, but got: .Nr   r   zExpected an image array with shape `(height, width, channels)`, or `(batch_size, height, width, channels)`, but got input with incorrect rank, of shape channels_lastr   float32r   )rS   rZ   r*   )r   r1   r"   convert_to_tensorr#   rG   intfloatr&   r%   castnumpyminimummaximumimagerW   r   ndarrayarray)r)   rS   rZ   r*   backend_moduler3   r#   r`   r_   rb   ra   rc   rd   re   rf   s                  r-   smart_resizer}   (  s   L $.wN
4yA~DTF!L
 	
 
*
*1
-C
399~!syy>ASYY!!3;;>99+QH 
   %Eo%b	59b	59"&M< &#:eS#9% 56EF#fk2A6v45EF
UJ/3
eF[$89A=>eEJ$67!;<$)) 5yA

 %**226;G$**22;B$))+w?#(( 5yA


 $))11%D
#))11*a@
#((W=
(-- 4i@1Dg
 )--
 2I>BG
 o%syy>Q/K"??/J">>C /K"??/J">>C syy>Q/K"??/J">>@C /K"??/J">>@C 


%
%$m & C !RZZ xx}Jr/   )NTN)NN)NNT)rF   Nr   F)r   rm   N)__doc__rH   rK   r:   rv   r   	keras.srcr   keras.src.api_exportr   PILr   r   
Resamplingpil_image_resamplingAttributeErrorr   NEARESTBILINEARBICUBICHAMMINGBOXLANCZOSrT   r.   r4   rA   rj   r}    r/   r-   <module>r      sr   * 	     -	 &)(33 #'//(11'//'//#'''//! "0BFBFJ "0++\ %'KLM1 N10 %'KLM i NiX 67 ` 8`q  )()  I s.   C" C CC" CC" "	C.-C.