0

When I import an image as a NumPy array using the following code:

import numpy as np
from PIL import Image
imgage = Image.open('input.jpg', 'r')
width, height = imgage.size
pixel_values = np.array(imgage.getdata(), dtype=np.uint8).reshape((width, height, 3))

And, then I export it using the following code:

output = Image.fromarray(pixel_values, 'RGB')
output = img.save('output.png')

The resulting image is completely different from the input.

Can you please what the problem is? How can I fix it?

hoomant
  • 455
  • 2
  • 12
  • I used the reshape function according to [How to read the RGB value of a given pixel in Python?](https://stackoverflow.com/questions/138250/how-to-read-the-rgb-value-of-a-given-pixel-in-python), however, it seems that the correct usage is `reshape((height, width, 3)`. – hoomant Jul 27 '20 at 20:07

1 Answers1

0

I'm not sure what you are trying to do, but when you reshape your image, you need to invert width and height.

pixel_values = np.array(imgage.getdata(), dtype=np.uint8).reshape((height, width, 3))

Also, on a different note, if you want to convert a PIL Image to a numpy array you just have to do

pixel_values = np.array(imgage)
Luke B
  • 1,143
  • 1
  • 11
  • 22