我想通过下面的代码对Keras(像素值只有0和1)的8*8像素灰度图像进行数据扩增:
from ctypes import sizeof
from re import X
from turtle import shape
from keras.preprocessing.image import ImageDataGenerator
from skimage import io
import numpy as np
from PIL import Image
datagen = ImageDataGenerator(
rotation_range=45, #Random rotation between 0 and 45
width_shift_range=0.2, #% shift
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest') #Also try nearest, constant, reflect, wrap
# forming a binary 8*8 array
array = np.array([[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,0]])
# scale values to uint8 maximum 255, and convert it to greyscale image
array = ((array) * 255).astype(np.uint8)
x = Image.fromarray(array)
i = 0
for batch in datagen.flow(x, batch_size=16,
save_to_dir='augmented',
save_prefix='aug',
save_format='png'):
i += 1
if i > 20:
break # otherwise the generator would loop indefinitely
但是我在输出中得到这个错误(当我有.flow
函数时):
ValueError: ('Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape', (8, 8))
有人能给予我一下吗?
1条答案
按热度按时间c9qzyr3d1#
ImageDataGenerator
接受4维Tensor输入,其中第一维是样本编号,最后一维是颜色通道。在代码中,您应该将此(8,8)
Tensor转换为(1,8,8,1)
Tensor。这可以通过以下方式完成:此外,在将数组传递给生成器之前,不应将其转换为图像,就像此处所做的那样
您只需将
array
传递给生成器。