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

标签 python python-imaging-library

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

相关文章:

python - ImageChops.difference 不适用于简单的 png 图像

python - 使用 src/target 坐标使用 Python PIL 进行透视变换

python - 根据两个图像的差异创建Alpha叠加图像

python - 物体碰撞时播放声音

python - 是否可以使用 python 解决演绎推理测试问题?

python - 获取两个输入时间之间的随机时间的数据帧 pandas python

python:从PNG转换为JPG而不使用PIL将文件保存到磁盘

python - 如何统计图像中特定尺寸的粒子数量?

python - 在 Python 3 中以字节形式访问 sys.argv

python - scipy 的曲线拟合不适用于正弦曲线?