How to read image from numpy array into PIL Image?

前端 未结 3 594
心在旅途
心在旅途 2021-01-17 22:38

I am trying to read an image from a numpy array using PIL, by doing the following:

from PIL import Image
import numpy as np
#img is a np array with shape (3,         


        
相关标签:
3条回答
  • 2021-01-17 23:01

    You don't need to reshape. This is what rollaxis is for:

    Image.fromarray(np.rollaxis(img, 0,3))
    
    0 讨论(0)
  • 2021-01-17 23:18

    Try

    img = np.reshape(256, 256, 3)
    Image.fromarray(img)
    
    0 讨论(0)
  • 2021-01-17 23:19

    Defining the datatype of the numpy array to np.uint8 fixed it for me.

    >>> img = np.full((256, 256), 3)
    >>> Image.fromarray(img)
    ...
    line 2753, in fromarray
    raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e
    TypeError: Cannot handle this data type: (1, 1), <i8
    

    So defining the array with the proper datatype:

    >>> img = np.full((256, 256), 3, dtype=np.uint8)
    >>> Image.fromarray(img)
    <PIL.Image.Image image mode=L size=256x256 at 0x7F346EA31130>
    

    creates the Image object successfully

    Or you could simply modify the existing numpy array:

    img = img.astype(np.uint8)
    
    0 讨论(0)
提交回复
热议问题