4

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)))
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
bob_vie
  • 53
  • 1
  • 5
  • what extension did you use to save that `some_path` image? Your save() call doesn't seem to specify one – DarkCygnus Jan 08 '18 at 16:16
  • That code doesn't make sense. `im` is a PIL Image object, but `Image.fromarray` expects its arg to be an array, and it creates an Image from that array. I assume you want a Numpy array. Is that correct? See https://stackoverflow.com/a/7769424/4014959 – PM 2Ring Jan 08 '18 at 16:18
  • The problem with "playing around with PIL" is you don't have a definitive problem statement, so you're doing things the API was never designed for and getting confused. Find an actual problem you need to solve with PIL - such as loading an image and saving it with a new extension - and then try to get that working. As it stands, this isn't really a question. –  Jan 08 '18 at 16:20

1 Answers1

3

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.

Glenn D.J.
  • 1,874
  • 1
  • 8
  • 19