我使用一条简单的线将 256 色索引图像分解为调色板
import numpy as np
from PIL import Image
im = Image.open('')
palette = np.array(im.getpalette(),dtype=np.uint8).reshape((256,3))
#####################
Printed result
[[ 1 3 0]
[ 2 4 1]
[ 28 0 4]
[ 20 2 26]
[ 24 5 18]
[ 33 7 22]
[ 36 7 12]
[ 0 20 18]
[ 42 15 16]
[ 43 18 30]
... etc
打印“调色板”将颜色列为 RGB 值,从索引 0 开始列出。索引 0 通常是深色或黑色。在某些引擎中,它用于 alpha、透明度。我想使用常用的透明度颜色,例如洋红色 255 0 255
我想将每个 png 文件放在一个文件夹中并进行批处理(我必须手动将颜色添加到图像中,然后将它们保存为 8 位,以便颜色成为调色板的一部分),然后执行以下操作:
- 在颜色图中将索引 0 颜色与洋红色交换位置
- 每个文件的洋红色位置会有所不同,只需找到颜色 255 0 25 并用它替换索引 0 处的颜色,同时也将索引 0 颜色放在洋红色位置
- do for all .png files in folder with a single run (magenta will be added and images indexed before running the script)
我想你想要这样的东西:
#!/usr/bin/env python3
import numpy as np
from PIL import Image
# Open image
im = Image.open('image.png')
# Extract palette
palette = np.array(im.getpalette(),dtype=np.uint8).reshape((256,3))
# Look through palette
for index,entry in enumerate(palette):
# Swap this entry with entry 0 if this is magenta
if index>0 and np.all(entry==[255,0,255]):
print(f'DEBUG: Swapping entry {index} with entry 0')
palette[0], palette[index] = palette[index], palette[0]
break
else:
print('ERROR: Did not find magenta entry in palette')
# Replace palette with new one and save
im.putpalette(palette)
im.save('result.png')
您可能会对其进行编码以在命令行上接受多个文件,如下所示:
for file in sys.argv[1:]:
...
...
然后你可以运行:
UpdatePalette.py *.png
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)