如何在keras中使用ImageDataGenerator和flow_from_directory保存调整大小的图像
问题描述:
我正在使用以下代码调整存储在文件夹(两个类)中的RGB图像的大小:
I am resizing my RGB images stored in a folder(two classes) using following code:
from keras.preprocessing.image import ImageDataGenerator
dataset=ImageDataGenerator()
dataset.flow_from_directory('/home/1',target_size=(50,50),save_to_dir='/home/resized',class_mode='binary',save_prefix='N',save_format='jpeg',batch_size=10)
我的数据树如下:
1/
1_1/
img1.jpg
img2.jpg
........
1_2/
IMG1.jpg
IMG2.jpg
........
resized/
1_1/ (here i want to save resized images of 1_1)
2_2/ (here i want to save resized images of 1_2)
运行代码后,我得到以下输出,但没有图像:
After running the code i am getting following output but not images:
Found 271 images belonging to 2 classes.
Out[12]: <keras.preprocessing.image.DirectoryIterator at 0x7f22a3569400>
如何保存图像?
答
在这里提供了一个非常简单的版本,可以在任意位置保存一个图像的增强图像:
Heres a very simple version of saving augmented images of one image wherever you want:
在这里我们弄清楚我们想要对原始图像进行哪些更改并生成增强后的图像
您可以在此处阅读有关差异效果的信息- https://keras.io/preprocessing/image/
Here we figure out what changes we want to make to the original image and generate the augmented images
You can read up about the diff effects here- https://keras.io/preprocessing/image/
datagen = ImageDataGenerator(rotation_range=10, width_shift_range=0.1,
height_shift_range=0.1,shear_range=0.15,
zoom_range=0.1,channel_shift_range = 10, horizontal_flip=True)
步骤2:在这里,我们选择原始图像对图像进行增强
读入图像
Step 2: Here we pick the original image to perform the augmentation on
read in the image
image_path = 'C:/Users/Darshil/gitly/Deep-Learning/My
Projects/CNN_Keras/test_augment/caty.jpg'
image = np.expand_dims(ndimage.imread(image_path), 0)
第3步:选择要保存增强图像的位置
save_here = 'C:/Users/Darshil/gitly/Deep-Learning/My
Projects/CNN_Keras/test_augment'
步骤4.我们拟合原始图像
datagen.fit(image)
第5步:遍历图像并使用"save_to_dir"参数保存
for x, val in zip(datagen.flow(image, #image we chose
save_to_dir=save_here, #this is where we figure out where to save
save_prefix='aug', # it will save the images as 'aug_0912' some number for every new augmented image
save_format='png'),range(10)) : # here we define a range because we want 10 augmented images otherwise it will keep looping forever I think
pass