【问题标题】:How to retain the colors of a PNG image when converting back from an array从数组转换回来时如何保留PNG图像的颜色
【发布时间】:2021-01-17 19:54:07
【问题描述】:

每当我将 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 但这不起作用,它只会返回一个 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)

【问题讨论】:

  • 错误是这一行im= im.putpalette(pat):putpalette 工作就地,所以不要把这个操作的结果写回im。只是im.putpalette(pat)。使用该修复程序,第二个代码对我来说可以正常工作。
  • 如果您仍然遇到问题,请告诉我
  • @HansHirse 啊,相当简单的修复。如果您希望我检查它,请随时发布您的解决方案。

标签: python numpy python-imaging-library png color-palette


【解决方案1】:

您的图像使用调色板使用单通道颜色。试试下面的代码。你也可以在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()

【讨论】:

  • 嗨,亚历克斯,感谢您的回答。您的解决方案绝对正确,但我一直在寻找一种无需将图像转换为“RGB”的解决方案。我想将图像保留为单个通道,同时将其扩展为数组。汉斯的评论解决了我的需要。如果汉斯没有给出答案,那么我会继续确认你的答案。谢谢。
【解决方案2】:

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

im= im.putpalette(pat)

如果你引用documentation of Image.putpalette,你会看到这个函数没有返回任何值,因此Image.putpalette直接应用于相应的图像。因此,没有必要(重新)分配不存在的返回值(即None)——或者,如这里所示,是错误的。

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

im.putpalette(pat)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-18
    • 2021-07-05
    • 2020-02-17
    • 2018-11-17
    • 2017-12-05
    • 2013-03-30
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多