用颜色填充图像但保留 alpha(PIL 中的颜色叠加)

Rea*_*10N 3 python python-imaging-library python-3.x

基本上,我正在尝试创建一个函数来获取给定的图像和颜色。对于图像中的每个像素,它将保留原始 alpha 值,但会将颜色更改为给定的颜色。

例如,如果函数得到下面的箭头图像和红色,

原始图像 - 所有颜色

它将输出以下图像:

结果图像 - 红色

在 Photoshop 和其他图像编辑器中,这种效果称为“颜色叠加”。是否有任何快速简便的方法可以在 PIL 中实现相同的结果?提前致谢!(;

Mar*_*ell 7

一种方法是创建一个与原始图像大小相同的纯红色图像,然后将原始图像的 alpha 通道复制到它上面:

from PIL import Image

# Open original image and extract the alpha channel
im = Image.open('arrow.png')
alpha = im.getchannel('A')

# Create red image the same size and copy alpha channel across
red = Image.new('RGBA', im.size, color='red')
red.putalpha(alpha) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


这是使用 Numpy 的第二种方法:

from PIL import Image
import numpy as np

# Open image
im = Image.open('arrow.png')

# Make into Numpy array
n = np.array(im) 

# Set first three channels to red
n[...,0:3]=[255,0,0] 

# Convert back to PIL Image and save
Image.fromarray(n).save('result.png')
Run Code Online (Sandbox Code Playgroud)

第三种方法是与类似大小的红色副本合成并使用原始 alpha 蒙版:

from PIL import Image

# Open image
im = Image.open('arrow.png')                                                                                                       

# Make solid red image same size
red = Image.new('RGBA', im.size, color='red')                                                                                      

# Composite the two together, honouring the original mask
im = Image.composite(red,im,im)  
Run Code Online (Sandbox Code Playgroud)

关键词:图像、图像处理、Python、枕头、PIL、Numpy、提取 alpha、alpha 通道、透明度、替换透明度、复制透明度、复制 alpha、移植 alpha、移植透明度。