如何在不使用model.fit_generator的情况下将旋转应用于Keras中的图像? [英] How can I apply rotation to image in Keras without using model.fit_generator?
问题描述
我正在使用卷积神经网络研究图像像素分类问题.
我的训练images
的大小为128x128x3
,而
标签mask
是128x128
I am working on an image pixel classification problem using convolution neural nets.
The size of my training images
is 128x128x3
and the size of
the label mask
is 128x128
我在Keras进行如下培训:
I do training in Keras as follows:
Xtrain, Xvalid, ytrain, yvalid = train_test_split(images, masks,test_size=0.3, random_state=567)
model.fit(Xtrain, ytrain, batch_size=32, epochs=20, verbose=1, shuffle=True, validation_data=(Xvalid, yvalid))
但是,我想对Xtrain
和ytrain
分别应用随机2D旋转,其大小也分别为128x128x3
和128x128
.更具体地说,我想将此旋转应用于每个时代迭代.
However, I want to apply a Random 2D rotation to Xtrain
and ytrain
which is also of size 128x128x3
and 128x128
respectively. More specifically, I want to apply this rotation for every epoch iteration.
暂时,我想继续使用model.fit
而不使用model.fit_generator
,因为我知道数据增强通常是使用.fit_generator
进行的.
For the time being, I would like to continue using model.fit
and not use model.fit_generator
, as I know data augmentation is commonly done using .fit_generator
.
所以从本质上讲,我想循环model.fit
,以便每个时期随机旋转Xtrain
和ytrain
.我是Python和Keras的新手,所以即使有可能,欢迎提供任何见识.
So essentially, I want to loop model.fit
so that Xtrain
and ytrain
is randomly rotated for every epoch. I am new to Python and Keras so any insights are welcome if this is even possible.
推荐答案
下面是使用ImageDataGenerator将输出保存到指定目录的示例,从而避免了使用model.fit_generator的要求.
Here's an exmaple of using ImageDataGenerator to save the output to a specified directory, thus getting around the requirement to use model.fit_generator.
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')
img = load_img('data/train/cats/cat.0.jpg') # this is a PIL image
x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)
# the .flow() command below generates batches of randomly transformed images
# and saves the results to the `preview/` directory
i = 0
for batch in datagen.flow(x, batch_size=1,
save_to_dir='preview', save_prefix='cat', save_format='jpeg'):
i += 1
if i > 20:
break # otherwise the generator would loop indefinitely
来自此处: https ://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html
您可以更改参数以适合您的用例,然后生成X_train和X_valid或任何数据集,然后加载到内存中并使用简单的旧model.fit.
You can change the args to suit your use case and then generate your X_train and X_valid or whatever datasets, then load into memory and use plain old model.fit.
这篇关于如何在不使用model.fit_generator的情况下将旋转应用于Keras中的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!