PIL TypeError:无法处理此数据类型

时间:2019-03-24 01:26:18

标签: python python-imaging-library

我有一个图像存储在numpy数组中,我想将其转换为PIL.Image,以便执行仅适用于PIL的插值。

尝试通过Image.fromarray()进行转换时,会引发以下错误:

  

TypeError:无法处理此数据类型

我已经阅读了herehere的答案,但它们似乎对我的情况没有帮助。

我要运行的内容:

from PIL import Image

x  # a numpy array representing an image, shape: (256, 256, 3)

Image.fromarray(x)

3 个答案:

答案 0 :(得分:0)

tl; dr

x是否在[0,255]中包含uint个值?如果不是,尤其是x的范围是0到1,那就是错误的原因。


说明

大多数图像库(例如matplotlib,opencv,scikit-image)都有两种表示图像的方式:

  • uint,值范围为0到255。
  • float,值范围为0到1。

后者在执行图像之间的操作时更为方便,因此在计算机视觉领域更为流行。 但是PIL似乎不支持RGB图像

看看here 似乎当您尝试从数组中读取图像时,如果数组的形状为(height, width, 3),它会自动假定它是RGB图像,并且期望它的dtype为{{ 1}} ! 但是,根据您的情况,您有一个RBG图片,其uint8值从0到1。


解决方案

您可以通过将图像转换为PIL期望的格式来修复它:

float

答案 1 :(得分:0)

以不同的方式解决

问题情况: 使用 灰度图像 二进制图像 时,如果numpy数组形状为(height, width, 1),错误也会出现。
例如,一张32 x 32像素的灰度图像(值0到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)

将提高TypeError: Cannot handle this data type: (1, 1, 1), |u1

解决方案:

如果图像形状为(32, 32, 1),请缩小尺寸(32, 32)

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

这次可以了!

另外,请确保dtypeuint8(对于灰色)或bool(对于二进制)。

答案 2 :(得分:0)

在我的案例中,我发现了相同错误的不同问题。我使用的图像是 RGBA 格式,所以在使用 fromarray() 函数之前,只需使用 convert() 函数将其转换为 RGB,它就可以正常工作。

image_file = Image.open(image_file)
image_file = image_file.convert('RGB')

P.S.:在将图像转换为 np 之前,将此解决方案作为初始步骤发布。