how to save resized images using ImageDataGenerator and flow_from_directory in keras

岁酱吖の 提交于 2019-12-05 11:06:25

Heres a very simple version of saving augmented images of one image wherever you want:

Step 1. Initialize image data generator

Here we figure out what changes we want to make to the original image and generate the augmented images
You can read up about the diff effects here- https://keras.io/preprocessing/image/

datagen = ImageDataGenerator(rotation_range=10, width_shift_range=0.1, 
height_shift_range=0.1,shear_range=0.15, 
zoom_range=0.1,channel_shift_range = 10, horizontal_flip=True)

Step 2: Here we pick the original image to perform the augmentation on

read in the image

image_path = 'C:/Users/Darshil/gitly/Deep-Learning/My 
Projects/CNN_Keras/test_augment/caty.jpg'

image = np.expand_dims(ndimage.imread(image_path), 0)

step 3: pick where you want to save the augmented images

save_here = 'C:/Users/Darshil/gitly/Deep-Learning/My 
Projects/CNN_Keras/test_augment'

Step 4. we fit the original image

datagen.fit(image)

step 5: iterate over images and save using the "save_to_dir" parameter

for x, val in zip(datagen.flow(image,                    #image we chose
        save_to_dir=save_here,     #this is where we figure out where to save
         save_prefix='aug',        # it will save the images as 'aug_0912' some number for every new augmented image
        save_format='png'),range(10)) :     # here we define a range because we want 10 augmented images otherwise it will keep looping forever I think
pass

The flow_from_directory method gives you an "iterator", as described in your output. An iterator doesn't really do anything on its own. It's waiting to be iterated over, and only then the actual data will be read and generated.

An iterator in Keras for fitting is to be used like this:

generator = dataset.flow_from_directory('/home/1',target_size=(50,50),save_to_dir='/home/resized',class_mode='binary',save_prefix='N',save_format='jpeg',batch_size=10)

for inputs,outputs in generator:

    #do things with each batch of inputs and ouptus

Normally, instead of doing the loop above, you just pass the generator to a fit_generator method. There is no real need to do a for loop:

model.fit_generator(generator, ......)

Keras will only save images after they're loaded and augmented by iterating over the generator.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!