创建一个副本而不是NumPy数组的引用
我试图用NumPy编写Python程序,但是遇到了一个问题:
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
这是我的代码,用于读取PNG图像.现在,我要编辑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
但是imareOriginal_3d
变量的值与imageEdited_3d
一个的值相同...
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? :/
您需要创建对象的副本.您可以使用 numpy.copy()
来完成此操作具有numpy
对象.因此,您的初始化应类似于:
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()
还有 copy
模块,用于创建 deep复制,或者浅复制.这与对象类型无关.例如,使用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)
说明:
浅表副本会构造一个新的复合对象,然后(到 在可能的范围内)将引用插入其中的对象 原始的.
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.