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).