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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With