2

I'm using PyPNG package to read a simple png file.
The returned pixels data is an itertools.imap object.
How do I read this data.

import png, array  
reader = png.Reader(filename='image.png')  
w, h, pixels, metadata = reader.read()  

(877, 615, <itertools.imap object at 0x2a956a5b50>, {'bitdepth': 8, 'interlace': 0, 'planes': 3, 'greyscale': False, 'alpha': False, 'gamma': 0.45455, 'size': (877, 615)})

pixels is this itertools.imap object which I assume containing the pixel info.

Thanks

Regards

RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
elgnoh
  • 493
  • 5
  • 15

2 Answers2

4

itertools.imap returns an iterable. You should be able to iterate over it as you would iterate over any other list.

Of course, one key difference is that because it's an iterator, you'll only be able to iterate over it once. You'll also not be able to index into it

EDIT (Upon OP's request):

How to iterate over a list

Suppose you have a list called L, and L looks like this:

L = ['a', 'b', 'c', 'd']

then, the elements at of L and their respective indices are:

+-------+---------+
| index | element |
+-------+---------+
|   0   |   'a'   |
+-------+---------+
|   1   |   'b'   |
+-------+---------+
|   2   |   'c'   |
+-------+---------+
|   3   |   'd'   |
+-------+---------+

Notice, that because python has zero-based indices, there is no index 4, even though there are four items in L.

Now, if you want the item at index 3 in L, you'd do L[3]. If you want the item at index 2 in L, you'd do L[s], and so on.

To iterate over a L (let's say you want to print out the values):

for elem in L:
    print elem

Another way:

for i in range(len(L)): # lookup range() and len()
    print L[i]

Hope this helps

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • I'm new to Python, could you provide an example how to iterate over this list? Thanks. – elgnoh Nov 21 '12 at 05:15
  • Thanks. Gotten so used to customized iterator, and forgot to associate simple for loop for such purpose. Also thanks for explaining the concept of iterable vs. list. – elgnoh Nov 21 '12 at 06:12
1

The simplest (not necessarily efficient for large images) is to use the builtin list function to convert from an iterator to a list:

pixelsAsList = list(pixels)
print pixelsAsList[0] # the first row
print pixelsAsList[0][0] # The Red channel from the first pixel on the first row.
David Jones
  • 4,766
  • 3
  • 32
  • 45