【问题标题】:TypeError: Cannot handle this data type - Wrong mode for `PIL.Image.fromarray`?TypeError:无法处理此数据类型 - `PIL.Image.fromarray` 的模式错误?
【发布时间】:2019-10-15 15:04:27
【问题描述】:

我正在尝试使用PIL.Image.fromarray

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()

我希望看到红色、绿色和蓝色 3 个像素。

但是,如果我在文档示例中省略 mode 关键字参数,我会得到:

TypeError: 无法处理此数据类型

如果我设置mode="RGB",保存的图像文件test.pngmatplotlib窗口都如下所示:

【问题讨论】:

    标签: python arrays image numpy python-imaging-library


    【解决方案1】:

    堆叠您的三个数组并根据thisthis 答案将它们转换为uint8 类型。

    import matplotlib.pyplot as plt
    import numpy as np
    from PIL import Image
    
    a = (np.dstack(([255, 0, 0],[0, 255, 0],[0, 0, 255]))).astype(np.uint8) 
    
    im = Image.fromarray(a, mode="RGB")
    im.save("test.png")
    plt.imshow(im)
    plt.show()
    

    替代选项是为您的输入数组添加额外维度,使其形状为(1, 3, 3)

    a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], dtype=np.uint8)
    im = Image.fromarray(a, mode="RGB")
    

    【讨论】:

    • @finefoot:好的,那么你只需要转换成(np.uint8)类型
    【解决方案2】:

    根据https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes 模式RGB 应该是3x8 位像素。但是,numpy.ndarray 的类型默认为 int64

    >>> a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
    >>> a.dtype
    dtype('int64')
    

    就是这样

    TypeError: 无法处理此数据类型

    来自。如果我为数组设置正确的 8 位 dtype 关键字,一切正常,即使没有指定 mode 关键字:

    import matplotlib.pyplot as plt
    import numpy as np
    from PIL import Image
    
    a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
    im = Image.fromarray(a, mode="RGB")
    im.save("test.png")
    plt.imshow(im)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-04-19
      • 1970-01-01
      • 2023-04-02
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 2020-06-16
      相关资源
      最近更新 更多