簡體   English   中英

如何通過 keras.load_img 加載多個圖像並為 CNN model 增加每個圖像

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

我想創建一個 CNN model 來對 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
    

您不需要遍歷圖像並應用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM