0

I need to perform some operations on a 2D array of values read from an image, and then create an image with a resulting 2D array. I'm using python lists to represent the 2D array.

Something very odd is happening; the values in the 2D array (list of lists) appear to become "0" at some point between the two print calls I have labeled. That is, they seem to be read correctly from the image... but then somehow get set to zero.

Code:

image = Image.open("test.png").convert("L")

data = [ [255] * image.size[1] ] * image.size[0]
pix = image.load()
for x in range(0, image.size[0]):
    for y in range(0, image.size[1]):
        data[x][y] = pix[x, y]
        #data[x][y] = 77
        print "1. data[x][y] = " + str(data[x][y]) + " .vs. " + str(pix[x, y]) # Prints correct values

for x in range(0, image.size[0]):
    for y in range(0, image.size[1]):
        print "2. data[x][y] = " + str(data[x][y]) + " .vs. " + str(pix[x, y]) # Always prints "0 .vs. [correct value]"

However, if I comment out the line

data[x][y] = pix[x, y]

And uncomment:

data[x][y] = 77

Then the two print statements show that all elements in data are 77

What is going on? I'm not an expert on python, but I can't think of any sensible reason why list values would change like that.

I have tried the following line, in case the pixel accessor is doing something wierd:

data[x][y] = 0 + int(pix[x, y])

But still get the same result. I've also tried using RGB images instead of greyscale.

I should make it clear that I am definitely not doing anything with data between those two print calls. The code above is exactly what I have reduced my original program to (after discovering that all my "results" image files were black).

4

2 に答える 2

3

問題は次の行にあります。

data = [ [255] * image.size[1] ] * image.size[0]

image.size[1]これにより、値で埋められた長さのリストが作成されます255。次に、同じリストimage.size[0]への参照を作成し、それらすべての参照を別のリストにパックします。したがって、 を変更すると、 、、も同じ listへの参照であるため、andなども変更されます。a[1][1]a[0][1]a[2][1]a[0]a[1]a[2]...

簡単な例を次に示します。

a = [[255]*10]*10
a[1][1] = 77
print (a)

最も簡単な回避策は次のとおりです。

a = [[255]*10 for _ in range(10)]

これは、同じリストへの参照のリストではなく、10 個の新しいリストを作成するためです。

于 2012-10-09T11:22:44.230 に答える
1

すべての行に変更datadata = []て追加することをお勧めします。

data = []
pix = image.load()
for y in xrange(image.size[1]):
    data.append([pix[x, y] for x in xrange(image.size[0])])
于 2012-10-09T11:25:46.850 に答える