Michael Boles
Michael Boles

Reputation: 369

Python for loop: executing second line overwrites object created in first line

I'm new to Python and wish to use a for loop to analyze vertical slices of an image. My for loop works when each of the individual lines is executed independently. However, when executed together, the object created in the first line takes on the values of the object created in the second line.

# create image of random noise 
im = np.random.randint(0,255,(100,200)) 

# create empty y and dy objects with same size as original image
empty = np.zeros([im.shape[0],im.shape[1]])
y = empty
dy = empty

# get pixel intensities in vertical strips, and then take first derivative 
for i in xrange(im.shape[1]):
    y[:,i] = im[:,i].astype(np.int32) 
    dy[:,i] = np.insert(diff(y[:,i]),0,0) 

I expected to get an object y that is identical to my image im, and an object dy which has the same dimensions as im and y but contains values representing the first derivative of pixel intensities along the vertical direction of the image.

Instead, I see that dy has been correctly calculated, but y has been overwritten with values identical to dy. Why is the object y being overwritten?

To clarify: my original image is type "uint8", which can't be differentiated. I have to convert to "int32" to compute the derivative. In the case of np.random.randint() the example image is already in int32. So the creation of object y is unnecessary in the provided example, but I need it to take the derivative of slices of my image.

Upvotes: 0

Views: 85

Answers (1)

jwalton
jwalton

Reputation: 5686

You're having a copy problem. The first time I saw this it confused me too! If you take a look at empty you'll see that it also contains the same values as y and dy.

To fix this you need to change your code to:

empty = np.zeros([im.shape[0],im.shape[1]])
y = empty.copy()
dy = empty.copy()

When you define empty an object is created in memory, and empty points to this object.

When you set y = empty and dy = empty, a new array isn't created in memory; y and dy are simply just pointers to the same array! So now you have that y, dy and empty all point to the same object.

So, modifying any of y, dy or empty will cause all of them to change.

Upvotes: 2

Related Questions