user2975921
user2975921

Reputation:

ImageDataGenerator on a folder

I have a problem with the code in keras document. In the below code, it just loaded 1 image. if I have 10 images in a folder, how am I going to use this code because load_img function just loading 1 image and I want to load my folder which contains 10 images and apply data generation on all images, Any help?

from keras.preprocessing.image import ImageDataGenerator, 
array_to_img, img_to_array, load_img

datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')

img = load_img('data/train/cats/cat.0.jpg') # this is a PIL image
x = img_to_array(img)
x = x.reshape((1,) + x.shape)

i = 0
for batch in datagen.flow(x, batch_size=1,
save_to_dir='preview', save_prefix='cat', save_format='jpeg'):
i += 1
if i > 20:
break

Upvotes: 1

Views: 3741

Answers (1)

user239457
user239457

Reputation: 1886

You can use flow_from_directory function of ImageDataGenerator and keras will do the thing automatically for you

datagen=ImageDataGenerator()
generator=datagen.flow_from_directory(directory)

edit:
You should have the following folder structure

directory/
    class_label_1/
       image1
       image2
       .
       .
    class_label_2/
       .
       .

Your parent directory should have one folder for each class and that class folder should have the images belonging to that class. The folder name is picked as the label

Upvotes: 4

Related Questions