【发布时间】:2016-03-08 04:44:17
【问题描述】:
如何用指定的背景颜色替换任何图像(png、jpg、rgb、rbga)的 alpha 通道?它还必须适用于没有 Alpha 通道的图像。
【问题讨论】:
标签: python python-imaging-library pillow alphablending
如何用指定的背景颜色替换任何图像(png、jpg、rgb、rbga)的 alpha 通道?它还必须适用于没有 Alpha 通道的图像。
【问题讨论】:
标签: python python-imaging-library pillow alphablending
这可以通过检查图像是否透明来完成
def remove_transparency(im, bg_colour=(255, 255, 255)):
# Only process if image has transparency (http://stackoverflow.com/a/1963146)
if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
# Need to convert to RGBA if LA format due to a bug in PIL (http://stackoverflow.com/a/1963146)
alpha = im.convert('RGBA').split()[-1]
# Create a new background image of our matt color.
# Must be RGBA because paste requires both images have the same format
# (http://stackoverflow.com/a/8720632 and http://stackoverflow.com/a/9459208)
bg = Image.new("RGBA", im.size, bg_colour + (255,))
bg.paste(im, mask=alpha)
return bg
else:
return im
【讨论】:
.getchannel('A') 而不是 .split()[-1]。
bg.convert('RGB')转换为RGB
我建议使用Image.alpha_composite。
如果 png 没有 alpha 通道,此代码可以避免 tuple index out of range 错误。
from PIL import Image
png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255,255,255))
alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)
我还建议您使用image.show() 检查这两个结果。
此答案归功于shuuji3 和其他帮助在this other question 中建立大量答案库的人。
【讨论】:
我用用户 tutuDajuju 更新了Vincius M's code,建议制作 [height, width, 3] 矩阵(不是 [height, width, 4]):
from PIL import Image
import numpy as np
png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255,255,255))
alpha_composite = Image.alpha_composite(background, png)
# if you check the matrix dimension, channel, it would be still 4.
h, w, channel = np.asarray(alpha_composite)
alpha_composite_3 = alpha_composite.convert('RGB')
# if you check the matrix dimension, channel, it would be 3.
h, w, channel = np.asarray(alpha_composite_3)
【讨论】: