替换颜色图中的颜色(python 3.7) [英] Replace colors in colormap (python 3.7)
问题描述
我使用一条简单的线将索引图像 256 色分解为调色板
I use a simple line to break an indexed image 256 color into palette using
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、透明度.我想使用常用的透明颜色,如 Magenta 255 0 255
Printing 'palette' lists the colors as RGB values as listed from index 0 onward. Index 0 is often dark color or black. In some engines it is used for alpha, transparency. I want to use commonly used colors for transparency like Magenta 255 0 255
我想将我的每个 png 文件放在一个文件夹中并进行批处理(我必须手动将颜色添加到图像中,然后将它们保存为 8 位,以便颜色成为调色板的一部分)然后执行:
I want to take each of my png files in a folder and do batch (I will have to manually add the color to the images, then save them as 8 bit so the color is part of the palette) then do:
- 将索引 0 颜色与颜色图中洋红色的位置交换
- 每个文件的洋红色位置会有所不同,只需找到颜色 255 0 25 并用它替换索引 0 处的颜色,同时取索引 0 颜色并将其放在洋红色位置
- 一次运行即可处理文件夹中的所有 .png 文件(在运行脚本之前将添加品红色并索引图像)
推荐答案
我想你想要这样的:
#!/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')
<小时>
您可能会将其编码为在命令行上接受多个文件,如下所示:
You would probably code it to accept multiple files on the command line like this:
for file in sys.argv[1:]:
...
...
然后你可以运行:
UpdatePalette.py *.png
这篇关于替换颜色图中的颜色(python 3.7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!