【问题标题】:Converting flat sequence to 2d sequence in python在python中将平面序列转换为二维序列
【发布时间】:2010-10-11 06:13:18
【问题描述】:

我有一段代码将为图像中的每个像素返回一个平面序列。

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,最后一个是序列中的索引。 知道图像的宽度和高度以及序列中的像素索引如何将该序列转换回二维序列?

【问题讨论】:

    标签: python image python-imaging-library


    【解决方案1】:

    简单的数学运算:你有 n、width、height 并想要 x、y

    x, y = n % width, n / width
    

    或(相同但更有效)

    y, x = divmod(n, width)
    

    【讨论】:

      【解决方案2】:

      您可以轻松地创建一个模拟二维数据的函数:

      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] 的形式访问行、列中的像素。

      【讨论】:

      • 它只是给了我“回溯(最近一次调用最后一次):文件“tablemaker.py”,第 14 行,在 datatmp[m] = data[n*width+m] IndexError:列出分配索引超出范围”作为错误
      • @giodamelio,已修复。使用追加
      猜你喜欢
      • 2011-09-30
      • 2023-04-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-29
      • 2012-04-24
      • 2022-11-20
      • 1970-01-01
      相关资源
      最近更新 更多