You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何两次数组转PIL Image结果不同?报TypeError数据类型错误

问题:数组形状相同但Image.fromarray报错的原因

代码示例

im = Image.open("image.png")
im_out = im.convert("RGBA").resize((256,256))

image_data = np.asarray(im_out)
print(image_data.shape)
ni = Image.fromarray(image_data)

image_data2 = np.asarray(im_out.getdata())

image_data2 = image_data2.reshape(image_data.shape)

Image.fromarray(image_data2) # 此行报错

报错信息

TypeError: Cannot handle this data type: (1, 1, 4), <i4

原因分析

虽然两个数组的形状完全一致,但它们的数据类型(dtype)不匹配:

  • np.asarray(im_out)直接从PIL图像对象转换,得到的数组dtype是uint8(RGBA图像每个通道的像素值是0-255的无符号8位整数),这是PIL原生支持的格式。
  • np.asarray(im_out.getdata())是从图像的像素序列转换,得到的数组dtype是int32(报错里的<i4代表小端字节序的4字节整数),即使reshape成相同形状,PIL无法识别这种整数类型的图像数据。

解决办法

将image_data2强制转换为uint8类型即可:

image_data2 = image_data2.reshape(image_data.shape).astype(np.uint8)
Image.fromarray(image_data2) # 正常运行

内容的提问来源于stack exchange,提问作者Jjkivai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 18:35:28