I am trying to convert images to grayscale using Python/Pillow. I had no difficulty in most images, but then, while testing with different images, I found this logo from the BeeWare project, that I know that has been further edited with some image editor and recompressed using ImageOptim.
The image has some kind of transparency (in the whole white area around the bee), but black color gets messed up. Here is the code:
#/usr/bin/env python3
import os
from PIL import Image, ImageFile
src_path = os.path.expanduser("~/Desktop/prob.png")
img = Image.open(src_path)
folder, filename = os.path.split(src_path)
temp_file_path = os.path.join(folder + "/~temp~" + filename)
if 'transparency' in img.info:
transparency = img.info['transparency']
else:
transparency = None
if img.mode == "P":
img = img.convert("LA").convert("P")
try:
img.save(temp_file_path, optimize=True, format="PNG", transparency=transparency)
except IOError:
ImageFile.MAXBLOCK = img.size[0] * img.size[1]
img.save(temp_file_path, optimize=True, format="PNG", transparency=transparency)
I also tried this:
png_info = img.info
if img.mode == "P":
img = img.convert("LA").convert("P")
try:
img.save(temp_file_path, optimize=True, format="PNG", **png_info)
except IOError:
ImageFile.MAXBLOCK = img.size[0] * img.size[1]
img.save(temp_file_path, optimize=True, format="PNG", **png_info)
Using either approach, all the black in the image becomes transparent.
I am trying to understand what I am missing here, or if this is some bug or limitation in Pillow. Digging a little through the image palette, I would say that transparency is in fact assigned to the black color in the palette. For instance, if I convert it to RGBA mode, the outside becomes black. So there must be something else that makes the outside area transparent.
Any tips?