Convert flat sequence to 2d sequence in python

I have a piece of code that will return a flat sequence for each pixel in the 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)

These codes return 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 pixels, and the last is the index in the sequence. Knowing the width and height of the image and the pixel index in a sequence, how can I convert this sequence back to a 2d sequence?

+3
source share
2 answers

Simple math: you have n, width, height and want x, y

x, y = n % width, n / width

or (does the same, but more efficiently)

y, x = divmod(n, width)
+1
source

, 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

Source: https://habr.com/ru/post/1768898/


All Articles