Zyx
Zyx

Reputation: 336

Python: corverting a greyscale BMP into a list of lists

My question is somewhat similar to this one, but I couldn't figure out how to make it work for me. I want to convert a grayscale bmp of arbitrary size into a list of lists with values between 0 and 255.
For example:
If input looks like this: grayscale bmp
The output should be:

pic =  [[255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
        [255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
        [255, 255, 127, 127, 127, 127, 127, 127, 255, 255],
        [255, 255, 127, 127, 127, 127, 127, 127, 255, 255],
        [255, 255, 127, 127, 0  , 0  , 127, 127, 255, 255],
        [255, 255, 127, 127, 0  , 0  , 127, 127, 255, 255],
        [255, 255, 127, 127, 127, 127, 127, 127, 255, 255],
        [255, 255, 127, 127, 127, 127, 127, 127, 255, 255],
        [255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
        [255, 255, 255, 255, 255, 255, 255, 255, 255, 255]]

I have almost no experience in image processing.

Upvotes: 0

Views: 137

Answers (1)

Nicolas Garnier
Nicolas Garnier

Reputation: 446

You should consider using PIL library :

In [1]: from PIL import Image
In [2]: img = Image.open('HrWCY.png')
In [3]: img.getdata().getpixel((0,0))
Out[3]: 0
In [4]: img.getdata().getpixel((4,4))
Out[4]: 255
In [5]: img.getdata().getpixel((5,7))
Out[5]: 164
In [6]: img.getdata().getpixel((12,12))
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-8456667c785c> in <module>()
----> 1 img.getdata().getpixel((12,12))
IndexError: image index out of range

Check the documentation, you should fine better methods for the purpose.

Upvotes: 1

Related Questions