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
511 views
in Technique[技术] by (71.8m points)

python - Create a copy and not a reference of a NumPy array

I'm trying to make a Python program with NumPy, but I ran into a problem:

width, height, pngData, metaData = png.Reader(file).asDirect()
planeCount = metaData['planes']
print('Bildgroesse: ' + str(width) + 'x' + str(height) + ' Pixel')
image_2d = np.vstack(list(map(np.uint8, pngData)))
imageOriginal_3d = np.reshape(image_2d, (width, height, planeCount)) 
imageEdited_3d = imageOriginal_3d

This is my code, to read in a PNG image. Now I want to edit imageEdited_3d but NOT imageOriginal_3d, like this:

imageEdited_3d[x,y,0] = 255

But then the imareOriginal_3d variable has the same values as the imageEdited_3d one...

Does anyone know, how I can fix this? So it doesn't only creates a reference, but it creates a real copy? :/

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to create the copy of the object. You may do it using numpy.copy() since you are having numpy object. Hence, your initialisation should be like:

imageEdited_3d = imageOriginal_3d.copy()

Also there is copy module for creating the deep copy OR, shallow copy. This works independent of object type. For example, your code using copy should be as:

from copy import copy, deepcopy

# Creates shallow copy of object
imageEdited_3d = copy(imageOriginal_3d)

# Creates deep copy of object
imageEdited_3d = deepcopy(imageOriginal_3d)

Description:

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.


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

...