我有一组24位的png文件,想将它们转换成8位的png文件。我使用了PIL的Image.convert()方法来解决这个问题。然而,在使用参数'mode=P'后,我发现具有相同RGB值的像素可能会被不同地转换。
我将一个示例图像转换为numpy数组,并且原始的24位png文件像这样具有值:
我希望相同RGB值的像素被以相同的方式转换。我知道像素被转换为调色板索引,但这仍然对我没有意义。我不熟悉PIL库。可以有人解释一下为什么会发生这种情况吗?提前感谢您。
根据 Mark 的示例实现了一个小功能。
对角像素的值已打印
在模式“P”下,8位图像包含125个唯一的调色板索引。似乎无论如何PIL都会执行抖动处理。
我将一个示例图像转换为numpy数组,并且原始的24位png文件像这样具有值:
RGB数组
...,
[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位数组
..., 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]))
对角像素的值已打印
... 154 154 154 154 154 154 124 154 160 160 160 154 160 ...
在模式“P”下,8位图像包含125个唯一的调色板索引。似乎无论如何PIL都会执行抖动处理。