我只是要说明为什么您的代码不起作用。 @peter de Rivaz 的回答应该是你在 numpy 中应该做的事情
当您allPixels.append(pixel) 时,您附加了pixel 的发生率。如果稍后更改pixel 的值,则pixel 的所有发生率都会更改。看这个例子:
>>> def RGBtoLMS(rgbValues, rgbLength): #Passing in a list of rgbValues and an int representing the length of that list
pixel = numpy.empty((3, 1), int)
allPixels = list()
x = 0
for h in xrange(rgbLength/3):
for i in xrange(len(pixel)):
for j in xrange(len(pixel[i])):
if x < rgbLength: #For some reason, x reaches rgbLength...
pixel[i][j] = rgbValues[x]
x+=1
allPixels.append(pixel)
for pixel in allPixels:
print pixel, id(pixel)
>>> RGBtoLMS([1,2,3,101,102,103,4,5,6,104,105,106],12)
[[104]
[105]
[106]] 38693552
[[104]
[105]
[106]] 38693552
[[104]
[105]
[106]] 38693552
[[104]
[105]
[106]] 38693552
所以你可以做一些事情来获得预期的行为:
>>> def RGBtoLMS(rgbValues, rgbLength): #Passing in a list of rgbValues and an int representing the length of that list
pixel = numpy.empty((3, 1), int)
allPixels = list()
x = 0
for h in xrange(rgbLength/3):
for i in xrange(len(pixel)):
for j in xrange(len(pixel[i])):
if x < rgbLength: #For some reason, x reaches rgbLength...
pixel[i][j] = rgbValues[x]
x+=1
allPixels.append(pixel*1)
for pixel in allPixels:
print pixel, id(pixel)
>>> RGBtoLMS([1,2,3,101,102,103,4,5,6,104,105,106],12)
[[1]
[2]
[3]] 38301608
[[101]
[102]
[103]] 37756712
[[4]
[5]
[6]] 37949360
[[104]
[105]
[106]] 38399424
或者将pixel的定义移到循环中。
>>> def RGBtoLMS(rgbValues, rgbLength): #Passing in a list of rgbValues and an int representing the length of that list
allPixels = list()
x = 0
for h in xrange(rgbLength):
if x < rgbLength: #For some reason, x reaches rgbLength...
pixel = numpy.empty((3, 1), int)
for i in xrange(len(pixel)):
for j in xrange(len(pixel[i])):
pixel[i][j] = rgbValues[x]
x+=1
allPixels.append(pixel)
else:
break
for pixel in allPixels:
print pixel, id(pixel)
>>> RGBtoLMS([1,2,3,101,102,103,4,5,6,104,105,106],12)
[[1]
[2]
[3]] 38301608
[[101]
[102]
[103]] 37756712
[[4]
[5]
[6]] 37949360
[[104]
[105]
[106]] 38399424