想要扩充一通道图像数据集,但没报错,没扩充,代码如下
# -*- coding: utf-8 -*-
# 载入包
from keras.preprocessing.image import ImageDataGenerator
import os
import time
# 定义扩充图片函数
from keras.utils import load_img, img_to_array
def image_expansion(filepath,savefilepath,multiples=20):
"""
:param filepath: 图片路径
:param savefilepath: 扩充保存图片路径
:param multiples: 扩充倍数,默认扩充20倍
:return: 返回扩充后数据集
"""
# keras中可以通过keras.preprocessing.image.ImageDataGenerator类来实现
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')
for parent, dirnames, filenames in os.walk(filepath):
for filename in filenames:
image_path=filepath+filename
print(image_path)
img = load_img(image_path)
x = img_to_array(img)
x = x.reshape((1,) + x.shape)
i = 1
for batch in datagen.flow(x, batch_size=1,
save_to_dir=savefilepath,
save_prefix='r',
save_format='jpg'):
print('正在扩充图片数据集第'+str(i)+'张')
i += 1
if i >multiples:
break
if __name__ == '__main__':
# 设置图片路径
filepath = 'C:/Users/ASUS/Dektop/R/benign/'
# 设置扩充保存图片路径
savefilepath = 'C:/Users/ASUS/Desktop/R/r-benign/'
time1 = time.time()
image_expansion(filepath,savefilepath,multiples=5)
time2=time.time()
print('总共耗时:' + str(time2 - time1) + 's')