keras如何实现批量数据增强(附代码)

import skimage.io as io
import os,sys
from skimage import data_dir
import numpy as np

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')
path="/home/public/桌面/hongyi/trainA/";     
dirs=os.listdir(path)
x_all=[]
for file in dirs:
    img = load_img(path+file)
    x = img_to_array(img)  
    x = x.reshape((1,) + x.shape)  # 这是一个numpy数组,形状为 (1, 3, 150, 150)
    x_all.append(x)
    i = 0
    for batch in datagen.flow(x, batch_size=1,
                          save_to_dir='/home/public/桌面/hongyi/results1'):
       i += 1
       if i > 50:             # 数据扩充倍数,此处为数据扩充50倍
        break             #  否则生成器会退出循环

rotation_range: 旋转范围, 随机旋转(0-180)度;
width_shift and height_shift: 随机沿着水平或者垂直方向,以图像的长宽小部分百分比为变化范围进行平移;
rescale: 对图像按照指定的尺度因子, 进行放大或缩小, 设置值在0 - 1之间,通常为1 / 255;
shear_range: 水平或垂直投影变换, 参考这里 https://keras.io/preprocessing/image/
zoom_range: 按比例随机缩放图像尺寸;
horizontal_flip: 水平翻转图像;
fill_mode: 填充像素, 出现在旋转或平移之后.

你可能感兴趣的:(实用代码总结)