np arrays being immutable - "assignment destination is read-only"

Solution 1:

Check if the array is writable with

>>> img.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : False
  ALIGNED : True
  UPDATEIFCOPY : False

If WRITEABLEis false, change it with

img.setflags(write=1)

Solution 2:

Since numpy version 1.16.0 the following doesn't work anymore:

img = np.asarray(Image.open(filename))
img.setflags(write=1)

The problem is that now OWNDATA is set to False and you can't set WRITEABLE flag to True. Therefore you should simply do the following:

img = np.array(Image.open(filename))

This will make a copy of array when casting it from Pillow object to numpy array. However I tested time performance in numpy 1.16.0 and haven't found any noticable difference between both methods.

Solution 3:

In this case, I think you are trying to edit the image provided to you by another user and he/she made it uneditable that's why you are getting this error. For your case, you may try to make a copy of the given file and do changes on that file by using .copy().

     img_copy = img.copy()
     prArray = [np.asarray(img_copy)[:, :, 0] for img_copy in problem_images]

And more importantly, I do not think that most of us want to make changes to our original image, that's why I always use .copy() and recommend you to do the same.

Solution 4:

ValueError: cannot set WRITEABLE flag to True of this array array.setflags(write=1) 

Skip the statement using copy the array using np.copy()