python - 我可以只使用 flow() 而不是 flow_from_directory 在 Keras 中增加图像和蒙版吗?

标签 python tensorflow machine-learning keras deep-learning

我一直在尝试使用 Keras 训练 CNN,并将数据增强应用于一系列图像及其分割掩码。在线示例说,为了做到这一点,我应该使用 flow_from_directory() 创建两个单独的生成器,然后压缩它们。

但是我可以只为图像和蒙版设置两个 numpy 数组,使用 flow() 函数并改为执行以下操作:

# Create image generator
data_gen_args = dict(rotation_range=5,
                     width_shift_range=0.1,
                     height_shift_range=0.1,
                     validation_split=0.2)
image_datagen = ImageDataGenerator(**data_gen_args)

seed = 1

# Create training and validation generators including masks
train_generator = image_datagen.flow(images, masks, seed=seed, subset='training')
val_train_generator = image_datagen.flow(images, masks, seed=seed, subset='validation')   

# Train model
model.fit_generator(train_generator, steps_per_epoch=50,
                validation_data = val_train_generator,
                validation_steps = 10, shuffle=True, epochs=20)

如果不是,为什么不呢?似乎如果我运行生成器,我只能输出图像而不能输出蒙版,所以我担心它没有按照我的意愿进行。

最佳答案

您需要一个自定义生成器,对图像和蒙版应用相同的增强。

Keras ImageDataGenerator 采用 2 个参数(图像、标签或 mask )并将转换应用于仅第一个(图像)。您可以在下面使用我的生成器:

# Create image generator
data_gen_args = dict(rotation_range=5,
                     width_shift_range=0.1,
                     height_shift_range=0.1,
                     validation_split=0.2)
image_datagen = ImageDataGenerator(**data_gen_args)

seed = 1

def XYaugmentGenerator(X1, y, seed, batch_size):
    genX1 = gen.flow(X1, y, batch_size=batch_size, seed=seed)
    genX2 = gen.flow(y, X1, batch_size=batch_size, seed=seed)
    while True:
        X1i = genX1.next()
        X2i = genX2.next()

        yield X1i[0], X2i[0]


# Train model
model.fit_generator(XYaugmentGenerator(images, masks, seed, batch_size), steps_per_epoch=np.ceil(float(len(images)) / float(batch_size)),
                validation_data = XYaugmentGenerator(images_valid, masks_valid, batch_size), 
                validation_steps = np.ceil(float(len(images_valid)) / float(batch_size))
, shuffle=True, epochs=20)

关于python - 我可以只使用 flow() 而不是 flow_from_directory 在 Keras 中增加图像和蒙版吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656000/

相关文章:

image-processing - 使用 YOLO 进行车牌检测

python - 更改 tkinter 中滚动条的大小(使用网格布局)

machine-learning - 我应该在最后一个卷积层中使用 3x3 卷积进行语义分割吗?

python - 如何将列表元素转换为 int 并与数字进行比较?

python - 获取input_array和output_array项,将model转为tflite格式

python - Keras/Tensorflow 中的时间分布

tensorflow - 导入错误 : No module named 'tflearn'

machine-learning - 完美的决策树分类

python - 如何测试 Python readline 完成?

Python - 运行 py.test 和覆盖率测试的 tox 中出现调用错误