Python pillow:阈值透明度问题

1 投票
1 回答
67 浏览
提问于 2025-04-14 17:00

我正在尝试把 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)

我该怎么去掉这些绿色的边缘呢?

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

在这里输入图片描述

这个图显示了你的透明度值在0到255之间变化。你似乎想对那些部分透明的像素做点什么,但我不清楚你是想把它们全部变得完全透明,还是全部变得完全不透明,或者只是想处理其中的一部分。而且我也不知道你为什么要在绿色背景上粘贴,如果你不想在输出的图像中看到绿色的话。无论如何,看看下面这行:

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

然后根据你的需要进行修改。

在这里输入图片描述

也许你想要的是这个:

newAlpha = alpha.point(lambda p: 0 if p>0 and p<140 else 255)

在这里输入图片描述

撰写回答