我正在尝试使用 NumPy 制作 Python 程序,但遇到了一个问题:
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
, 像这样:imageEdited_3d[x,y,0] = 255
但随后
imareOriginal_3d
变量具有与 imageEdited_3d
相同的值一...有谁知道,我该如何解决这个问题?所以它不仅创建了一个引用,而且创建了一个真实的副本? :/
最佳答案
您需要创建对象的副本。你可以使用 numpy.copy()
因为你有 numpy
目的。因此,您的初始化应该是这样的:
imageEdited_3d = imageOriginal_3d.copy()
还有
copy
用于创建深拷贝或浅拷贝的模块。这与对象类型无关。例如,您的代码使用 copy
应该是: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.
关于python - 创建副本而不是 NumPy 数组的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196995/