Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't modify numpy array

I got stuck practising with images in Python 3:

import numpy as np
from matplotlib.image import imread
photo_data = imread('c:\jpeg.jpg')
photo_data[0,0,1] = 0

I get this error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-40-f19579124b68> in <module>()
      1 photo = photo_data
      2 print(type(photo))
----> 3 photo[0,0,1] = 0
      4 plt.imshow(photo_data)

ValueError: assignment destination is read-only

I'm following an online course where this code seems working, can you tell me what I'm getting wrong?

like image 207
the302storm Avatar asked Aug 26 '26 03:08

the302storm


2 Answers

The issue at hand is that the array is set by matplotlib to read-only. To confirm:

print(photo_data.flags)

And you will get:

C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : False
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False

To make it writable, simply:

photo_data.setflags(write=1)
photo_data[0,0,1] = 0
like image 170
Lukasz Tracewski Avatar answered Aug 27 '26 17:08

Lukasz Tracewski


some times, you will get error as below if you try to set write flag to True.

ValueError: cannot set WRITEABLE flag to True of this array

Just make copy of it and work. it is useful instead downgrading the numpy version

photo = photo_data.copy() print(type(photo)) photo[0,0,1] = 0 plt.imshow(photo_data)

like image 33
Madhu Mohan Kommu Avatar answered Aug 27 '26 17:08

Madhu Mohan Kommu