gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:06 27 4
gpt4 key购买 nike

我想使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com