Python-Imaging-Library仅粘贴255 alpha的图像部分

时间:2016-12-10 21:27:54

标签: python python-imaging-library

我想使用python paste库的PIL将图像粘贴到黑色背景中。

我知道我可以将图像本身用作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

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,那么 这是一个可能的解决方案。它产生了 一个专用的面具,用于粘贴:

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通道相当无用。 如果您以后不需要它,您还可以加载背景:

background = Image.new('RGB', (825, 1125), (0, 0, 0))