Search code examples
pythonconv-neural-networkdata-augmentation

how to load multiple images through keras.load_img and data augment each images for CNN model


I want to create a CNN model to classify between 10 different cars. First, I download few images, and now I want to increase the number of images through data augmentation. Since it's hectic to do one image at a time, I have written a for loop for it, and it is showing an error.

TypeError                                 Traceback (most recent call last)
<ipython-input-14-9ced4a120c2d> in <module>
     10 
     11 for i in images:
---> 12     x = img_to_array(images[i])
     13     x = x.reshape((1,) + x.shape)
     14     j=0

~\anaconda3\envs\DSEnv\lib\site-packages\keras_preprocessing\image\iterator.py in __getitem__(self, idx)
     51 
     52     def __getitem__(self, idx):
---> 53         if idx >= len(self):
     54             raise ValueError('Asked to retrieve element {idx}, '
     55                              'but the Sequence '

TypeError: '>=' not supported between instances of 'tuple' and 'int'

Code:

images = ImageDataGenerator().flow_from_directory(r'\Users\Mohda\OneDrive\Desktop\ferrari sf90 stradale')
datagen = ImageDataGenerator(
    rotation_range=30, 
    width_shift_range=0.3,
    height_shift_range=0.3, 
    shear_range=0.2, 
    zoom_range=0.2,
    horizontal_flip=True, 
    vertical_flip=True,
    fill_mode='nearest')

for i in images:
    x = img_to_array(images[i])
    x = x.reshape((1,) + x.shape)
    j=0
    for batch in datagen.flow(x,batch_size=1,save_to_dir='preview',save_prefix='ferrari sf90 stradale',save_format='jpeg'):
        i+=1
        if i>20:
            break
    

Solution

  • You do not need to loop over the images and apply the ImageDataGenerator instead just use the created ImageDataGenerator on the path to the images and it does it on the fly for you. In order to get the images, you can call next() on the generator.

    PATH_TO_IMAGES = r'\Users\Mohda\OneDrive\Desktop\ferrari sf90 stradale'
    
    # Specify whatever augmentation methods you want to use here
    train_datagen = ImageDataGenerator(
            rotation_range=30, 
            width_shift_range=0.3,
            height_shift_range=0.3, 
            shear_range=0.2, 
            zoom_range=0.2,
            horizontal_flip=True, 
            vertical_flip=True,
            fill_mode='nearest')
    
    train_generator = train_datagen.flow_from_directory(
            PATH_TO_IMAGES,
            target_size=(150, 150),
            batch_size=32,
            save_to_dir=/tmp/img-data-gen-outputs
            class_mode='binary')
    
    # Use the generator by calling .next()
    
    train_generator.next()