【问题标题】:How to read image from numpy array into PIL Image?如何将 numpy 数组中的图像读入 PIL Image?
【发布时间】:2015-05-20 09:39:48
【问题描述】:

我正在尝试使用 PIL 从 numpy 数组中读取图像,方法如下:

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

并收到以下错误:

File "...Image.py", line 2155, in fromarray
    raise TypeError("Cannot handle this data type")

我认为这是因为fromarray 期望形状为(height, width, num_channels),但我拥有的数组的形状为(num_channels, height, width),因为它存储在lmdb 数据库中。

如何重塑图像以使其与Image.fromarray 兼容?

【问题讨论】:

  • 也许可以试试Image.fromarray(np.uint8(img))
  • 数组的类型是uint8,问题出在形状上

标签: python numpy pillow lmdb


【解决方案1】:

你不需要重塑。 This is what rollaxis is for:

Image.fromarray(np.rollaxis(img, 0,3))

【讨论】:

    【解决方案2】:

    试试

    img = np.reshape(256, 256, 3)
    Image.fromarray(img)
    

    【讨论】:

      【解决方案3】:

      将 numpy 数组的数据类型定义为 np.uint8 为我修复了它。

      >>> 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
      

      所以用正确的数据类型定义数组:

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

      成功创建 Image 对象

      或者您可以简单地修改现有的 numpy 数组:

      img = img.astype(np.uint8)
      

      【讨论】:

        猜你喜欢
        • 2010-09-27
        • 2015-12-18
        • 2019-11-29
        • 2021-12-09
        • 2017-06-25
        • 1970-01-01
        • 1970-01-01
        • 2018-11-22
        • 2012-11-13
        相关资源
        最近更新 更多