导入多张图片

时间:2019-01-28 12:20:12

标签: python keras imagedata

我想用以下代码复制我的照片:

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest')

img = load_img('data/class1/11408_3.jpg')
x = img_to_array(img)  
x = x.reshape((1,) + x.shape)

i = 0
for batch in datagen.flow(x, batch_size=1,
                          save_to_dir='preview', save_prefix='class1', save_format='jpeg'):
    i += 1
    if i > 20:
        break 

使用一张图片,一切正常。但是我在这条路上有很多照片。如何获得所有图片-一张一张?

2 个答案:

答案 0 :(得分:0)

您可以使用包含每个文件路径的字符串列表,并将其放入这样的for循环中

filePaths = ['data/class1/11408_3.jpg', ...]
for file in filePaths:
    img = load_img(file)

答案 1 :(得分:0)

感谢您的输入。我现在用以下方法解决了这个问题:

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import glob, os

datagen = ImageDataGenerator(
        rotation_range=90,
        horizontal_flip=True,
        fill_mode='nearest')

os.chdir("dir")
for file in glob.glob("*.png"):
    img = load_img(file)
    x = img_to_array(img)
    x = x.reshape((1,) + x.shape)

    i = 0
    for batch in datagen.flow(x, batch_size=1,save_to_dir='output', save_prefix='new', save_format='jpg'):
        i += 1
        if i > 20:
            break