8

I'm currently working on a Python program that involves using NumPy for image processing. However, I've encountered an issue when trying to create a deep copy of a NumPy array instead of just copying the reference.

Here's a snippet of my code, where I read in a PNG image and assign it to imageOriginal_3d:

width, height, pngData, metaData = png.Reader(file).asDirect()
planeCount = metaData['planes']
print('Image Size: ' + 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 // TODO: CREATE DEEP COPY

My intention is to edit imageEdited_3d without affecting the values in imageOriginal_3d. However, when I modify imageEdited_3d, the changes currently also appear in imageOriginal_3d.

0

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a notable difference in time consumption when constructing a deep copy versus shallow copy?
@wedran There is indeed. Deepcopy is much more time consuming! Try this gist

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.