使用PIL Image.fromarray()转换numpy数组遇TypeError求助
问题描述
我有一段代码:
cam_gb = Image.fromarray(cam_gb)
其中cam_gb是numpy.ndarray类型,数据类型为float64,形状为(3, 224, 224)。运行时出现如下错误:
File "\site-packages\PIL\Image.py", line 3073, in fromarray raise TypeError(msg) from e TypeError: Cannot handle this data type: (1, 1, 224), <f8
即使把cam_gb从形状(3, 224, 224)转置为(224, 224, 3),还是会报同样的错误。
我还尝试了这段代码:
cam_gb = Image.fromarray(cam_gb.astype(np.uint8))
得到错误:
File "\lib\site-packages\PIL\Image.py", line 3073, in fromarray raise TypeError(msg) from e TypeError: Cannot handle this data type: (1, 1, 224), |u1
也试过:
cam_gb = Image.fromarray((cam_gb * 255).astype(np.uint8))
但错误依旧:
File "\lib\site-packages\PIL\Image.py", line 3073, in fromarray raise TypeError(msg) from e TypeError: Cannot handle this data type: (1, 1, 224), |u1
我原本打算执行这段代码:
cam_gb_on_image = Image.alpha_composite(original_image, cam_gb)
希望能得到解决办法,谢谢。
解决方法
错误提示里的(1,1,224)说明实际处理的数组维度和你描述的(3,224,224)不匹配,大概率是通道维度出了问题,按以下步骤修复:
确认数组真实形状
先打印cam_gb.shape确认维度,排查是否有代码操作悄悄修改了数组形状(比如误执行squeeze、维度缩减)。正确调整维度与数据格式
PIL的fromarray要求RGB图像维度顺序为(高度, 宽度, 通道数),且uint8类型数据范围需在0-255之间。如果数组确实是(3,224,224),执行以下操作:# 转置为(H, W, C)顺序 cam_gb = cam_gb.transpose(1, 2, 0) # 归一化到0-1区间后转成0-255的uint8 cam_gb = (cam_gb - cam_gb.min()) / (cam_gb.max() - cam_gb.min()) * 255 cam_gb = cam_gb.astype(np.uint8) # 转换为PIL图像 cam_gb_img = Image.fromarray(cam_gb)适配alpha合成要求
Image.alpha_composite要求两张图均为RGBA模式,需做格式转换:original_image_rgba = original_image.convert("RGBA") cam_gb_rgba = cam_gb_img.convert("RGBA") # 可调整热力图透明度,比如设为半透明 cam_gb_rgba.putalpha(128) # 合成图像 cam_gb_on_image = Image.alpha_composite(original_image_rgba, cam_gb_rgba)
内容的提问来源于stack exchange,提问作者Haider
相关产品推荐
相关产品推荐

