Skip to content
Advertisement

Numpy array not copy

I am working with numpy and images. I have a big image which i want to process bit by bit. So I want to create a reference to the original image, do something with it and move on. But when I change something in the frame the change does not transfer to the original, which is the opposite of everything I read online

for example here : https://stackoverflow.com/a/53939444/11333604 if you don’t use copy if you change one array the other changes. That does NOT HAPPEN to me

here is some pseudo code that demonstrates my problem

import numpy as np
#create a "big" imgae total black
matrix = np.full((5,5),255,np.uint8)
# the frame that i want to process 
h = 3
w = 3
sub  = matrix[:h, :w]
#mask to make everything 0 
mask = np.zeros((h,w),np.uint8)
sub = sub & mask
#also change something radom so i know the problem is not the & or the mask
sub[0][0] = 12


#sub is changes
print(sub)
#matrix is not
print(matrix)

output

[[12  0  0]
 [ 0  0  0]
 [ 0  0  0]]
[[255 255 255 255 255]
 [255 255 255 255 255]
 [255 255 255 255 255]
 [255 255 255 255 255]
 [255 255 255 255 255]]

I suspect it has something to do with my arrays being 2d but i cant think of how

Advertisement

Answer

That’s because in this line

sub = sub & mask

you’re making sub to “look” at some new array formed with sub & mask and it loses its connection to matrix. If you do this in-place instead

sub &= mask

then matrix will be affected too:

>>> matrix

array([[ 12,   0,   0, 255, 255],
       [  0,   0,   0, 255, 255],
       [  0,   0,   0, 255, 255],
       [255, 255, 255, 255, 255],
       [255, 255, 255, 255, 255]], dtype=uint8)
Advertisement