PIL TypeError:无法处理此数据类型 [英] PIL TypeError: Cannot handle this data type

查看:206
本文介绍了PIL TypeError:无法处理此数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

When trying to convert it through Image.fromarray() it raises the following error:

TypeError:无法处理此数据类型

TypeError: Cannot handle this data type

我已在此处

I have read the answers here and here but they do not seem to help in my situation.

我要运行的内容:

from PIL import Image

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

Image.fromarray(x)

推荐答案

tl; dr

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

tl;dr

Does x contain uint values in [0, 255]? If not and especially if x ranges from 0 to 1, that is the reason for the error.

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

Most image libraries (e.g. matplotlib, opencv, scikit-image) have two ways of representing images:

  • uint,值范围为0到255.
  • float,值范围为0到1.
  • as uint with values ranging from 0 to 255.
  • as float with values ranging from 0 to 1.

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

The latter is more convenient when performing operations between images and thus is more popular in the field of Computer Vision. However PIL seems to not support it for RGB images.

如果您此处 看来,当您尝试从数组中读取图像时,如果数组的形状为(height, width, 3),它会自动假定它是RGB图像,并且期望它的dtypeuint8 ! 但是,对于您而言,您的RBG图像的float值介于0到1之间.

If you take a look here it seems that when you try to read an image from an array, if the array has a shape of (height, width, 3) it automatically assumes it's an RGB image and expects it to have a dtype of uint8! In your case, however, you have an RBG image with float values from 0 to 1.

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

You can fix it by converting your image to the format expected by PIL:

im = Image.fromarray((x * 255).astype(np.uint8))

这篇关于PIL TypeError:无法处理此数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆