PIL TypeError: Cannot handle this data type

后端 未结 2 744
囚心锁ツ
囚心锁ツ 2021-02-01 02:28

I have an image stored in a numpy array that I want to convert to PIL.Image in order to perform an interpolation only available with PIL.

When trying to con

2条回答
  •  死守一世寂寞
    2021-02-01 03:25

    I solved it different way.

    Problem Situation: When working with gray image or binary image, if the numpy array shape is (height, width, 1), this error will be raised also.
    For example, a 32 by 32 pixel gray image (value 0 to 255)

    np_img = np.random.randint(low=0, high=255, size=(32, 32, 1), dtype=np.uint8)
    # np_img.shape == (32, 32, 1)
    pil_img = Image.fromarray(np_img)
    

    will raise TypeError: Cannot handle this data type: (1, 1, 1), |u1

    Solution:

    If the image shape is like (32, 32, 1), reduce dimension into (32, 32)

    np_img = np.squeeze(np_img, axis=2)  # axis=2 is channel dimension 
    pil_img = Image.fromarray(np_img)
    

    This time it works!!

    Additionally, please make sure the dtype is uint8(for gray) or bool(for binary).

提交回复
热议问题