python - PIL:fromarray 在 P 模式下给出了错误的对象
问题描述
我想以P
模式加载图像,将其转换为np.array
然后再将其转换回来,但我得到了一个错误的图像对象,它是灰色图像,而不是彩色图像
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')