【问题标题】:PIL: fromarray gives a wrong object in P modePIL:fromarray 在 P 模式下给出了错误的对象
【发布时间】:2018-10-30 23:57:28
【问题描述】:

我想以P 模式加载图像,将其转换为np.array,然后再将其转换回来,但我得到了一个错误的图像对象,它是灰色图像,而不是彩色图像

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是一张灰图

【问题讨论】:

  • 我已经修改了问题,它几乎是完整的代码
  • 在此处提供示例图片。
  • 另外,这是因为您丢弃了调色板。您必须以“P”模式打开,而不是转换为它。
  • 如果您在第一行之后立即执行label.save('preconvert.png') 会发生什么?

标签: python numpy machine-learning python-imaging-library


【解决方案1】:

“P”模式下的图像需要将每个颜色索引与实际 RGB 颜色相关联的调色板。将图像转换为数组会丢失调色板,您必须重新恢复它。

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

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2019-04-14
    • 2021-04-18
    • 1970-01-01
    • 2011-09-21
    • 2022-12-03
    • 2013-11-10
    • 2018-03-28
    • 1970-01-01
    相关资源
    最近更新 更多