Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

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

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.

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.

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.

So, I loop into the 2d array and I check the cell value and try to set it to 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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

img.setflags(write=1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...