a
    +=icW0                     @   s$  d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZ	zddl
mZ ddl
mZ W n ey~   dZdZY n0 edurejejejdZeed	rejed
< eedrejed< eedrejed< dd Zd&ddZd'ddZd(ddZdd Zdd  Zd)d"d#Zd*d$d%ZdS )+z9Utilities for real-time data augmentation on image data.
    )absolute_import)division)print_functionN)ImageEnhance)Image)nearestZbilinearZbicubicHAMMINGZhammingBOXboxLANCZOSZlanczosc                 C   s   |   |otj| S )zCheck if a filename refers to a valid file.

    # Arguments
        filename: String, absolute path to a file
        white_list_formats: Set, allowed file extensions

    # Returns
        A boolean value indicating if the filename is valid or not
    )lowerendswithospathisfile)filenamewhite_list_formats r   p/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/keras_preprocessing/image/utils.pyvalidate_filename%   s    

r   channels_lastTc                 K   sV   t |||d}|jdkr<|dks(|dkr<td |d}|j| fd|i| dS )	a~  Saves an image stored as a Numpy array to a path or file object.

    # Arguments
        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()`.
    )data_formatscaleRGBAjpgjpegz?The JPG format does not support RGBA images, converting to RGB.RGBformatN)array_to_imgmodewarningswarnconvertsave)r   xr   Zfile_formatr   kwargsimgr   r   r   save_img3   s
    

r'   Frgbr   c           	   	   C   s,  |du rt d d}tdu r&tdt| d}tt| }|dkrd|jdvr|	d}nD|d	kr|jd
kr|	d
}n&|dkr|jdkr|	d}nt
d|dur|d |d f}|j|kr|tvrt
d|dt t| }|||}|W  d   S 1 s0    Y  dS )a(  Loads an image into PIL format.

    # Arguments
        path: Path to image file.
        grayscale: DEPRECATED use `color_mode="grayscale"`.
        color_mode: The desired image format. One of "grayscale", "rgb", "rgba".
            "grayscale" supports 8-bit images and 32-bit signed integer images.
            Default: "rgb".
        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.
            Default: "nearest".

    # Returns
        A PIL Image instance.

    # Raises
        ImportError: if PIL is not available.
        ValueError: if interpolation method is not supported.
    Tz<grayscale is deprecated. Please use color_mode = "grayscale"	grayscaleNz?Could not import PIL.Image. The use of `load_img` requires PIL.rb)LzI;16Ir+   Zrgbar   r(   r   z0color_mode must be "grayscale", "rgb", or "rgba"   r   zCInvalid interpolation method {} specified. Supported methods are {}z, )r    r!   	pil_imageImportErroropenioBytesIOreadr   r"   
ValueErrorsize_PIL_INTERPOLATION_METHODSr   joinkeysresize)	r   r)   Z
color_modeZtarget_sizeinterpolationfr&   Zwidth_height_tupleZresampler   r   r   load_imgO   s<    




r<   r   r   ZbmpZpngppmZtifZtiffc                    s:   t dd t tr fn D   fddt| D S )a  Lists all pictures in a directory, including all subdirectories.

    # Arguments
        directory: string, absolute path to the directory
        ext: tuple of strings or single string, extensions of the pictures

    # Returns
        a list of paths
    c                 s   s   | ]}d | V  qdS )z.%sNr   ).0er   r   r   	<genexpr>       z list_pictures.<locals>.<genexpr>c                    s8   g | ]0\}}}|D ] }|   rtj||qqS r   )r   r   r   r   r7   )r?   root_filesr;   extr   r   
<listcomp>   s   z!list_pictures.<locals>.<listcomp>)tuple
isinstancestrr   walk)	directoryrG   r   rF   r   list_pictures   s    "
rN   c                 #   sb    fdd}|| D ]H\}}}t |D ]4}| drBtd | |r&||fV  q&qdS )a  Iterates on files with extension in `white_list_formats` contained in `directory`.

    # Arguments
        directory: Absolute path to the directory
            containing files to be counted
        white_list_formats: Set of strings containing allowed extensions for
            the files to be counted.
        follow_links: Boolean, follow symbolic links to subdirectories.

    # Yields
        Tuple of (root, filename) with extension in `white_list_formats`.
    c                    s   t tj|  ddd dS )N)followlinksc                 S   s   | d S )Nr   r   )r$   r   r   r   <lambda>   rB   z<_iter_valid_files.<locals>._recursive_list.<locals>.<lambda>)key)sortedr   rL   )subpathfollow_linksr   r   _recursive_list   s    z*_iter_valid_files.<locals>._recursive_listz.tiffzYUsing ".tiff" files with multiple bands will cause distortion. Please verify your output.N)rR   r   r   r    r!   )rM   r   rU   rV   rC   rD   rE   fnamer   rT   r   _iter_valid_files   s    
rX   c                 C   s   t j| }|rXtt| ||}t|}t|d | t|d |  }}	|||	 }
nt| ||}
g }g }|
D ]F\}}|||  t j||}t j|t j	|| }|| qp||fS )aC  Lists paths of files in `subdir` with extensions in `white_list_formats`.

    # Arguments
        directory: absolute path to a directory containing the files to list.
            The directory name is used as class label
            and must be a key of `class_indices`.
        white_list_formats: set of strings containing allowed extensions for
            the files to be counted.
        split: tuple of floats (e.g. `(0.2, 0.6)`) to only take into
            account a certain fraction of files in each directory.
            E.g.: `segment=(0.6, 1.0)` would only account for last 40 percent
            of images in each directory.
        class_indices: dictionary mapping a class name to its index.
        follow_links: boolean, follow symbolic links to subdirectories.

    # Returns
         classes: a list of class indices
         filenames: the path of valid files in `directory`, relative from
             `directory`'s parent (e.g., if `directory` is "dataset/class1",
            the filenames will be
            `["class1/file1.jpg", "class1/file2.jpg", ...]`).
    r   r-   )
r   r   basenamelistrX   lenintappendr7   relpath)rM   r   splitZclass_indicesrU   dirname	all_filesZ	num_filesstartstopZvalid_filesclasses	filenamesrC   rW   Zabsolute_pathrelative_pathr   r   r   "_list_valid_filenames_in_directory   s*    "rg   float32c                 C   sV  t du rtdtj| |d} | jdkr8td| jf |dvrLtd| |dkrb| d	d
d} |r| t|  } t	| }|dkr| | } | d9 } | jd
 dkrt 
| ddS | jd
 dkrt 
| ddS | jd
 d	kr>t	| dkrt 
| dddddf ddS t 
| dddddf ddS td| jd
 f dS )aY  Converts a 3D Numpy array to a PIL Image instance.

    # Arguments
        x: Input Numpy array.
        data_format: Image data format, either "channels_first" or "channels_last".
            Default: "channels_last".
        scale: Whether to rescale the image such that minimum and maximum values
            are 0 and 255 respectively.
            Default: True.
        dtype: Dtype to use.
            Default: "float32".

    # 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.dtype   zLExpected image array to have rank 3 (single image). Got array with shape: %s   r   channels_firstzInvalid data_format: %srm   r-      r         Zuint8r   r   int32r,   r+   zUnsupported channel number: %s)r.   r/   npasarrayndimr4   shape	transposeminmaxZ	fromarrayZastype)r$   r   r   rj   Zx_maxr   r   r   r      s4    

$$r   c                 C   s   |dvrt d| tj| |d}t|jdkrH|dkr|ddd}nbt|jdkr|dkr||d|jd |jd f}q||jd |jd df}nt d	|jf |S )
ar  Converts a PIL Image instance to a Numpy array.

    # Arguments
        img: PIL Image instance.
        data_format: Image data format,
            either "channels_first" or "channels_last".
        dtype: Dtype to use for the returned array.

    # Returns
        A 3D Numpy array.

    # Raises
        ValueError: if invalid `img` or `data_format` is passed.
    rl   zUnknown data_format: %sri   rk   rm   rn   r   r-   zUnsupported image shape: %s)r4   rr   rs   r[   ru   rv   Zreshape)r&   r   rj   r$   r   r   r   img_to_array!  s    ry   )r   NT)Fr(   Nr   )r=   )r   Trh   )r   rh   )__doc__
__future__r   r   r   r1   r   r    numpyrr   ZPILr   r   r.   r/   ZNEARESTZBILINEARZBICUBICr6   hasattrr   r	   r   r   r'   r<   rN   rX   rg   r   ry   r   r   r   r   <module>   sJ   






   
  
?
.
: