PIL TypeError:无法处理此数据类型 [英] PIL TypeError: Cannot handle this data type
问题描述
我有一个图像存储在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.
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屋!