我使用一个简单的行将一个索引的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]
等
打印 "调色板 "将颜色以RGB值的形式从索引0开始列出。索引0通常是深色或黑色。在一些引擎中,它被用于alpha、透明度。我想用常用的颜色来做透明度,比如品红255 0 255
我想把我的每一个png文件放在一个文件夹里,然后做批处理(我必须手动添加颜色到图像中,然后把它们保存为8位,所以颜色是调色板的一部分),然后做。
我想你想要的是这样的东西。
#!/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