2

I am trying to convert an array into a image (tif) for compression (it will be undone at the other end). However, I'm falling at the first hurdle...

I have the following:

pillow_image = Image.fromarray(image_data)

Which gives me this error:

  File "/Users/workspace/test-app/env/lib/python2.7/site-packages/PIL/Image.py",

line 2155, in fromarray arr = obj.array_interface AttributeError: 'tuple' object has no attribute 'array_interface'

What I'm I doing wrong here?

1 Answer 1

5

image_data is a tuple of 4 numpy arrays, each (probably) of shape (H, W). You need image_data to be a single array of shape (H, W, 4). Therefore, use np.dstack to combine the channels.

At least one of your arrays has dtype int32. But to use it as an 8-bit color channel, the arrays needs to be of dtype uint8 (so that the maximum value is 255). You can convert the array to dtype uint8 using astype. Hopefully your data does not contain values greater than 255. If it does, astype('uint8') will keep only the least significant bits (i.e. return the number modulo 256).

image_data = np.dstack(image_data).astype('uint8')
pillow_image = Image.fromarray(image_data)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for such a informative answer. It it as simple to cover it back again?
I'm not sure what you mean by "cover". If you mean how to split it into 4 separate arrays again, then you could use arr = np.array(pillow_image) and r, g, b, a = arr[..., 0], arr[..., 1], arr[..., 2], arr[..., 3].
Sorry, I mean convert them back to 4 arrays again. I can see from the link you posted some good examples. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.