I've run into a frustrating problem while trying to build a grid of colors using PIL and python. I can loop over my grid and extract colors just fine but when I go to read them back one or more of them has always disappeared for some reason. This seems like an incredibly basic error but a very frustrating one.
Here is the code in question. cx and cy just point to the center of each sample point in the grid, the color is the most used color in the sample area
image = ImageGrab.grab(box)
matrix = [[None] * ROWS] * COLS
c1 = set()
for row in range(ROWS):
for col in range(COLS):
cx = (col * CELLW) + int(CELLW / 2)
cy = (row * CELLH) + int(CELLH / 2)
sample_box = (cx - SAMPLE_SIZE, cy - SAMPLE_SIZE, cx + SAMPLE_SIZE, cy + SAMPLE_SIZE)
sample = image.crop(sample_box)
color = sorted(sample.getcolors())[-1][1]
matrix[col][row] = color
c1.add(color)
print(c1)
c2 = set()
for row in range(ROWS):
for col in range(COLS):
c2.add(matrix[col][row])
print(c2)
As you can see, what (I think) should happen is that c1 holds all unique colors and prints them. then c2 loops over the same thing and prints the unique colors too. I can't see why they should be different but they are.
The output is something like as follows:
{(240, 240, 240), (255, 255, 255), (252, 252, 252)}
{(240, 240, 240), (255, 255, 255)}
Any help with this frustrating problem would be greatly appreciated
I think that the issue here is that your matrix holds multiple references to the same list. Consider:
>>> matrix = [[None]*3]*4
>>> matrix
[[None, None, None], [None, None, None], [None, None, None], [None, None, None]]
>>> matrix[1][1]=0
>>> matrix
[[None, 0, None], [None, 0, None], [None, 0, None], [None, 0, None]]
You can get around that by initializing your "matrix" with:
matrix = [[None]*ROWS for _ in range(COLUMNS)]
You can use xrange in python 2.x if you prefer ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With