Reputation: 3
Working with Spyder, so python 2.7
I'm fairly new to python and learning about image processing for some work I will need to do down the line, but I'm having some trouble working with the arrays python is spitting out at me. I'm sure that all of my troubles are due to lapses in basic understanding, so I'm hoping that someone can straighten me out.
Lots of this is just practice for me, so I go through a lot of basic commands to get a better grasp on things. The problem comes when I attempt to convert the image to an array. The image is 814x611, but instead of arranging the data like that, np.array decides to give me an array with 497354 rows and 3 columns (RGB values I assume). I wasn't especially successful at turning that back into an image.
Any attempt I've tried to get the correct output or alter the array it gives back have been unsuccessful or sent back errors. At this point I'm pretty burned out. I hope someone can help me think about this the right way.
import numpy as np
from PIL import Image as im
import matplotlib.pyplot as plt
imoprt os
os.chdir('c:\\users\\jan\\desktop\\pythonstuff')
laura = im.open("laura.jpg")
laura.save("laura.jpg","png")
dimensions = laura.size
print dimensions
plt.imshow(laura)
print type(laura)
#pd for pixel data
#tried this with and without the tuple dtype. no change
pd = np.array(laura.getdata(),dtype=tuple)
print pd
that gives me
(814, 611)
<type 'instance'>
[[93 100 93]
[94 101 94]
[97 103 99]
...,
[126 63 82]
[126 63 82]
[128 63 83]]
and then it properly displays my image below that. Why would it give me the data in this strange format? Is there an easy way to convert it to a format that I can conveniently turn BACK into an image?
Upvotes: 0
Views: 52
Reputation: 2088
The format you are using is an RGB 8-bit file.
The underlying structure of your image is an (814, 611, 3)
numpy array, where 3 is a color intensity, one for each channel and (814, 611)
are dimensions of your image.
For the simplicity PIL flattens out the first two dimensions (this is anyway how numpy arrays operate on a low level) and then runs indexing operations to render the image once you call imshow.
Upvotes: 0
Reputation: 4996
pd = np.array(laura.getdata()).reshape((laura.size[0], laura.size[1]),3)
That should do the trick. The 3 is because its an RGB image.
Upvotes: 1