0

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

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

4

2 回答 2

5

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

print(x.flags)

您可以使数组可写

x.setflags(write=1)

在返回之前。

另请参阅:np 数组是不可变的 - “分配目标是只读的”

于 2017-08-20T23:15:35.960 回答
-1

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

于 2021-02-26T23:25:54.193 回答