可变的变化,但没有更新

时间:2015-09-22 20:47:52

标签: python

我试图通过切换顶部和底部的列来翻转使用Python中的opencv拍摄的图像(RGB值矩阵):

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

出于某种原因,temp执行image[col-i-1]image[i] = image[dol-i-1]更改为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)

我打印了每列的第一个值,看看有什么变化,它显示了这个:

temp

为什么PostMethod method = new PostMethod(url); method.addRequestHeader("Content-Type", "application/json"); method.addRequestHeader("Authorization", "Bearer "+accessToken); method.setRequestEntity(new StringRequestEntity(requestAsString, "application/json", "UTF-8")); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setSoTimeout(timeout); int rCode = client.executeMethod(method); 会改变?

1 个答案:

答案 0 :(得分:1)

临时变量似乎发生变化的原因是因为在Python中,当你指定

时,你没有制作副本
temp = image[i]

相反,您将新名称“绑定”到同一个对象。这意味着temp只是指向image[i]也指向的相同底层数据结构。当您下次更新image[i]时,该更改也会反映在temp变量中。

显示相同行为的一个简单示例是:

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

对于那些不熟悉Python的人来说,这是一个常见的陷阱,这可以从数十个related SO questions中得到证明。