a
    +=icB-                     @   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	m
Z
 ze
djZW n eyp   eZY n0 dd	lmZmZmZ G d
d deZG dd dZdS )z9Utilities for real-time data augmentation on image data.
    )absolute_import)division)print_functionN)get_keras_submoduleutils   )array_to_imgimg_to_arrayload_imgc                   @   sl   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )Iteratora  Base class for image data iterators.

    Every `Iterator` must implement the `_get_batches_of_transformed_samples`
    method.

    # Arguments
        n: Integer, total number of samples in the dataset to loop over.
        batch_size: Integer, size of a batch.
        shuffle: Boolean, whether to shuffle the data between epochs.
        seed: Random seeding for data shuffling.
    )ZpngZjpgZjpegZbmpppmZtifZtiffc                 C   sB   || _ || _|| _|| _d| _d| _t | _d | _	| 
 | _d S Nr   )n
batch_sizeseedshufflebatch_indextotal_batches_seen	threadingLocklockindex_array_flow_indexindex_generator)selfr   r   r   r    r   s/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/keras_preprocessing/image/iterator.py__init__$   s    
zIterator.__init__c                 C   s(   t | j| _| jr$t j| j| _d S N)npZaranger   r   r   randomZpermutationr   r   r   r   _set_index_array/   s    zIterator._set_index_arrayc                 C   s   |t | kr"tdj|t | d| jd ur@tj| j| j  |  jd7  _| jd u r`|   | j| j	| | j	|d   }| 
|S )NzEAsked to retrieve element {idx}, but the Sequence has length {length})idxlengthr   )len
ValueErrorformatr   r   r    r   r   r"   r   #_get_batches_of_transformed_samples)r   r#   r   r   r   r   __getitem__4   s    

zIterator.__getitem__c                 C   s   | j | j d | j S )Nr   )r   r   r!   r   r   r   __len__C   s    zIterator.__len__c                 C   s   |    d S r   )r"   r!   r   r   r   on_epoch_endF   s    zIterator.on_epoch_endc                 C   s
   d| _ d S r   )r   r!   r   r   r   resetI   s    zIterator.resetc                 c   s   |    | jd ur&tj| j| j  | jdkr8|   | jdkrHd}n| j| j | j }| j|| j krz|  jd7  _nd| _|  jd7  _| j	||| j  V  qd S )Nr   r   )
r,   r   r   r    r   r   r"   r   r   r   )r   Zcurrent_indexr   r   r   r   L   s    


zIterator._flow_indexc                 C   s   | S r   r   r!   r   r   r   __iter__b   s    zIterator.__iter__c                 O   s   | j |i |S r   )next)r   argskwargsr   r   r   __next__g   s    zIterator.__next__c                 C   s:   | j  t| j}W d   n1 s&0    Y  | |S )zGFor python 2.x.

        # Returns
            The next batch.
        N)r   r.   r   r(   r   r   r   r   r   r.   j   s    (zIterator.nextc                 C   s   t dS )Gets a batch of transformed samples.

        # Arguments
            index_array: Array of sample indices to include in batch.

        # Returns
            A batch of transformed samples.
        N)NotImplementedErrorr2   r   r   r   r(   v   s    	z,Iterator._get_batches_of_transformed_samplesN)__name__
__module____qualname____doc__Zwhite_list_formatsr   r"   r)   r*   r+   r,   r   r-   r1   r.   r(   r   r   r   r   r      s   r   c                   @   sD   e Zd ZdZdd Zdd Zedd Zedd	 Zed
d Z	dS )BatchFromFilesMixinz{Adds methods related to getting batches from filenames

    It includes the logic to transform image files to batches.
    c
                 C   s(  || _ t|| _|dvr$td|d|| _|| _| jdkr`| jdkrR| jd | _qd| j | _nT| jdkr| jdkr| jd | _qd| j | _n$| jdkr| jd	 | _nd	| j | _|| _|| _|| _	|	| _
|d
ur| j j}
|dkrd|
f}n"|dkr|
df}ntd|f nd
}|| _|| _d
S )a   Sets attributes to use later for processing files into a batch.

        # Arguments
            image_data_generator: Instance of `ImageDataGenerator`
                to use for random transformations and normalization.
            target_size: tuple of integers, dimensions to resize input images to.
            color_mode: One of `"rgb"`, `"rgba"`, `"grayscale"`.
                Color mode to read images.
            data_format: String, one of `channels_first`, `channels_last`.
            save_to_dir: Optional directory where to save the pictures
                being yielded, in a viewable format. This is useful
                for visualizing the random transformations being
                applied, for debugging purposes.
            save_prefix: String prefix to use for saving sample
                images (if `save_to_dir` is set).
            save_format: Format to use for saving sample images
                (if `save_to_dir` is set).
            subset: Subset of data (`"training"` or `"validation"`) if
                validation_split is set in ImageDataGenerator.
            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.
        >   Z	grayscalergbargbzInvalid color mode:z); expected "rgb", "rgba", or "grayscale".r:   Zchannels_last)   r;   )   )r   NZ
validationr   Ztrainingr   z;Invalid subset name: %s;expected "training" or "validation")image_data_generatortupletarget_sizer&   
color_modedata_formatimage_shapesave_to_dirsave_prefixsave_formatinterpolationZ_validation_splitsplitsubset)r   r>   r@   rA   rB   rD   rE   rF   rI   rG   Zvalidation_splitrH   r   r   r   set_processing_attrs   sJ    $









z(BatchFromFilesMixin.set_processing_attrsc                    s  t jt f| j | jd}| j}t D ]x\}}t|| | j| j	| j
d}t|| jd}t|drl|  | jr| j|j}| j||}| j|}|||< q*| jrt D ]P\}}t|| | jdd}dj| j|t jd| jd	}	|tj| j|	 q| jd
kr|  }
n| jdv r`t j!t|| jd}
t D ]\}}| j"| |
|< qDn| jdkrt jt|t| j#f| jd}
t D ]\}}d|
|| j"| f< qn>| jdkrԇ fdd| j$D }
n| jdkr| j$  }
n|S | j%du r||
fS ||
| j%  fS dS )r3   )dtype)rA   r@   rG   )rB   closeT)scalez {prefix}_{index}_{hash}.{format}g    cA)prefixindexhashr'   input>   sparsebinaryZcategoricalg      ?Zmulti_outputc                    s   g | ]}|  qS r   r   ).0outputr   r   r   
<listcomp>      zKBatchFromFilesMixin._get_batches_of_transformed_samples.<locals>.<listcomp>rawN)&r   Zzerosr%   rC   rK   	filepaths	enumerater
   rA   r@   rG   r	   rB   hasattrrL   r>   Zget_random_transformshapeZapply_transformZstandardizerD   r   r'   rE   r    randintrF   saveospathjoinZ
class_modecopyemptyclassesZclass_indiceslabelssample_weight)r   r   Zbatch_xrZ   ijZimgxparamsfnameZbatch_yZn_observationr   rV   r   r(      s\    	



z7BatchFromFilesMixin._get_batches_of_transformed_samplesc                 C   s   t dt| jdS )z%List of absolute paths to image filesz;`filepaths` property method has not been implemented in {}.Nr4   r'   typer5   r!   r   r   r   rZ     s
    zBatchFromFilesMixin.filepathsc                 C   s   t dt| jdS )z!Class labels of every observationz8`labels` property method has not been implemented in {}.Nrm   r!   r   r   r   rf     s
    zBatchFromFilesMixin.labelsc                 C   s   t dt| jd S )Nz?`sample_weight` property method has not been implemented in {}.rm   r!   r   r   r   rg   "  s
    z!BatchFromFilesMixin.sample_weightN)
r5   r6   r7   r8   rJ   r(   propertyrZ   rf   rg   r   r   r   r   r9      s   M=

r9   )r8   
__future__r   r   r   r`   r   numpyr   Zkeras_preprocessingr   SequenceZIteratorTypeImportErrorobjectr   r   r	   r
   r   r9   r   r   r   r   <module>   s   
l