简体   繁体   English

在python中将平坦序列转换为2d序列

[英]Converting flat sequence to 2d sequence in python

I have a piece of code that will return a flat sequence for every pixel in a image. 我有一段代码将返回图像中每个像素的平面序列。

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)

This codes returns something like this 此代码返回类似这样的内容

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

The first three values are the RGB of the pixel and the last one is the index in the sequence. 前三个值是像素的RGB,最后一个是序列中的索引。 Knowing the width and height of the image and the pixels index in sequence how can i convert that sequence back into a 2d sequence? 知道图像的宽度和高度以及像素索引如何将该序列转换回2d序列?

Simple math: you have n, width, height and want x, y 简单的数学:你有n,宽度,高度,想要x,y

x, y = n % width, n / width

or (does the same but more efficient) 或(做同样但效率更高)

y, x = divmod(n, width)

You could easily make a function that would emulate 2d data: 您可以轻松地创建一个可以模拟2d数据的函数:

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

But if you want to put the data in a 2dish data structure, you could do something like this: 但是如果你想将数据放在2dish数据结构中,你可以这样做:

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

You may need to do a deep copy in that last line. 您可能需要在最后一行进行深层复制。 This will make data2d a list of lists so you can access the pixel in row, column as data[row][column] . 这将使data2d成为列表列表,因此您可以访问行,列中的像素作为data[row][column]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM