python - 创建副本而不是 NumPy 数组的引用

标签 python numpy copy

我正在尝试使用 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/

相关文章:

MySQL 使用 INSERT 复制表数据并进行重复键更新... "field id is ambiguous?"

python - 如何从 txt 文件中读取路径并将这些文件复制到新目录?

java - 如何复制hashset和hashmap,Java是否使用指针?

python - 如何从Python中的特定点开始Itertools循环?

python - 如何绘制不同长度的数组

python - 提取比 numpy 中的花式索引慢?

python - 字典与 NumPy 数组性能 Python

python - 现有的开源 Python WxWidgets 设计器有哪些?

python - 应用程序退出后未设置剪贴板?

python - 如何访问Python列表中字典中的项目?