首页 > 解决方案 > 在 Python 中使用 Keras 进行图像增强

问题描述

如何为存储在文件夹中的多个图像应用 Keras 图像增强?

PS:我为单个图像尝试了以下代码,并且效果很好。

有人可以帮我解决多张图片吗?

enter code here

from keras.preprocessing import image

import matplotlib.pyplot as plt
import cv2

from keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(
            rotation_range = 30, 
            width_shift_range = 0.2,
            height_shift_range = 0.2, 
            shear_range = 0.2, 
            zoom_range = 0.2,
            horizontal_flip = 0.2,
            fill_mode = "nearest")

for img in glob.glob("Images/*/*.jpg"):
    cv_img = cv2.imread(img)
    cv_resize = cv2.resize(cv_img,(200,200))
    cv_norm_img = cv_resize/255.0
    break


cv_norm_img = np.array(cv_norm_img)

input_batch = cv_norm_img.reshape((1,*cv_norm_img.shape))

i = 0

for output_batch in datagen.flow(input_batch,batch_size=1):
    plt.figure()
    imgplot = plt.imshow(image.img_to_array(output_batch[0]))
    i+=1
    if i==10:
        break
    plt.axis('off')
    plt.show

标签: pythonimageimage-processingkeras

解决方案


最简单的方法是使用目录中的 ImageDataGenerator.flow。文档位于https://keras.io/preprocessing/image/。images 将是一个形状数组 (batch_size, 200, 200, 3) 注意:每次运行它时,它都会在 save_to_dir 中放入更多的图像,因此您可能不想包含该参数。您可以通过 img1=images[0]、img2=images[1] 等方式访问单个图像 如下设置您的生成器

datagen = ImageDataGenerator(rotation_range = 30, width_shift_range = 0.2,
                             height_shift_range = 0.2,
                             shear_range = 0.2, 
                             zoom_range = 0.2,
                             rescale=1/255,
                             horizontal_flip = True,
                             fill_mode = "nearest")
data=datagen.flow_from_directory(your_dir, target_size=(200, 200),
                                 batch_size=your_file_count, shuffle=False,
                                 save_to_dir=your_save_dir,save_format='png',
                                 interpolation='nearest')
images,labels=data.next()


推荐阅读