从数组转换回时如何保留 PNG 图像的颜色

How to retain the colors of a PNG image when converting back from an array

每当我将 PNG 图像转换为 np.array 然后再将其转换回 PNG 时,我会丢失图像的所有颜色。当我将它从 np.array.

转换回来时,我希望能够保留原始 PNG 的颜色

原始 PNG 图片

我的代码:

from PIL import Image    

im = Image.open('2007_000129.png')
im = np.array(im)

#augmenting image
im[0,0] = 1

im = Image.fromarray(im, mode = 'P')

输出图像的黑白版本

我也尝试使用 getpaletteputpalette 但这不起作用它只是 returns 一个 NonType 对象。

im = Image.open('2007_000129.png')
pat = im.getpalette()
im = np.array(im)
im[0,0] = 1
im = Image.fromarray(im, mode = 'P')
im= im.putpalette(pat)

您的图像使用调色板的单通道颜色。试试下面的代码。您也可以在

查看有关此主题的更多信息
from PIL import Image    
import numpy as np


im = Image.open('gsmur.png')
rgb = im.convert('RGB')
np_rgb = np.array(rgb)
p = im.convert('P')
np_p = np.array(p)

im = Image.fromarray(np_p, mode = 'P')
im.show()
im2 = Image.fromarray(np_rgb)
im2.show()

使用提供的第二个代码,错误来自这一行:

im= im.putpalette(pat)

如果你参考documentation of Image.putpalette,你会看到这个函数没有return任何值,因此Image.putpalette直接应用于相应的图像。因此,(重新)分配 non-existent return 值(然后是 None)是没有必要的——或者,如这里所见,是错误的。

所以,简单的解决方法就是使用:

im.putpalette(pat)

使用此更改,提供的第二个代码按预期工作。