创建一个副本而不是NumPy数组的引用 [英] Create a copy and not a reference of a NumPy array

查看:104
本文介绍了创建一个副本而不是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.

这篇关于创建一个副本而不是NumPy数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆