2010-10-10 75 views
3

我有一段代码将为图像中的每个像素返回一个平坦序列。在python中将平面序列转换为2d序列

import Image 
im = Image.open("test.png") 
print("Picture size is ", width, height) 
data = list(im.getdata()) 
for n in range(width*height): 
    if data[n] == (0, 0, 0): 
     print(data[n], n) 

此代码返回这样的事情

((0, 0, 0), 1250) 
((0, 0, 0), 1251) 
((0, 0, 0), 1252) 
((0, 0, 0), 1253) 
((0, 0, 0), 1254) 
((0, 0, 0), 1255) 
((0, 0, 0), 1256) 
((0, 0, 0), 1257) 

前三个值是像素的RGB,最后一个是序列索引。 了解图像的宽度和高度以及像素索引的顺序如何将该序列转换回2d序列?

回答

1

简单的数学:你有n个,宽度,高度和希望的x,y

x, y = n % width, n/width 

或(不相同,但更有效)

y, x = divmod(n, width) 
+0

谢谢。有效 – giodamelio 2010-10-10 22:16:09

0

你可以很容易地将仿真2D数据的函数:

def data2d(x,y,width): 
    return data[y*width+x] 

但是,如果你想将数据放在一个2dish数据结构,你可以做这样的事情:

data2d = [] 
for n in range(height): 
    datatmp = [] 
    for m in rante(width): 
    datatmp.append(data[n*width+m]) 
    data2d[n] = datatmp 

您可能需要在最后一行中进行深层复制。这将使data2d成为一个列表列表,因此您可以像data[row][column]那样访问行中的像素。

+0

这给了我“回溯(最近调用最后一个): 文件“tablemaker.py”,第14行,在 datatmp [m] = data [n * width + m] IndexError:列表分配索引超出范围“作为错误 – giodamelio 2010-10-10 22:04:31

+0

@giodamelio,fixed。使用追加 – JoshD 2010-10-10 22:13:31

+0

感谢您的帮助 – giodamelio 2010-10-11 06:20:02