0

I'm trying to flip an image (matrix with RGB values) taken with opencv in Python by switching the columns on the top and bottom:

cv2.imshow('Image',image)
temp = image[0]
row,col,number = image.shape
for i in range (0,col/2) :
        temp = image[i] 
        image[i] = image[col-i-1]
        image[col-i-1] = temp

For some reason, temp changes to image[col-i-1] after executing image[i] = image[dol-i-1].

I printed the first values of each column to see what changed and it showed this:

temp
[ 74 63 167]  (old) 
[ 85 69 177]  (new)
image[i]
[ 85 69 177]  (old)
[ 77 66 170]  (new)
temp
[ 77 66 170]  (old)
[ 77 66 170]  (new)
image[col-i-1]
[ 77 66 170]  (old)
[ 77 66 170]  (new)

So why does temp change?

Oliver W.
  • 13,169
  • 3
  • 37
  • 50

1 Answers1

1

The reason the temporary variable seems to change is because in Python, you're not making a deep copy when you assign

temp = image[i]

Instead, you're "binding" a new name to the same object. This means that temp simply points to the same underlying data structure that image[i] is also pointing to. When you next make an update to image[i], that change will also be reflected in the temp variable.

An easy example that shows the same behaviour is this one:

>>> a = [1,2,3]
>>> b = a
>>> a[2] = 0
>>> a  # as expected
[1, 2, 0]
>>> b  # python gotcha
[1, 2, 0]

It's a common pitfall for people who are new to Python, as evidenced from the dozens of related SO questions.

Community
  • 1
  • 1
Oliver W.
  • 13,169
  • 3
  • 37
  • 50