【问题标题】:how to load multiple images through keras.load_img and data augment each images for CNN model如何通过 keras.load_img 加载多个图像并为 CNN 模型增加每个图像
【发布时间】:2021-01-30 06:15:30
【问题描述】:

我想创建一个 CNN 模型来对 10 种不同的汽车进行分类。首先,我下载了一些图像,现在我想通过数据增强来增加图像的数量。由于一次做一张图片很忙,我为它写了一个 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'

代码:

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
    

【问题讨论】:

    标签: python conv-neural-network data-augmentation


    【解决方案1】:

    您不需要遍历图像并应用ImageDataGenerator,而只需在图像路径上使用创建的ImageDataGenerator,它会为您即时执行。为了获取图片,您可以在生成器上调用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()
    

    【讨论】:

    • 感谢您的帮助。你能告诉我如何从这里开始,如何增强每个 img
    • 如果你想保存增强的图像,只需在 save_to_dirflow_from_directory 中设置路径,就像我在更新的答案中所做的那样。
    • 好的,我已经给出了这样的路径save_to_dir=r'\Users\Mohda\OneDrive\Desktop\daug' 它显示了一个操作 找到属于 1 个类的 18 个图像。但我在此文件夹中没有看到任何图像
    • 图片目录的结构是什么?它需要遵循this structure,但不一定要拆分为train、test和valid。喜欢这个images/train/class1/
    猜你喜欢
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多