想要将numpyarray转换成Image出错,ValueError: Could not save to PNG for display

发布时间:2023年12月19日

问题再现

cams_H 是一个形状为torch.size([1, 7, 7, 3])的tensor,
它经历了以下语句:

cams_H_np = cams_H.numpy()
cams_H_img = Image.fromarray(cams_H_np[0, :, :, 0])
cams_H_img

报错了:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/anaconda3/envs/myenvs/lib/python3.7/site-packages/PIL/PngImagePlugin.py in _save(im, fp, filename, chunk, save_all)
   1285     try:
-> 1286         rawmode, mode = _OUTMODES[mode]
   1287     except KeyError as e:

KeyError: 'F'

The above exception was the direct cause of the following exception:

OSError                                   Traceback (most recent call last)
~/anaconda3/envs/myenvs/lib/python3.7/site-packages/PIL/Image.py in _repr_png_(self)
    679         try:
--> 680             self.save(b, "PNG")
    681         except Exception as e:

~/anaconda3/envs/myenvs/lib/python3.7/site-packages/PIL/Image.py in save(self, fp, format, **params)
   2431         try:
-> 2432             save_handler(self, fp, filename)
   2433         except Exception:

~/anaconda3/envs/myenvs/lib/python3.7/site-packages/PIL/PngImagePlugin.py in _save(im, fp, filename, chunk, save_all)
   1288         msg = f"cannot write mode {mode} as PNG"
-> 1289         raise OSError(msg) from e
...
--> 683             raise ValueError(msg) from e
    684         return b.getvalue()
    685 

ValueError: Could not save to PNG for display

解决方法

想要转换成Image的话,要先把数据存储结构换成uint8才行,
在转换成Image之前,添加cams_H_np = cams_H_np.astype('uint8'),解决啦!

文章来源:https://blog.csdn.net/weixin_44092088/article/details/135092012
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。