Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL image to array and back

EDIT: Sorry, the first version of the code was bullshit, I tried to remove useless information and made a mistake. Problem stays the same, but now it's the code I actually used

I think my problem is probably very basic but I cant find a solution. I basically just wanted to play around with PIL and convert an image to an array and backward, then save the image. It should look the same, right? In my case the new image is just gibberish, it seems to have some structure but it is not a picture of a plane like it should be:

def array_image_save(array, image_path ='plane_2.bmp'):
  image = Image.fromarray(array, 'RGB')
  image.save(image_path)
  print("Saved image: {}".format(image_path))

im = Image.open('plane.bmp').convert('L')
w,h = im.size
array_image_save(np.array(list(im.getdata())).reshape((w,h)))
like image 811
bob_vie Avatar asked Oct 24 '25 10:10

bob_vie


1 Answers

Not entirely sure what you are trying to achieve but if you just want to transform the image to a numpy array and back, the following works:

from PIL import Image
import numpy as np

def array_image_save(array, image_path ='plane_2.bmp'):
  image = Image.fromarray(array)
  image.save(image_path)
  print("Saved image: {}".format(image_path))

im = Image.open('plane.bmp')
array_image_save(np.array(im))

You can just pass a PIL image to np.array and it takes care of the proper shaping. The reason you get distorted data is because you convert the pil image to greyscale (.convert('L')) but then try to save it as RGB.

like image 154
Glenn D.J. Avatar answered Oct 27 '25 01:10

Glenn D.J.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!