'Trying to replace part of array to another array, get error ValueError: assignment destination is read-only
I have two arrays with pixels, I need to replace the first part of array 'pixels_new', to array 'pixels_old'
pixels_old = numpy.asarray(im) #picture 100X100
pixels_new = numpy.asarray(img) #picture 100X200
for k in range(0,101):
for i in range(len(pixels_old[k])):
print(pixels_new[i])
print(pixels_old[i])
pixels_new[i] = pixels_old[i]
It gives me an error:
File "/Users/apple/Desktop/projects/BariySatarov/exercise22.py", line 48, in make_new_im
pixels_new[i] = pixels_old[i]
ValueError: assignment destination is read-only
Please help me with it
Solution 1:[1]
I did a simple test as below.
import numpy as np
data = np.asarray([1, 2, 3])
data[0] = 2
data
>>> array([2, 2, 3])
This shows np.asarray
does not return the immutable variable, which is read-only. The error is ValueError: assignment destination is read-only
. So, I think your im
and img
variables are immutable. You haven't included the source code for your im
and img
, so I couldn't tell much about this. However, I have one suggestion is that you should clone or convert your im
and img
into nd.array before proccessing.
Solution 2:[2]
When we see this message :???ValueError: assignment destination is read-only
We need to take two steps to solve it:
First:
print(pixels_new.flags)
output:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : False. ------> # this option must be True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
then:
pixels_new.flags.writeable = True
The problem will be solved, but if the following message is given, do the following:
ValueError: cannot set WRITEABLE flag to True of this array
Make a copy of it so you can apply the changes to it:
pixel_n = pixels_new.copy()
pixels_n[i] = pixels_old[i]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hung Du |
Solution 2 | Salio |