Keras自定义图像预处理功能导致值错误“输出数组是只读的”

时间:2017-07-12 01:12:06

标签: python keras valueerror

我想在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
    ....

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

2 个答案:

答案 0 :(得分:2)

当我遇到这个错误时,我发现我的numpy数组不可写,您可以查看

print(x.flags)

您可以使用

使数组可写
x.setflags(write=1)

返回之前。

另请参阅:np arrays being immutable - "assignment destination is read-only"

答案 1 :(得分:-1)

我已将 keras 版本从 2.3.0 降级到 2.2.0 并解决了此错误