Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a copy and not a reference of a NumPy array

Tags:

python

copy

numpy

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? :/

like image 529
Gykonik Avatar asked Oct 22 '16 20:10

Gykonik


People also ask

How do you copy a NumPy array?

Use numpy. copy() function to copy Python NumPy array (ndarray) to another array. This method takes the array you wanted to copy as an argument and returns an array copy of the given object. The copy owns the data and any changes made to the copy will not affect the original array.

Does indexing a NumPy array create a copy?

Producing a View of an Array As stated above, using basic indexing does not return a copy of the data being accessed, rather it produces a view of the underlying data. NumPy provides the function numpy.

Does NumPy slicing create a copy?

Whether a view or a copy is created is determined by whether the indexing can be represented as a slice. Exception: If one does "fancy indexing" then always a copy is created.

Is NP copy a deep copy?

copy() function creates a deep copy. It is a complete copy of the array and its data, and doesn't share with the original array.


1 Answers

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.

like image 147
Moinuddin Quadri Avatar answered Sep 28 '22 12:09

Moinuddin Quadri