Search code examples
pythonmatplotlibpythonanywhere

Pythonanywhere: matplotlib.pyplot.imgopen creates a numpy.array that cannot be modified


I am having a problem editing the pixels of an image using matplotlib.

Python 3.7.5 (default, Nov 14 2019, 22:26:37) 
>>> import matplotlib.pyplot as plt
>>> img = plt.imread('allo.JPG')
>>> img[0][0]
array([255, 255, 255], dtype=uint8)
>>> img[0][0][1]
255
>>> img[0][0][1]=40
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ValueError: assignment destination is read-only

I've explored the error in various ways to no avail. Ideas?


Solution

  • The writeable flag is set to False for that img array.

    You can make a copy and it will have the flag set to True:

    >>> img.flags
      C_CONTIGUOUS : True
      F_CONTIGUOUS : False
      OWNDATA : False
      WRITEABLE : False
      ALIGNED : True
      WRITEBACKIFCOPY : False
      UPDATEIFCOPY : False
    
    >>> img1 = img.copy()
    >>> img1.flags
      C_CONTIGUOUS : True
      F_CONTIGUOUS : False
      OWNDATA : True
      WRITEABLE : True
      ALIGNED : True
      WRITEBACKIFCOPY : False
      UPDATEIFCOPY : False