PIL更改颜色通道强度

时间:2018-07-25 13:38:22

标签: python-3.x image-processing python-imaging-library

我想制作一个颜色选择器,它可以在保留python3透明度的同时为png纹理重新着色。
我只希望重新着色图像的较亮部分,而且还希望保持渐变。
我唯一想到的选择是调整颜色通道强度,但是我在PIL文档中找不到类似的内容。
如何更改色彩通道强度?我的PNG纹理以ARGB模式加载,可以>>>> here <<。

找到。

原始图片:

enter image description here

1 个答案:

答案 0 :(得分:2)

我梦for以求的方法:

  • 提取并保存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')

使用colpickerH=10,您会收到以下提示(尝试放入Hue=10 here):

enter image description here

使用colpickerH=120,您会收到以下提示(尝试放入Hue=120 here):

enter image description here


只是为了好玩,您可以直接编写 ImageMagick 在命令行中使用完全相同的代码而无需编写任何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

是的,我可以单线完成,但是很难阅读。