Python-Imaging-Library 仅粘贴具有 255 alpha 的图像部分
Python-Imaging-Library only paste imageparts with 255 alpha
我想使用 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 通道毫无用处。
如果你以后不需要它,你也可以加载背景:
background = Image.new('RGB', (825, 1125), (0, 0, 0))
我想使用 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 通道毫无用处。 如果你以后不需要它,你也可以加载背景:
background = Image.new('RGB', (825, 1125), (0, 0, 0))