[英]Python 2D array losing data somewhere
在尝试使用PIL和python构建颜色网格时遇到了令人沮丧的问题。 我可以循环我的网格并提取颜色就好了但是当我去阅读它们时,由于某种原因,它们中的一个或多个总是消失。 这似乎是一个令人难以置信的基本错误,但非常令人沮丧。
这是有问题的代码。 cx和cy只指向网格中每个采样点的中心,颜色是样本区域中使用最多的颜色
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)
正如你所看到的,我认为应该发生的是c1拥有所有独特的颜色并打印出来。 然后c2循环在同一个东西上并打印出独特的颜色。 我不明白为什么他们应该是不同的,但他们是。
输出如下:
{(240, 240, 240), (255, 255, 255), (252, 252, 252)}
{(240, 240, 240), (255, 255, 255)}
任何有关这个令人沮丧的问题的帮助将不胜感激
我认为这里的问题是你的矩阵拥有对同一个列表的多个引用。 考虑:
>>> 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]]
您可以通过以下方式初始化“矩阵”来解决这个问题:
matrix = [[None]*ROWS for _ in range(COLUMNS)]
如果你愿意,可以在python 2.x中使用xrange
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.