Keras 自定义图像预处理功能出现值错误"输出数组是只读的"



我想在Keras中使用一些自定义的图像预处理函数以及ImageDataGenerator函数。例如,我的自定义函数如下所示:

def customizedDataAugmentation(x):
choice = np.random.choice(np.arange(1, 4), p=[0.3, 0.3, 0.4])
if choice==1:
x = exposure.adjust_gamma(x, np.random.uniform(0.5,1.5))
elif choice==2:
ix = Image.fromarray(np.uint8(x))
blurI = ix.filter(ImageFilter.GaussianBlur(np.random.uniform(0.1,2.5)))
x = np.asanyarray(blurI)
return x

使用它的方式是这样的:

self.train_datagen = image.ImageDataGenerator(
rescale=1./255,
zoom_range=0.15,
height_shift_range=0.1,
horizontal_flip=True,
preprocessing_function=customizedDataAugmentation
)

但是,当我开始训练时,它会跳出此错误:

Traceback (most recent call last):
File "/home/joseph/miniconda3/envs/py27/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/home/joseph/miniconda3/envs/py27/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/joseph/miniconda3/envs/py27/lib/python2.7/site-packages/keras/utils/data_utils.py", line 560, in data_generator_task
generator_output = next(self._generator)
File "/home/joseph/miniconda3/envs/py27/lib/python2.7/site-packages/keras/preprocessing/image.py", line 1039, in next
x = self.image_data_generator.standardize(x)
File "/home/joseph/miniconda3/envs/py27/lib/python2.7/site-packages/keras/preprocessing/image.py", line 494, in standardize
x *= self.rescale
ValueError: output array is read-only

self.image_data_generator.standardize(x)是调用自定义函数的函数。定义如下所示:

def standardize(self, x):
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
....

如果我不调用我的自定义函数,我就不会有这个错误。 有人知道发生了什么吗?

当我遇到此错误时,我发现我的 numpy 数组不可写,您可以检查一下

print(x.flags)

您可以使用以下命令使数组可写

x.setflags(write=1)

在归还之前。

另请参阅:np 数组不可变 - "赋值目标是只读的">

我已经将 keras 版本从 2.3.0 降级到 2.2.0,它解决了这个错误

最新更新