gpt4 book ai didi

python - PIL 的 Image.convert() 函数如何使用模式 'P'

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:08 34 4
gpt4 key购买 nike

我有一组 24 位 png 文件,我想将它们转换为 8 位 png 文件。我使用 PIL 的 Image.convert() 方法来解决这个问题。但是,在使用模式“P”作为参数后,我发现具有相同 RGB 值的像素可以进行不同的转换。

我将示例图像传输到一个 numpy 数组中,原始 24 位 png 文件具有如下值:

RGB array

   ..., 
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
[204, 102, 119],
...

在使用模式为“P”的转换函数后,图像值变成了这样:

8-bit array

   ..., 98, 98, 134, 98, 98, 98, 134, 98, 98, 98, 134, ...

代码示例:

from PIL import Image
import numpy as np
img = Image.open("path-to-file.png")
p_img = img.convert("P")

我希望具有相同 RGB 值的像素以相同的方式转换。我知道像素被转换成调色板索引,但这对我来说仍然没有意义。我不熟悉 PIL 库。有人可以解释为什么会这样吗?提前致谢。


按照 Mark 的例子实现了一些东西

import numpy as np
from PIL import Image
#from improc import GenerateNColourImage

# Set image height and width
N = 6
h, w = 100, 100

# Generate repeatable random Numpy image with N^3 unique colours at most
n = np.random.randint(N, size=(h, w, 3), dtype=np.uint8)
# Work out indices of diagonal elements
diags = np.diag_indices(h)

# Intentionally set all diagonal elements same shade of blue
n[diags] = [10,20,200]
# Make Numpy image into PIL Image, palettise, convert back to Numpy array and check diagonals
a0 = Image.fromarray(n)

unique_colors = np.unique(n.reshape(-1, n.shape[2]), axis=0).shape
print(unique_colors) #e.g. print (217, 3)
a1 = a0.convert('P')
a2 = np.array(a1)

# Look at diagonals - should all be the same
print(a2[diags])
print(' %s %d' % ("Number of unique colors: ", np.unique(a2).shape[0]))

Diagonal pixels' values printed

... 154 154 154 154 154 154 124 154 160 160 160 154 160 ...

“P”模式下的 8 位图像包含 125 个唯一的调色板索引。看来 PIL 无论如何都会执行抖动。

最佳答案

当我们将图像转换为 P 颜色模式时,这是显示的正常行为。调色板模式的工作方式是创建一个映射表,该映射表将一个索引(在 0 - 255 范围内)对应到更大颜色空间(如 RGB)中的离散颜色。例如,图像中的 RGB 颜色值 (0, 0, 255)(纯蓝色)得到索引 1(只是一个假设的例子)。同样的过程遍历原始图像中的每个唯一像素值(但在映射过程中,表格大小不应超过 256)。因此,具有如下值的 numpy 数组(或常规列表):-

   ..., 98, 98, 134, 98, 98, 98, 134, 98, 98, 98, 134, ...

对应于映射表中的索引,而不是实际颜色值本身。因此,您可以将它们解释为一个索引,它在读取图像时会转换为存储在该索引中的实际颜色值。

但是这些像素值,并不总是意味着图像是颜色模式P。例如,如果您查看灰度图像 (​​L) 的像素数据,这些值看起来与调色板模式下的情况相同,但实际上对应于真实颜色值(或阴影)灰色),而不是索引。

关于python - PIL 的 Image.convert() 函数如何使用模式 'P',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56962889/

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