Python np 数组是不可变的 - “分配目标是只读的”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39554660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:27:29  来源:igfitidea点击:

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

pythonarraysnumpy

提问by Ramesh Ramasubramanian

FD** - I am a Python newb as well as a stack overflow newb as you can tell. I have edited the question based on comments.

FD** - 正如你所知,我是一个 Python 新手,也是一个堆栈溢出新手。我已经根据评论编辑了这个问题。

My goal is to read a set of PNG files, create Image(s) with Image.open('filename') and convert them to simple 2D arrays with only 1s and 0s. The PNG is of the format RGBA with mostly only 255 and 0 as values. Quite often in the images, the edges are grey scale values, which I would like to avoid in the 2D array.

我的目标是读取一组 PNG 文件,使用 Image.open('filename') 创建 Image(s) 并将它们转换为只有 1s 和 0s 的简单二维数组。PNG 的格式为 RGBA,主要只有 255 和 0 作为值。在图像中,边缘经常是灰度值,我想在 2D 数组中避免这种情况。

I created the 2D array from image using np.asarray(Image) getting only the 'Red' channel. In each of the 2d image array, I would like to set the cell value = 1 if the current value is non zero.

我使用 np.asarray(Image) 从图像创建了二维数组,只获取“红色”通道。在每个二维图像数组中,如果当前值非零,我想设置单元格值 = 1。

So, I loop into the 2d array and I check the cell value and try to set it to 1.

因此,我循环到 2d 数组并检查单元格值并尝试将其设置为 1。

It gives me an error indicating that the array is read-only. I read through several stack overflow threads discussing that np arrays are immutable and it is a still bit unclear. I use PIL and numpy

它给了我一个错误,表明数组是只读的。我通读了几个堆栈溢出线程,讨论 np 数组是不可变的,但仍然有点不清楚。我使用 PIL 和 numpy

Thanks @user2314737. I will attempt to set that flag. @Eric, thanks for your comments as well.

谢谢@user2314737。我将尝试设置该标志。@Eric,也感谢您的评论。

from PIL import Image
import numpy as np

The relevant code:

相关代码:

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

for img in prArray:
    for x in range(184):
        for y in range(184):
            if img[x][y] != 0:
                img[x][y] = 1

The error "assignment destination is read-only" is in the last line.

错误“分配目标为只读”在最后一行。

Thank you everyone for help.

谢谢大家的帮助。

回答by user2314737

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

如果WRITEABLE是假的,改变它

img.setflags(write=1)

回答by AleksMat

Since numpyversion 1.16.0the following doesn't work anymore:

由于以下numpy版本1.16.0不再起作用:

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

The problem is that now OWNDATAis set to Falseand you can't set WRITEABLEflag to True. Therefore you should simply do the following:

问题是 nowOWNDATA设置为False并且您不能将WRITEABLE标志设置为True。因此,您只需执行以下操作:

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

This will make a copy of array when casting it from Pillowobject to numpyarray. However I tested time performance in numpy1.16.0and haven't found any noticable difference between both methods.

这将在将数组从Pillow对象转换为数组时制作数组的副本numpy。但是,我测试了时间性能,numpy1.16.0并没有发现两种方法之间有任何显着差异。

回答by Avneesh Upadhayay

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().

在这种情况下,我认为您正在尝试编辑其他用户提供给您的图像,而他/她将其设为不可编辑,这就是您收到此错误的原因。对于您的情况,您可以尝试制作给定文件的副本并使用.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.

更重要的是,我认为我们大多数人都不想对原始图像进行更改,这就是为什么我总是使用.copy()并建议您这样做。

回答by eslam mofreh

You haven't the access to the source of the image instead what you're should do is to copy it into another array and now you can do assignment.

您无权访问图像的来源,而您应该做的是将其复制到另一个数组中,现在您可以进行分配。