PIL图像从I模式转换为P模式

时间:2019-10-21 15:43:19

标签: python python-imaging-library color-depth

我有这张深度图:

enter image description here

我用PIL加载的

depth_image = Image.open('stereo.png')

如果我打印图像的模式,它将显示模式I,即根据文档说明为(32-bit signed integer pixels)

这是正确的,因为图像值的范围是0到255。我想将此深度图像着色以更好地可视化,所以我尝试使用以下调色板将其转换为P模式:

depth_image = depth_image.convert('P', palette=custom_palette)
depth_image.save("colorized.png")

但是结果是这样的黑白图像:

enter image description here

我确定调色板可以,因为int格式中的256种颜色全部集中在一个阵列中。

在保存之前,我曾尝试将其转换为RGB

depth_image = depth_image.convert('RGB')

我也尝试过添加调色板,如:

depth_image = depth_image.putpalette(custom_palette)

如果我尝试保存它而不将其转换为RGB,则会得到:

    depth_image.save("here.png")
AttributeError: 'NoneType' object has no attribute 'save'

到目前为止,我将尝试将图像转换为numpy数组,然后从那里映射颜色,但是我想知道关于PIL缺少什么。我正在浏览文档,但是没有发现有关IP转换的任何信息。

1 个答案:

答案 0 :(得分:1)

我认为问题在于您的值缩放到0..65535而不是0..255的范围。

如果执行此操作,则会看到值大于预期值:

i = Image.open('depth.png') 
n = np.array(i) 

print(n.max(),n.mean())
# prints 32257, 6437.173

因此,我迅速尝试:

n = (n/256).astype(np.uint8)
r = Image.fromarray(n)
r=r.convert('P') 
r.putpalette(custom_palette)     # I grabbed this from your pastebin

it may only be possible for the background