gpt4 book ai didi

python - 如何保存解决此 : saving images with PIL. 图像

转载 作者:行者123 更新时间:2023-11-28 19:04:59 26 4
gpt4 key购买 nike

用PIL.Image保存图片时出现错误代码如下:

from PIL import Image
generated = np.load('/home/jovyan/GROUP_SHARED/Kimi.Zhang/cutout.npy')
generated = generated[:25, :, :, :]
print('image_size', generated.shape)

j = Image.fromarray(generated)
for i in range(len(generated)):
j.save('/home/jovyan/GROUP_SHARED/Kimi.Zhang/imagetest_' + str(i) +'.jpg')

“生成”包含25张图片,我想将它们一张一张保存为jpg。

结果是:

image_size (25, 3, 32, 32)

KeyError                                  Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/PIL/Image.py in fromarray(obj, mode)
2415 typekey = (1, 1) + shape[2:], arr['typestr']
-> 2416 mode, rawmode = _fromarray_typemap[typekey]
2417 except KeyError:

KeyError: ((1, 1, 32, 32), '<f4')

During handling of the above exception, another exception occurred:

TypeError Traceback (most recent call last)
<ipython-input-45-00cdf704f05a> in <module>()
5
6
----> 7 j = Image.fromarray(generated)
8 for i in range(len(generated)):
9 j.save('/home/jovyan/GROUP_SHARED/Kimi.Zhang/imagetest_' + str(i)
+ '.jpg')

/opt/conda/lib/python3.6/site-packages/PIL/Image.py in fromarray(obj, mode)
2417 except KeyError:
2418 # print(typekey)
-> 2419 raise TypeError("Cannot handle this data type")
2420 else:
2421 rawmode = mode

TypeError: Cannot handle this data type

有人知道怎么解决吗?非常感谢!

补充:

  KeyError                                  Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/PIL/Image.py in fromarray(obj, mode)
2415 typekey = (1, 1) + shape[2:], arr['typestr']
-> 2416 mode, rawmode = _fromarray_typemap[typekey]
2417 except KeyError:

KeyError: ((1, 1, 32), '<f4')

During handling of the above exception, another exception occurred:

TypeError Traceback (most recent call last)
<ipython-input-47-1316bb4844f6> in <module>()
7 #j = Image.fromarray(generated)
8 for i in range(len(generated)):
----> 9 j = Image.fromarray(generated[i])
10 j.save('/home/jovyan/GROUP_SHARED/Kimi.Zhang/imagetest_' + str(i)
+ '.jpg')
11

/opt/conda/lib/python3.6/site-packages/PIL/Image.py in fromarray(obj, mode)
2417 except KeyError:
2418 # print(typekey)
-> 2419 raise TypeError("Cannot handle this data type")
2420 else:
2421 rawmode = mode

TypeError: Cannot handle this data type

最佳答案

假设 generated 中的数据有效

  • 遍历第一个维度,跟踪索引
  • 确保数据类型正确
  • 创建图像
  • 保存图片

...
prefix = '\my\path\prefix'
ext = 'jpg'
for suffix, data in enumerate(generated):
print(data.shape)
data.dtype = np.uint8
im = Image.fromarray(data, mode = 'RGB')
print(f'{prefix}_{suffix}.{ext}')
im.save(f'{prefix}_{suffix}.{ext}', 'JPEG')

关于python - 如何保存解决此 : saving images with PIL. 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com