how to save resized images using ImageDataGenerator and flow_from_directory in keras

前端 未结 4 1917
情深已故
情深已故 2021-02-14 06:47

I am resizing my RGB images stored in a folder(two classes) using following code:

from keras.preprocessing.image import ImageDataGenerator
dataset=ImageDataGener         


        
4条回答
  •  长发绾君心
    2021-02-14 07:21

    In case you want to save the images under a folder having same name as label then you can loop over a list of labels and call the augmentation code within the loop.

    from tensorflow.keras.preprocessing.image import ImageDataGenerator  
    
    # Augmentation + save augmented images under augmented folder
    
    IMAGE_SIZE = 224
    BATCH_SIZE = 500
    LABELS = ['lbl_a','lbl_b','lbl_c']
    
    for label in LABELS:
      datagen_kwargs = dict(rescale=1./255)  
      dataflow_kwargs = dict(target_size=(IMAGE_SIZE, IMAGE_SIZE), 
                            batch_size=BATCH_SIZE, interpolation="bilinear")
    
      train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
        rotation_range=40,
        horizontal_flip=True,
        width_shift_range=0.1, height_shift_range=0.1,
        shear_range=0.1, zoom_range=0.1,
        **datagen_kwargs)
    
      train_generator = train_datagen.flow_from_directory(
          'original_images', subset="training", shuffle=True, save_to_dir='aug_images/'+label, save_prefix='aug', classes=[label], **dataflow_kwargs)
      
      # Following line triggers execution of train_generator
      batch = next(train_generator) 
    

    So why do this when generator can directly be passed to model? In case, you want to use the tflite-model-maker which does not accept a generator and accepts labelled data under folder for each label:

    from tflite_model_maker import ImageClassifierDataLoader
    data = ImageClassifierDataLoader.from_folder('aug_images')
    

    Result

    aug_images
    | 
    |__ lbl_a
    |   |
    |   |_____aug_img_a.png
    |
    |__ lbl_b
    |   |
    |   |_____aug_img_b.png
    | 
    |__ lbl_c
    |   |
    |   |_____aug_img_c.png
    

    Note: You need to ensure the folders already exist.

提交回复
热议问题