0

I want to use some customized image preprocessing function along with ImageDataGenerator function in Keras. For example, my customized function looks like this:

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

And the way to use it is like:

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

However, when I start training, it jumps out this error:

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) is the function that calls the customized function. The definition looks something like this:

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

If I don't call my customized function I wouldn't have this error though. Anyone knows what's happening?

Joseph Zhou
  • 125
  • 1
  • 2
  • 12

2 Answers2

5

When I ran into this error, I found that my numpy array wasn't writable, which you can check with

print(x.flags)

You can make the array writable with

x.setflags(write=1)

before returning it.

See also: np arrays being immutable - "assignment destination is read-only"

-1

I have downgraded keras version from 2.3.0 to 2.2.0 and it solve this error