在colormap中替换颜色 (python 3.7)

问题描述 投票:0回答:1

我使用一个简单的行将一个索引的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位,所以颜色是调色板的一部分),然后做。

  • 将0号索引的颜色与颜色图中的洋红交换位置。
  • 每一个文件的洋红位置都不一样,只要找到255 0 25的颜色,把索引0的颜色替换掉就可以了,但也要把索引0的颜色放在洋红的位置上。
  • 对文件夹中的所有.png文件进行一次运行(在运行脚本之前,洋红色将被添加,并对图像进行索引enter image description here

This is an image where Magenta isnt first color of image paletteHere is how it should be as final result

python replace colormap 8-bit indexed
1个回答
0
投票

我想你想要的是这样的东西。

#!/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
© www.soinside.com 2019 - 2024. All rights reserved.