简体   繁体   English

如何通过 keras.load_img 加载多个图像并为 CNN model 增加每个图像

[英]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.我想创建一个 CNN model 来对 10 种不同的汽车进行分类。 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.由于一次做一张图像很忙,我为它编写了一个 for 循环,它显示了一个错误。

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
    

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.您不需要遍历图像并应用ImageDataGenerator而是只需在图像路径上使用创建的ImageDataGenerator ,它会为您即时执行。 In order to get the images, you can call next() on the generator.为了获取图像,您可以在生成器上调用next()

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM