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

标签 python python-3.x python-imaging-library

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

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

Original image - all colors

它将输出如下图像:

Result image - red

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

最佳答案

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

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) 

enter image description here


这是使用 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')

第三种方法是与类似大小的红色副本合成并使用原始的 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)  

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

关于python - 用颜色填充图像但保留 alpha(PIL 中的颜色叠加),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56196592/

相关文章:

python - 如果没有图像处理Python库(Pillow和cv2)无法读取,如何解码这个二进制图像文件?

python - Sklearn 预处理 - PolynomialFeatures - 如何保留输出数组/数据帧的列名/标题

python - 在 python 中将文件附加到电子邮件会导致文件名空白?

python - urllib2.urlopen : "Name or service not known" persists when starting script without internet connection

python - 运行 jupyter notebook 时导入错误 : No module named IPython. 路径?

python - gensim 文件未找到错误

python - 如何在保留现有权限的同时使用 os.chmod 更改文件权限?

python - 如何简单地覆盖被替换元素的列表

python - PIL处理PNG的问题

python - 哈里斯角点检测器 python