Search code examples
pythonpypng

how to read itertools.imap object from PyPNG's reader


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


Solution

  • 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