我想使用 python PIL
库的 paste
将图像粘贴到黑色背景。
我知道我可以使用图像本身作为 alpha 蒙版,但是我只想得到图像中 alpha 值为 255 的部分。
这怎么可能?
这是到目前为止我的代码:
import PIL
from PIL import Image
img = Image.open('in.png')
background = Image.new('RGBA', (825, 1125), (0, 0, 0, 255))
offset = (50, 50)
background.paste(img, offset, img) #image as alpha mask as third param
background.save('out.png')
我在官方找不到任何东西,但不好documentation
最佳答案
如果我正确理解你的问题,那么 这是一个可能的解决方案。它生成 专用面膜,用于粘贴:
from PIL import Image
img = Image.open('in.png')
# Extract alpha band from img
mask = img.split()[-1]
width, height = mask.size
# Iterate through alpha pixels,
# perform desired conversion
pixels = mask.load()
for x in range(0, width):
for y in range(0, height):
if pixels[x,y] < 255:
pixels[x,y] = 0
# Paste image with converted alpha mask
background = Image.new('RGBA', (825, 1125), (0, 0, 0, 255))
background.paste(img, (50, 50), mask)
background.save('out.png')
请注意,背景图像的 Alpha channel 相当无用。 如果以后不需要它,您还可以加载背景:
background = Image.new('RGB', (825, 1125), (0, 0, 0))
关于Python-Imaging-Library 仅粘贴 255 alpha 的图像部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41080497/