ValueError: assignment destination is read-only [Solved]
Last updated: Apr 11, 2024 Reading time · 2 min
# ValueError: assignment destination is read-only [Solved]
The NumPy "ValueError: assignment destination is read-only" occurs when you try to assign a value to a read-only array.
To solve the error, create a copy of the read-only array and modify the copy.
You can use the flags attribute to check if the array is WRITABLE .
Running the code sample produces the following output:
In your case, WRITEABLE will likely be set to False .
In older NumPy versions, you used to be able to set the flag to true by calling the setflags() method.
However, setting the WRITEABLE flag to True ( 1 ) will likely fail if the OWNDATA flag is set to False .
You will likely get the following error:
- "ValueError: cannot set WRITEABLE flag to True of this array"
To solve the error, create a copy of the array when converting it from a Pillow Image to a NumPy array.
Passing the Pillow Image to the numpy.array() method creates a copy of the array.
You can also explicitly call the copy() method.
You can also call the copy() method on the Pillow Image and modify the copy.
The image copy isn't read-only and allows assignment.
You can change the img_copy variable without getting the "assignment destination is read-only" error.
You can also use the numpy.copy() method.
The numpy.copy() method returns an array copy of the given object.
The only argument we passed to the method is the image.
You can safely modify the img_copy variable without running into issues.
You most likely don't want to make changes to the original image.
Creating a copy and modifying the copy should be your preferred approach.
If you got the error when using the np.asarray() method, try changing it to np.array() .
Change the following:
To the following:
As long as the WRITEABLE flag is set to True , you will be able to modify the array.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- TypeError: Object of type ndarray is not JSON serializable
- ValueError: numpy.ndarray size changed, may indicate binary incompatibility
- NumPy RuntimeWarning: divide by zero encountered in log10
- ValueError: x and y must have same first dimension, but have shapes
Borislav Hadzhiev
Web Developer
Copyright © 2024 Borislav Hadzhiev
问 正在尝试将部分数组替换为另一个数组,出现错误ValueError: assignment destination is read-only EN
我有两个带有像素的数组,我需要将数组' pixels _new‘的第一部分替换为数组'pixels_old’。
Stack Overflow用户
发布于 2020-12-02 19:51:20
我做了一个简单的测试,如下所示。
这表明 np.asarray 不返回不可变变量,该变量是只读的。错误是 ValueError: assignment destination is read-only 。所以,我认为你的 im 和 img 变量是不可变的。您还没有包含您的 im 和 img 的源代码,因此我不能详细说明这一点。然而,我有一个建议,那就是在处理之前,你应该克隆你的 im 和 img ,或者将它们转换成nd.array。
https://stackoverflow.com/questions/65107411
Copyright © 2013 - 2024 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号: 粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
IMAGES