我为此想到了一种方法:
- 提取并保存Alpha/透明度通道
- 将图像减去 Alpha 后转换为 HSV 色彩空间并保存 V(亮度)
- 从颜色选择器中获取新的色调(可能还有饱和度)
- 合成一个新的色调通道和一个新的饱和度通道 255(完全饱和)
- 将新的色相、饱和度和原始 V(亮度)合并到 3 通道 HSV 图像
- 将 HSV 图像转换回 RGB 空间
- 将原来的 Alpha 通道合并回来
看起来像这样:
#!/usr/local/bin/python3
import numpy as np
from PIL import Image
# Open and ensure it is RGB, not palettised
img = Image.open("keyshape.png").convert('RGBA')
# Save the Alpha channel to re-apply at the end
A = img.getchannel('A')
# Convert to HSV and save the V (Lightness) channel
V = img.convert('RGB').convert('HSV').getchannel('V')
# Synthesize new Hue and Saturation channels using values from colour picker
colpickerH, colpickerS = 10, 255
newH=Image.new('L',img.size,(colpickerH))
newS=Image.new('L',img.size,(colpickerS))
# Recombine original V channel plus 2 synthetic ones to a 3 channel HSV image
HSV = Image.merge('HSV', (newH, newS, V))
# Add original Alpha layer back in
R,G,B = HSV.convert('RGB').split()
RGBA = Image.merge('RGBA',(R,G,B,A))
RGBA.save('result.png')
With colpickerH=10
你明白了(尝试把Hue=10
here https://www.w3schools.com/colors/colors_hsl.asp):
With colpickerH=120
你明白了(尝试把Hue=120
here https://www.w3schools.com/colors/colors_hsl.asp):
只是为了好玩,您可以在不编写任何 Python 的情况下完成完全相同的操作,只需在命令行中使用图像魔术师它安装在大多数 Linux 发行版上,并且适用于 macOS 和 Windows:
# Split into Hue, Saturation, Lightness and Alpha channels
convert keyshape.png -colorspace hsl -separate ch-%d.png
# Make a new solid Hue channel filled with 40, a new solid Saturation channel filled with 255, take the original V channel (and darken it a little), convert from HSL to RGB, copy the Alpha channel from the original image
convert -size 73x320 xc:gray40 xc:white \( ch-2.png -evaluate multiply 0.5 \) -set colorspace HSL -combine -colorspace RGB ch-3.png -compose copyalpha -composite result.png
是的,我可以把它写成一行行,但它会更难阅读。