Reputation: 21
I have three stages: 1. convert an Image into numpy array 2. save that array in a text file 3. convert the array into Image by reading that text file
I tried below code, which is converting image into an array and again reading the same array from the text file
from PIL import Image
import numpy
im = Image.open("a.jpg") # img size (480,910,3)
np_im = numpy.array(im)
with open('test.txt', 'w') as outfile:
for slice_2d in np_im:
numpy.savetxt(outfile, slice_2d)
new_data = numpy.loadtxt('test.txt')
new_data=new_data.reshape((480,910,3))
img = Image.fromarray(new_data,'RGB')
img.save('my.bmp')
img.show()
if i compare the array (before saving and after loading from file and reshaping) array looks exactly the same(except dot). ex.
[[[ 48 58 24]
[ 48 58 24]
[ 47 57 23]
...
and
[[[ 48. 58. 24.]
[ 48. 58. 24.]
[ 47. 57. 23.]
...
but the image I'm getting is completely distorted. why so?
Upvotes: 0
Views: 2853
Reputation: 1408
You might be interested in numpy.savetxt
. It sounds a lot like you're trying to build this.
There's also a complementary numpy.loadtxt
.
If you feed savetxt a filename ending in .gz
, it'll even compress the data. loadtxt understands it just the same.
This will work for arbitrary numpy arrays.
Upvotes: 1
Reputation: 21
after some exercise, I got my answer
img = Image.fromarray(new_data.astype(numpy.uint8),'RGB')
Upvotes: 1