0

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?

sanghmitra
  • 21
  • 2
  • 9
  • Possible duplicate of [Image.fromarray just produces black image](https://stackoverflow.com/questions/47290668/image-fromarray-just-produces-black-image) – D Malan Oct 31 '19 at 08:23

2 Answers2

1

after some exercise, I got my answer

img = Image.fromarray(new_data.astype(numpy.uint8),'RGB')
sanghmitra
  • 21
  • 2
  • 9
1

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.

Gloweye
  • 1,294
  • 10
  • 20