tags:

views:

41

answers:

2

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. 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?

A: 

You could easily make a function that would emulate 2d data:

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:

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].

JoshD
It just gives me "Traceback (most recent call last): File "tablemaker.py", line 14, in <module> datatmp[m] = data[n*width+m]IndexError: list assignment index out of range" as the error
giodamelio
@giodamelio, fixed. use append
JoshD
thanks for your help
giodamelio
+1  A: 

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

x, y = n % width, n / width

or (does the same but more efficient)

y, x = divmod(n, width)
kriss
Thank you. It worked
giodamelio