I have a 4 channel Numpy image that needs to be converted to PIL image in order implement torchvision transformations on image. But when I try to do this using PIL.Image.from_array(<my_numpy_image>) I get the following error.

TypeError: Cannot handle this data type

I cannot loose and get rid of any channel information right now so won't be able to discard any channels.

  • $\begingroup$ Are you sure you are passing in a Numpy array of floats? Can you print type(my_numpy_image) and my_numpy_image.dtype? $\endgroup$
    – Richard
    Aug 21 '19 at 17:39
  • $\begingroup$ It's numpy array of np.uint8 $\endgroup$
    – thanatoz
    Aug 21 '19 at 17:43

Try specifying mode so that PIL is aware of data format.

img = Image.fromarray(source_array, mode="CMYK")

If that does not work, what is the shape of source array ?

  • $\begingroup$ The shape of source arrays are (1400,2100) and they are all consistent in shape. What will happen if the channel number is even greater? $\endgroup$
    – thanatoz
    Aug 21 '19 at 17:45
  • $\begingroup$ Why does this array have only two dimensions ? Source array should be 4D (#Images, #Channels, X_dim,Y_dim). # of channels can be 1 (Grayscale) 3 (RGB) or 4 (RGBA / CMYK) $\endgroup$ Aug 22 '19 at 2:50
  • $\begingroup$ I was just representing the shape of every individual channel with its 2d matrix. The shape of the complete array is (1400,2100,4). But it is not a CMYK image but just an arbitrary arrays of this shape. But I believe that we can treat it like a cmyk image. This should help. $\endgroup$
    – thanatoz
    Aug 22 '19 at 3:03
  • $\begingroup$ But what if I increase one more channel in the image? How will I be able to handle that data too in the future? $\endgroup$
    – thanatoz
    Aug 22 '19 at 3:04
  • $\begingroup$ (1400,2100,4) is missing one dimension. You need 1 int / float value for each pixel in image. Is 1400x2100 high/width ? $\endgroup$ Aug 22 '19 at 3:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.