gpt4 book ai didi

python - PIL : fromarray gives a wrong object in P mode

转载 作者:行者123 更新时间:2023-11-30 09:17:53 24 4
gpt4 key购买 nike

我想以 P 模式加载图像,将其转换为 np.array 然后再转换回来,但我得到了错误的 Image 对象,它是灰色的图片,不是彩色的

label = PIL.Image.open(dir).convert('P')
label = np.asarray(label)
img = PIL.Image.fromarray(label, mode='P')
img.save('test.png')

dir为原图片的路径; test.png是一张灰色图片

最佳答案

“P”模式下的图像需要一个将每个颜色索引与实际 RGB 颜色相关联的调色板。将图像转换为数组会丢失调色板,必须重新恢复它。

label = PIL.Image.open(dir).convert('P')
p = label.getpalette()
label = np.asarray(label)
img = PIL.Image.fromarray(label, mode='P')
img.setpalette(p)
img.save('test.png')

关于python - PIL : fromarray gives a wrong object in P mode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446949/

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