PIL:fromarray在P模式下给出了错误的对象 [英] PIL: fromarray gives a wrong object in P mode
本文介绍了PIL:fromarray在P模式下给出了错误的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以 P
模式加载图像,将其转换为 np.array
,然后将其转换回,但是我得到了一个错误的Image对象,该对象是灰色的图片,而不是彩色图片
I want to load an image in P
mode, transform it into np.array
and then transform it back, but I got a wrong Image object which is a gray image, not a color one
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
是灰色图片
dir
is the path of the original picture; test.png
is a gray picture
推荐答案
"P"模式下的图像需要一个调色板,该调色板将每个颜色索引与实际的RGB颜色相关联.将图像转换为数组会丢失调色板,您必须再次将其还原.
Images in 'P' mode require a palette that associates each color index with an actual RGB color. Converting the image to an array loses the palette, you must restore it again.
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')
这篇关于PIL:fromarray在P模式下给出了错误的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文