替换colormap(python 3.7)中的颜色

2024-10-05 18:58:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一条简单的线,使用

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]

。。。等

打印“调色板”将颜色列为从索引0开始列出的RGB值。索引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


Tags: 文件from图像imageimportnumpy文件夹png
1条回答
网友
1楼 · 发布于 2024-10-05 18:58:45

我想你想要这样的东西:

#!/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

相关问题 更多 >