0
from PIL import Image

array = np.zeros((3,64,64),'uint8')
array[0] = redToImage;
array[1] = blueToImage;
array[2] = greenToImage;

img = Image.fromarray(array)
if img.mode != 'RGB':
   img = img.convert('RGB')
img.save('testrgb.jpg')

I have redToImage,blueToImage,greenToImage and all of them is a numpy array with (64,64) size. However when I try to create image from array, it gives me that error. I really searched and tried lots of methods.

It gives this error:

***---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\PIL\Image.py in fromarray(obj, mode)
   2514             typekey = (1, 1) + shape[2:], arr['typestr']
-> 2515             mode, rawmode = _fromarray_typemap[typekey]
   2516         except KeyError:
KeyError: ((1, 1, 64), '|u1')
During handling of the above exception, another exception occurred:
TypeError                                 Traceback (most recent call last)
<ipython-input-331-9ce9e6816b75> in <module>
      6 array[2] = greenToImage;
      7
----> 8 img = Image.fromarray(array)
      9 if img.mode != 'RGB':
     10     img = img.convert('RGB')
~\Anaconda3\lib\site-packages\PIL\Image.py in fromarray(obj, mode)
   2515             mode, rawmode = _fromarray_typemap[typekey]
   2516         except KeyError:
-> 2517             raise TypeError("Cannot handle this data type")
   2518     else:
   2519         rawmode = mode
TypeError: Cannot handle this data type***
2
  • The three color arrays probably need to contain integer 'uint8' data. Commented Dec 9, 2019 at 21:25
  • I converted it to integer but this didn't solve the problem sir Commented Dec 9, 2019 at 22:00

1 Answer 1

1

The typing error says that Image.fromarray(array) cannot automatically reshape a (3, 64, 64) matrix to a (64, 64, 3) matrix. fromarray(x) expects that x will contain 3 layers or 64x64 blocks instead of 64 layers of 3x64 blocks. Changing your code to something similar as below produces the desired result (in my case a green 64x64 pixels .jpg image).

from PIL import Image
import numpy as np

array = np.zeros((64, 64, 3), 'uint8')

'''
Creating dummy versions of redToImage, greenToImage and blueToImage.
In this example, their combination denotes a completely green 64x64 pixels square.
'''
array[:, :, 0] = np.zeros((64, 64))
array[:, :, 1] = np.ones((64, 64))
array[:, :, 2] = np.zeros((64, 64))

img = Image.fromarray(array)
if img.mode != 'RGB':
    img = img.convert('RGB')
img.save('testrgb.jpg')
Sign up to request clarification or add additional context in comments.

Comments

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.