gpt4 book ai didi

python - 在 PIL/pillow 中处理二进制 PNG 图像

转载 作者:太空狗 更新时间:2023-10-30 02:53:25 24 4
gpt4 key购买 nike

当将二进制 PNG 文件从 PIL Image 对象转换为 numpy 数组时,无论原始图像是否反转,值都是相同的。

例如,这两个图像生成相同的 numpy 数组。

t image t inverted image

import numpy as np
from PIL import Image
t = Image.open('t.png')
t_inverted = Image.open('t_inverted.png')
np.asarray(t)
np.asarray(t_inverted)

np.asarray(t)np.asarray(t_inverted) 的输出是:

array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 0, 1, 1, 0, 1],
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=uint8)

我预计 0 和 1 也会倒置。为什么它们是一样的?

最佳答案

这两个 PNG 文件都是索引。它们包含相同的数据数组,只有您看到的值 0 和 1,但这些值并不是像素的颜色。它们应该是调色板中的索引。在第一个文件中,调色板是

 Index     RGB Value
0 [ 0, 0, 0]
1 [255, 255, 255]

在第二个文件中,调色板是

 Index     RGB Value
0 [255, 255, 255]
1 [ 0, 0, 0]

问题是当 Image 对象被转换为一个 numpy 数组时,调色板没有被使用,只有索引数组被返回。

要解决此问题,请使用 Image 对象的 convert() 方法将格式从索引调色板转换为 RGB 颜色:

t = Image.open('t.png')
t_rgb = t.convert(mode='RGB')
arr = np.array(t_rgb)

关于python - 在 PIL/pillow 中处理二进制 PNG 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49579522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com