Python枕头:阈值透明度问题

问题描述 投票:0回答:1

我正在尝试将

png
转换为
bmp
256 8 位索引颜色,但我不知道如何设置阈值以使部分透明像素变得透明、原始和结果:

Image

这是我的代码:

from PIL import Image
import os

def convert_to_indexed_bmp(input_image_path, output_bmp_path):
    img = Image.open(input_image_path)

    indexed_background_color = (0, 255, 0)

    img_with_indexed_background = Image.new("RGBA", img.size, indexed_background_color)
    img_with_indexed_background.paste(img, (0, 0), img)

    img_indexed = img_with_indexed_background.convert("RGB").convert("P", palette=Image.ADAPTIVE, colors=256)

    img_indexed.save(output_bmp_path)

input_folder = "splash.png"
output_folder = "splash.bmp"


convert_to_indexed_bmp(input_folder, output_folder)

如何剪掉这个绿色边缘?

python python-3.x python-imaging-library
1个回答
0
投票

我无法从你的问题中看出你真正想做什么,但希望你能通过阅读以下内容得到你想要的。

#!/usr/bin/env python3

from PIL import Image

# Load input image
im = Image.open('z.png')

# Create lime green  output image of same size
res = Image.new('RGBA', im.size, 'lime')

# Let's analyse the alpha channel
alpha = im.getchannel('A')
alpha.save('DEBUG-alpha.png')

# Derive new alpha channel, thresholding at 127
newAlpha = alpha.point(lambda p: 255 if p>127 else 0)
 
# Now paste image with new alpha onto background and save
res.paste(im, (0,0), newAlpha)
res.save('result.png')

这是

DEBUG-alpha.png
:

显示你的 alpha 值在 0 到 255 之间变化。你似乎想对部分透明的像素做一些事情 - 但我不知道你是否想让它们全部完全透明,或者全部完全不透明,或者也许只是其中一些。如果您不想在输出图像中出现绿色,我也不知道为什么要粘贴到绿色背景上。不管怎样,看看那行:

newAlpha = alpha.point(lambda p: 255 if p>127 else 0)

并根据您的需要进行更改。

© www.soinside.com 2019 - 2024. All rights reserved.