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

问题描述

每当我将PNG图像转换为np.array然后再将其转换回PNG时,我都会丢失图像的所有颜色。从np.array转换回原始PNG时,我希望能够保留其颜色。

原始PNG图片

enter image description here

我的代码

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')

输出图像的黑白版本

enter image description here

我也尝试使用getpaletteputpalette,但这不起作用,它只会返回一个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)

解决方法

您的图像使用调色板的单一通道颜色。试试下面的代码。您也可以在What is the difference between images in 'P' and 'L' mode in PIL?

上查看有关此主题的更多信息
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,则会看到此函数不返回任何值,因此Image.putpalette直接应用于相应的图像。因此,不需要(重新)分配不存在的返回值(然后是None),或者是错误的。

因此,简单的解决方法就是使用:

im.putpalette(pat)

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