Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print pixels of an image as a matrix?

I would like to print the pixels of an image as a matrix.

Here is the code I am using:

from PIL import Image

im = Image.open("8Black.png")
pixels = list(im.getdata())

print(pixels)

I created the image "8Black.png" using photoshop and painted it all black. The python version that I use is 3.5.0. However, when I run the above code I get:

[0,0,0,0,0,0,0,0,0,0,0,0,...,0]

I want to get this instead:

[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[...],[...]]

I tried changing this:

pixels = list(im.getdata())

to this:

pixels = np.matrix(im.getdata())

but still did not get the result I wanted.

How can I get the pixel data as a matrix? Did I miss something?

like image 878
Ling Avatar asked Sep 26 '22 22:09

Ling


1 Answers

You're explicitely asking for the original 2D image to be "flattened" into a 1D sequence by doing getdata().

You could use reshape to bring it back to it's original form

matrix = np.array(im.getdata()).reshape(im.size)
like image 116
Marcus Müller Avatar answered Sep 28 '22 23:09

Marcus Müller