Supratim Haldar
Supratim Haldar

Reputation: 2426

Keras flow_from_directory() read only from selected sub-directories

I have a directory structure as follows.

train
|- dog --> contains image files of dogs
|- cat --> contains image files of cats
|- elephant --> contains image files of elephants

I want to train a CNN to identify animals, but only for cats and dogs and not elephants.

I want to use keras ImageDataGenerator class to augment data and flow_from_directory() method to read the image files.

train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(directory='train', class_mode='categorical', target_size=(64,64), batch_size=16, shuffle=True)

The above code will read data from all sub-directories of 'train', which I don't want. One option is to create a new directory and copy of 'dog' and 'cat' sub-directories along with the files inside it. But is there a way to control it from flow_from_directory() method itself?

Upvotes: 8

Views: 3967

Answers (1)

gorjan
gorjan

Reputation: 5575

Assuming that I understood your question in the right way, this should help you:

train_generator = train_datagen.flow_from_directory(directory='train', class_mode='categorical', target_size=(64,64), batch_size=16, shuffle=True, classes=["dog", "cat"])

This will read only the images from the directories dog and cat, leave out the elephant directory and provide distinct categorical labels for them.

Upvotes: 16

Related Questions