Reputation: 13
I'm trying to convert png
to bmp
256 8 bits indexed colors, but I can't figure out how to set a threshold to make partial transparent pixels become transparent, original and result:
Here's my code:
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)
How to cut off this green edges?
Upvotes: 1
Views: 148
Reputation: 207798
I can't tell from your question what you actually want to do, but hopefully you can get what you want by reading the following.
#!/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')
This is DEBUG-alpha.png
:
which shows your alpha values vary between 0 and 255. You seem to want to do something with the partially transparent pixels - but I can't tell if you want to make all of them fully transparent, or all of them fully opaque or maybe just some of them. Nor do I know why you paste onto a green background if you don't want green in your output image. Anyway, look at the line that says:
newAlpha = alpha.point(lambda p: 255 if p>127 else 0)
and change it according to what you need.
Maybe you want this:
newAlpha = alpha.point(lambda p: 0 if p>0 and p<140 else 255)
Upvotes: 0